beyevaza
beyevaza

Reputation: 13

Resizing event not firing when page is loading

window.addEventListener('resize', function(){
    if (document.documentElement.clientWidth < 500) {
        // My Code.
    }
}, false);

"My Code" takes effect only if I change the clientWidth(resize browser window, for example) after the page is loaded, even if the clientWidth condition is true from beginning.

My goal is to fire "My Code" if the clientWidth condition is true, both: 1) if clientWidth changed after the loading(browser resize) 2) When the page is loading

Upvotes: 1

Views: 828

Answers (3)

simey.me
simey.me

Reputation: 2207

just wrap your code in a function, call it once during page initialization, and every time your event runs (resize/resizing)

function checkWidth( width ) {
  if ( document.documentElement.clientWidth < width ) {

    // my code

  }
}

checkWidth( 500 );

window.addEventListener('resize', function(){
  checkWidth( 500 );
}, false );

Essentially exactly what @nem commented :)

Upvotes: 0

Quentin Roger
Quentin Roger

Reputation: 6538

You can try this :

function myFunction() {
    if ($(window).width() < 500) {
        alert('<500')
    }
}

$(document).ready(function(e) {
    myFunction();
});

$(window).resize(function(e) {
   myFunction();
});

Note that resize event handler is set and also triggered so the action is fired on document ready.

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You could use dispatchEvent to trigger the event. Also notice the event name is "resize". I am not using jQuery as your original post did not include any jQuery code.

setTimeout(function () {
  window.dispatchEvent(new Event('resize'));
  }, 3000);

var called = 1;
window.addEventListener('resize', function(){
   // if (document.documentElement.clientWidth < 500) { //this demo is to show the resize is getting called
        document.getElementById('logger').innerHTML = 'resize called ' + called++;
   // }
}, false);
<div id="logger"></div>

Reference: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Upvotes: 2

Related Questions