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.
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.
Share Improve this question edited Nov 5, 2016 at 10:56 cCe.jbc asked Nov 5, 2016 at 10:14 cCe.jbccCe.jbc 1171 silver badge10 bronze badges 6- Are you sure this is happening on scroll? It doesn't do it for me. Fiddle – putvande Commented Nov 5, 2016 at 10:19
- Maybe you've another scroll event listener what is triggering resize event manually! – Khorshed Alam Commented Nov 5, 2016 at 10:21
- It doesn't appends any p tag on scroll. Can you post your remaining codes, if you have something else added with this. – frnt Commented Nov 5, 2016 at 10:24
- Sorry, I forgot to mention it was only happening on mobile devices @putvande . Post edited. – cCe.jbc Commented Nov 5, 2016 at 10:57
- @frnt this is only an example so it is the only code I am using. See my ment above. – cCe.jbc Commented Nov 5, 2016 at 10:58
1 Answer
Reset to default 9The 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');
}
});