Reputation: 269
Hello i am trying to make a responsive version of my website, and im having some trouble with the navigation, the below code work...sort of. I want it so that when the document is less than 600px it will fire the jquery code, now if i go onto the page when its more than 600px it works as intended, then i resize the window so it's less than 600px and the code fires, then i click on the navigation button that appears and the "slide toggle" keeps firing so the nav moves up then down several times before staying closed. HOWEVER if the screen size is less than 600px to begin with it works fine, and then once expanded to it's more than 600px the jquery is still there so when i click the button the code fires and again it slides up and down over and over, Anyone got any ideas :S code is based of this tutorial HERE Thanks for the help.
jQuery(document).ready(function ($){
$(window).on('resize', function () {
var windowsize = $(window).width();
if (windowsize < 600) {
$("#mmenu").hide();
$(".mtoggle").click(function() {
$("#mmenu").slideToggle(500);
$("#mmenu li").click(function(){
$("#mmenu").slideUp(500);
});
});
}
}).trigger('resize');
});
Edit: I fixed the toggle problem, issue was slideToggle, i just had to change that to slideDown, dont feel like an idiot at all for not noticing that, however it still fires when i make the screen bigger, i tried an else statement for > 600 but that didn't nothing.
Upvotes: 0
Views: 375
Reputation: 6657
Quick refresher on events using JQuery. Every time that you call .click
on a JQuery variable you're actually binding an event handler to that DOM element. So for instance this code:
$(".mtoggle").click(function() {
$("#mmenu").slideToggle(500);
$("#mmenu li").click(function(){
$("#mmenu").slideUp(500);
});
});
This code is binding a click handler to the #mmenu li
element every time you click an .mtoggle
element. So the #menu li
's click event will actually occur multiple times.
To solve your resize issue it sounds like you're looking for is the .unbind
method (http://api.jquery.com/unbind/). If you want to make it so there is no event handler on the .mtoggle
element when you resize to larger than 600px you'll have to call this method:
$(".mtoggle").unbind('click');
Which detaches all click
event handlers from the element.
Upvotes: 1