This (jQuery) function is invoked on jQuery(document).ready and jQuery(document).resize. It runs fine on the ready condition but on resize the events go a bit screwy. They either inherit functionality or in the case of the slideToggle seemingly fire for each resize.
(function(jQuery){
jQuery.fn.responsive = function() {
// Vars
var menuButton = jQuery('nav #menu-button');
var menuItems = jQuery('nav ul');
var menuLinks = jQuery('nav ul li a.scroll');
var viewportW = jQuery(window).width();
var viewportH = jQuery(window).height();
// Menu links
menuLinks.click(function(e){
if (viewportW > 800) {
e.preventDefault();
e.stopPropagation();
var pos = jQuery(this.hash).offset().top;
jQuery('html,body').animate({scrollTop: pos}, 1000);
} else if (viewportW < 799) {
e.stopPropagation();
menuItems.slideUp('fast'); // Hide menu on click
}
});
// Menu button
menuButton.click(function(e){
menuItems.slideToggle('fast');
//e.stopPropagation();
//e.preventDefault();
});
}
})(jQuery);
What am I doing wrong? I have tried to kill event propagation but to no avail.
EDIT:
This runs after:
// Doc ready
jQuery(document).ready(function() {
// Run functions
jQuery().responsive();
});
// On resize
jQuery(window).resize(function(){
jQuery().responsive();
});
When you call one of the callback registation functions likes
$(someElement).click(...), you are actually adding a handler for that event. If you call the function twice with the same, the handler gets called twice. Do demonstrate, try this html page (with jquery.js in the same page):On first loading the page, it behaves as expected, but then after resizing the window, clicking “Click me” gets more than one “click!”.
The only reason you would have for re-registering a handler is if the respective elements have been destroyed and re-created.
If this is happening, and it’s not convenient to attempt to reliably re-register the handlers when necessary, consider using delegated events or .live().
Also note the .off() function which can remove all of the handlers on a set of elements.
Lastly, you should probably change
to
adding to
jQuery.fnadds functions that can be called from jQuery objects, i.e. allowing, say,For some reason these functions are also added to the
jQueryobject itself, so it still works, but the latter makes the function’s purpose more clear and keeps the jQuery class clean.