Sam
Sam

Reputation: 347

How to Slide an Element Horizontally

I need to add a else statement to a click function so the .container disappears when the button is clicked a second time.

function() {

    $('div.container').css({'width':'350px'});

    } else {

    $('div.container').css({'width':'0'});

     }

});

Edit:

I need the element to toggle slide left on a button click.

Upvotes: 0

Views: 620

Answers (3)

Ahmad Maleki
Ahmad Maleki

Reputation: 1495

toggle() Method:

Using jQuery you can use the toggle() method.

The toggle() method toggles between hide() and show() for the selected elements.

So you can simply have

$('#buttonId').on('click', function(){
    $('#container').toggle();
})
div{
  background-color: #a8a8ff;
  height: 100px;
  width: 350px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonId">Click Me!</button>
<div id="container" class="long"></div>

toggleClass() Method:

According to your comment if you want to toggle a style (e.g: width) it's better and cleaner to define a class for your style and use toggleClass() method.

The toggleClass() method toggles between adding and removing the class.

$('#buttonId').on('click', function(){
    $('#container').toggleClass('long short');
})
div{
  background-color: #a8a8ff;
  height: 100px;
}

.long{
  width: 350px;
}

.short{
  width: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonId">Click Me!</button>
<div id="container" class="long"></short>

animate() Method:

Based on your second commend you can use the animate() method to simulate the slide functionality.

The jQuery animate() method lets you create custom animations.

To slide the element to left: (Credits to JQGeek for his answer here.)

$('#buttonId').on('click', function(){
    $('#container').animate({width:'toggle'},350);
})
div{
  background-color: #a8a8ff;
  height: 100px;
  width: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonId">Click Me!</button>
<div id="container"></div>

Upvotes: 2

Ajay Kumar
Ajay Kumar

Reputation: 1352

You can do like this

$(document).on('click', 'button_selector', function () {
    if (true) {
        // your code
    }
    else{
        // your code
    }
});

suggestion

you can use toggle for this

$(document).on('click', 'button_selector', function () {
    $('div.container').toggle();
});

Upvotes: 1

Jinesh
Jinesh

Reputation: 1580

You can follow my code

$(function(){
   var firstClick = 0;
   $("button").click(function(){
       firstClick++;
       if(firstClick==2)
          $('div.container').hide();
       else
         $('div.container').show();
   });
})

Upvotes: 0

Related Questions