Why is the variable not registering as true to make the second if statement work?

70 Views Asked by At

I am trying to create a slider menu, which slides up from bottom (footer) to top, and when clicked on, goes back to the bottom (footer). The code I have works fine with the first if statement, it does not register the var SlideUp == true and therefore, the slider does not go back down when clicked on.

This is on my JS file:

$(document).ready(function(){

   var sliderUp = false;
     if (sliderUp == false) {
        $("#slider").click( function(){
           $(this).animate({height:'100%'},200);
           sliderUp = true;
           console.log('pullUp');
           $('.firsts').fadeOut(100);
        }); 
     } 


 if (sliderUp == true) {
    $("#slider").click( function(){
       $(this).animate({height:'50px'},200);
       sliderUp = false;
       console.log(sliderUp);
       console.log('pullDown');
       $('.firsts').fadeIn(100);
   });  
 }
 });

This is my CSS:

#slider{
    background: orange;
    color: white;
    height: 50px;
    text-align: center;
    position: absolute;
    bottom: 0;
    width: 100%;
 }
2

There are 2 best solutions below

0
Amogh Hegde On BEST ANSWER

You are putting conditions outside the events Try This:

$(document).ready(function() {

  var sliderUp = false;
  $("#slider").click(function() {
    if (sliderUp == false) {
      $(this).animate({
        height: '100%'
      }, 200);
      sliderUp = true;
      console.log('pullUp');
      $('.firsts').fadeOut(100);
    } else {
      $(this).animate({
        height: '50px'
      }, 200);
      sliderUp = false;
      console.log(sliderUp);
      console.log('pullDown');
      $('.firsts').fadeIn(100);
    }
  });
});

0
swathi_sri On

Instead of making the code complicated with if and else you can use .toggle to achieve your requirement.

$('#slider').toggle(
    function(){
        $(this).animate({height:'100%'},200);
        console.log('pullUp');
        $('.firsts').fadeOut(100);
    },
    function(){
        $(this).animate({height:'50px'},200);
        console.log('pullDown');
        $('.firsts').fadeIn(100);
    }
);