Joe Morano
Joe Morano

Reputation: 1895

How to break up a jQuery "toggle" function into seperate "show" and "hide" functions?

I have a function that toggles the width of a div, so it has the appearence of "sliding in" from outside the boundaries of the screen

$(".slider").animate({
  width: "toggle",
}, 300, function() {
});

Is there a way I can break this into two different functions, one that shows the div and one that hides it?

So ideally if I trigger the show function when the div is already shown, nothing should happen, and vice versa.

I made a fiddle to illustrate what I'm trying to do: http://jsfiddle.net/2x816nmf/1/ . So the problem in the fiddle is that both .hide-slider and .show-slider simply toggle the width. .hide-slider should only set .slider's width to 0, and .show-slider should only set the width to the number defined in the CSS. If I press either button twice in a row, nothing should happen.

Upvotes: 1

Views: 294

Answers (1)

Mattia Nocerino
Mattia Nocerino

Reputation: 1513

You can just add a boolean variable that checks everything:

show = true;

$('.show-slider').click(function() {
    if(show == false){
  $(".slider").animate({
    width: "toggle",
  }, 300, function() {
  });
     show = true;
   }
});
$('.hide-slider').click(function() {
    if (show == true){
  $(".slider").animate({
    width: "toggle",
  }, 300, function() {
  });
        show = false;
    }
});

the show variable is first setted to true because the div is visible on start...

change your fiddle and it will work!

Upvotes: 1

Related Questions