Jake Hills
Jake Hills

Reputation: 448

jquery - toggle animation

I've got a sidebar that when you click a button the sidebar slides left 250px, when you click the same button I want it to slide back 250px - I am currently using jquery .toggle but as I'm fairly new to jquery I need to ask what I'm doing wrong?

http://jsfiddle.net/zfc3V/13/

(function($){
  $('a.mobile-menu-icon').toggle(
    function(){
      $('#sidebar').animate({left: '250px'}, 700);
    },
    function(){
      $('#sidebar').animate({left: '0px'}, 700);
    });
});

I'm using 1.9.1 (before .toggle was removed) and UI is not an option.

Thanks.

Upvotes: 0

Views: 1520

Answers (4)

Simon Arnold
Simon Arnold

Reputation: 16157

Use CSS instead
JS:

$('a.mobile-menu-icon').on("click", function() {
  $('#sidebar').toggleClass('show');
});

Css:

#sidebar {
  left: 0;
  -webkit-transition: all .7s ease;
  -moz-transition: all .7s ease;
  -ms-transition: all .7s ease;
  -o-transition: all .7s ease;
  transition: all .7s ease;
}

#sidebar.show {
  left: 250px;
}

Upvotes: 0

XCS
XCS

Reputation: 28137

  1. Shorthand for document.ready is $(function(){ }); not function()
  2. If you want something to happen on click you have to add a click event handler.
  3. You can use CSS transitions for the animation instead of jQuery.

    $(function($){ $('a.mobile-menu-icon').on('click',function(){ $('#sidebar').toggleClass('active'); }); });

http://jsfiddle.net/zfc3V/19/

Upvotes: 2

ayyp
ayyp

Reputation: 6598

The .toggle() event was deprecated, and does not work in that function anymore. By adding a data-open property to your <a> it is very easy to create such a function. Here is the code that would do so. The only change that is required is making your <a> like so: <a href="#" class="mobile-menu-icon" data-open="true">Click to toggle</a>

$('a.mobile-menu-icon').click(function() {
    var x = $(this).data('open');
    $('#sidebar').animate({left: (x) ? '250px' : '0px'}, 700);
    x ? $(this).data('open', false) : $(this).data('open', true);
});

Here's a fiddle link: http://jsfiddle.net/zfc3V/18/

Upvotes: 0

Edorka
Edorka

Reputation: 1811

but the event is "click", not toggle. Maybe with this:

$('a.mobile-menu-icon').click( function(event){
 var trigger = $(this);
 if( trigger.hasClass("expanded")){
   trigger.removeClass("expanded");
   $('#sidebar').animate({left: '250px'}, 700);
 } else {
   trigger.addClass("expanded");
    $('#sidebar').animate({left: '0px'}, 700);
 }
});

Upvotes: 1

Related Questions