Reputation: 999
I am attempting to make a slide out menu which has a button to slide in/out classed 'open'.
When the open button is clicked jQuery does the slide in and adds the class 'close' and removes class 'open' - this works fine.
Then when 'close' is clicked I am attempting to slide out, add class 'open' and remove class 'close' to take it back to it's original state.
But the close does not work, it adds the close class but the close function is not working on click, maybe you can't have a function on class that has been added...?
Any help much appreciated.
$(".open").click(function(){
$('.mainmenu').stop().animate({left: '0'}, 800);
$( ".open" ).addClass( "close" );
$( ".open" ).removeClass( "open" );
});
$(".close").click(function(){
$('.mainmenu').stop().animate({left: '-180'}, 800);
$( ".close" ).addClass( "open" );
$( ".close" ).removeClass( "close" );
});
Upvotes: 0
Views: 920
Reputation: 11338
$("body").on('click','.open', function(){
$('.mainmenu').stop().animate({left: '0'}, 800);
$( ".open" ).removeClass( "open" ).addClass( "close" );
});
$("body").on("click",".close", function(){
$('.mainmenu').stop().animate({left: '-180'}, 800);
$( ".close" ).addClass( "open" ).removeClass( "close" );
});
Easier way, by using of on() method, for elements that aren't present on page load... Fiddle: http://jsfiddle.net/urjsw5z1/2/
Upvotes: 2
Reputation: 353
Assuming your button has the "open" class at the beginning. Your javascript code will add the callback for the "open" class, and will do nothing for "close" class because there's no component with such class yet. A work around is to do the following:
function open() {
$('.mainmenu').stop().animate({left: '0'}, 800);
$( ".open" ).addClass( "close" );
$( ".open" ).removeClass( "open" );
$(".close").click(function(){
close();
});
}
function close() {
$('.mainmenu').stop().animate({left: '-180'}, 800);
$( ".close" ).addClass( "open" );
$( ".close" ).removeClass( "close" );
$(".open").click(function(){
open();
});
}
$(".open").click(function(){
open();
});
$(".close").click(function(){
close();
});
Upvotes: 1