cCe.jbc
cCe.jbc

Reputation: 117

$(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.

Upvotes: 5

Views: 5193

Answers (1)

Zenel Rrushi
Zenel Rrushi

Reputation: 2366

The problem with mobile devices is that they have the browser toolbars that are hidden when you scroll and this leads 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 if the correct window width is the same or 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 changed');
    }
});

Upvotes: 9

Related Questions