简体   繁体   中英

Invoke function with $(window).resize and on initial page load

Hey guys I am trying to invoke my function when the page is initially loaded and when the window is resized however I am unsure how this can be done. I currently have the following code:

$(window).resize(function(){
  var offerPageMediaQuery = window.matchMedia('all and (max-width: 969px)');
  if(mq.matches) {
      $('.mobileposition').append($('.offer-key-info'));
  } else {
      $('.offer-content').append($('.offer-key-info'));
  }
});

As you can see when the page is resized this function will run however I also want it to run on the initial load of the page also.

Any idea how this can be done? Thanks

You can call resize() with no parameter to raise the event too:

$(window).resize(function(){
    var offerPageMediaQuery = window.matchMedia('all and (max-width: 969px)');
    $(mq.matches ? '.mobileposition' : '.offer-content').append($('.offer-key-info'));
}).resize(); // call here

Alternatively you could extract the logic to a function and call it under both events:

function foo() {
    var offerPageMediaQuery = window.matchMedia('all and (max-width: 969px)');
    $(mq.matches ? '.mobileposition' : '.offer-content').append($('.offer-key-info'));
}

$(window).resize(foo);
foo();

I would also suggest that it may be better to instead do this using CSS media queries instead of relying on JS. You could have a copy of the .offer-key-info element in the DOM in both places and the hide/show the required one depending on the media query which matches the required resolution.

function myFunction(){
var offerPageMediaQuery = window.matchMedia('all and (max-width: 969px)');
  if(mq.matches) {
      $('.mobileposition').append($('.offer-key-info'));
  } else {
      $('.offer-content').append($('.offer-key-info'));
  }
}

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

$(window).load(function(){
   myFunction();
});
$(document).ready(function(){
   myFunction();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM