0

I've created a function that handles changes in the width of the window by changing the menu and header to whatever necessary at that point. I've created a function and I call that function by doing the following:

$(window).resize(headerFn);

This works fine. But, if I'd resize from 850 to 860 pixels the following function would get executed 5 times instead of just once:

        $('html').click(function() {
        console.log('html was clicked to close the menu. ' + width);
        header.hide();
        mobile.show();
        search.show();
        header.css('width', 0);
    });

This means that even if the view is wider than 980 px (which would be the difference between 2 versions of the header) it will completely hide the header. It somehow remembers every single width the window has had and executes it as often as it has been changed. An example:

On page load and clicking somewhere without resizing will console log this with a loading width of 876px:

html was clicked to close the menu. 876

if I resize it to 892px and click again it returns this:

html was clicked to close the menu. 876
html was clicked to close the menu. 878
html was clicked to close the menu. 880
html was clicked to close the menu. 882
html was clicked to close the menu. 884
html was clicked to close the menu. 886
html was clicked to close the menu. 888
html was clicked to close the menu. 890
html was clicked to close the menu. 892

Anyone has any idea why it executes as often as the screen has been resized?

Thanks a lot!

  • 1
    Because every time the window is resized the function is fired, and the window is resized every time the dimension of the window is changed by so much as a pixel; whether the browser's native event-handling is set to fire that resize event by every pixel change, or by every two-pixels, is a matter for the browser developers. – David Thomas Dec 28 '17 at 14:15

1 Answers1

1

this might be because you add that click event for the html tag on every screen resize event!?

i can't see your whole file. so it's just guessing.

it's a good practice to fire functions after the resize has finished for some milliseconds to save cpu power like this:

var resizeId;
$(window).resize(function() {
    clearTimeout(resizeId);
    resizeId = setTimeout(doneResizing, 500);
});

function doneResizing() {
    // do stuff after resize
}
André Kelling
  • 1,575
  • 16
  • 23