0

When I run this one time it gives me window resized :2 why this so and how can get 1 when i resize window only one time.

<script src="jquery-2.2.1.min.js">

</script>
<script>

var x=0;
$(document).ready(function()
{
           $(window).resize(function()
           {
               $("span").text(x += 1);
           });        
});    
</script>
</head>    
<body>
<p>Window resized :<span></span></p>
</body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Shanky
  • 85
  • 1
  • 10

1 Answers1

1

Why it triggers twice

This answers your question: Why does the jQuery resize event fire twice?

I added a fiddle that confirms it triggers twice on scale down in chrome, once on scale up.In Edge it triggers once on both scale up and down.

var x=0;

$(window).resize(function()
{
  console.log(x +=1);
});        

Fiddle

How to make it trigger once

var x = 0,
    y = 0;
$(window).resize(function() {
    clearTimeout(y);
    y = setTimeout(finishedRezise, 100);
});

function finishedRezise(){
  console.log(x += 1);  
}

Fiddle

The javascript function SetTimeout() prevents the function from being executed by a specified number of milliseconds. clearTimeout() clears the timer from SetTimout() and takes the returned value from setTimeout() as parameter, and it needs to be defined globally. See W3Schools documentation W3School

Community
  • 1
  • 1
David
  • 703
  • 11
  • 24
  • actully its working fine in google chrome, but not in firefox. Anyway thanx – Shanky Mar 10 '16 at 09:31
  • Updated my answer with fix that I tested working in Firefox, Chrome and Edge – David Mar 10 '16 at 09:35
  • yes now its working in all browsers but could you explain me what you did in this code, I can not understand this why you took x, y,clearTimeout and all – Shanky Mar 10 '16 at 09:39