cCe.jbc cCe.jbc - 1 month ago 22
jQuery Question

$(window).resize() executes when scrolling on mobile devices

For example:

HTML

<div><p>A lot of text that goes off the page so you have to scroll down.........</p></div>


JavaScript

$(window).resize(function(){
$("div").append("<p>appended</p>");
});


This works and appends the paragraph as expected on resize, but it is also appended when I scroll down. This means when I get to the end of the original text there is about 20 appended paragraphs.

This is only happening on mobile devices (so far I've checked Chrome, Safari and Firefox), not on desktop browsers.

Is there a way to stop this happening and have the paragraph appended only when the window (that you see) is resized?
Or maybe only have the code within the resize execute every so often?

Thanks.

Answer

The problem with mobile devices is that they have the browser toolbars that are hidden when you scroll and this leeds to screen change (activates the resize event) and this means that you have to make some validations to your code and detect why was the resize event fired.

One way I have used is by saving the window width and checking is the correct window width was the same or iot changed. If it changes then it means that the append should happen (in your case).

var dwidth = $(window).width();

$(window).resize(function(){
var wwidth = $(window).width();;
if(dwidth!==wwidth){
    dwidth = $(window).width();
    console.log('width change Here to work');
    }
});