S
S
savage_me2018-03-06 20:14:22
JavaScript
savage_me, 2018-03-06 20:14:22

Question for understanding Javascrpipt - why the event $('#id').click(function(){...}); works twice?

Here's the code. First, we run the function when the window is loaded, then when the window is resized.

<html><head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script>
$( window ).on( "load", function() {
  ff();
});
$(window).resize(function() {
    clearTimeout(this.id);
    this.id = setTimeout(ff, 1500);
});

function ff() {
var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
if( windowWidth <= 500 ) $( "#idx" ).click(function() { alert(windowWidth); });
if( windowWidth > 500 ) $( "#idx" ).click(function() { alert(windowWidth); });
}
</script>
</head><body><img src="https://assets.servedby-buysellads.com/p/manage/asset/id/32054" id="idx">
</body></html>


The page initially loads in a browser with a screen width of less than 500 pixels. Then the "Expand" button is pressed on the top right and the browser window expands to full screen - the screen width becomes more than 500 pixels. Already in the maximized screen, a click is made on the element with id="idx" and two alerts are triggered - one first shows that the screen width is less than 500 pixels, and the second - that it is more. That is, when the screen size is small, something like registering the $( "#idx" ).click(function() {}); event happens, and it fires even when the screen width has already changed.

Why is that? It is necessary that the event would work on the current screen size.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question