1

I've got the below function for the window resize. My question is how do I make it work on window resize as well as page orientation is changed?

    $(window).resize(function() {
        if(this.ab) clearTimeout(this.ab);
        this.ab = setTimeout(function() { 
            $(this).trigger('winresized');
        },1000);
    });
    $(window).on('winresized', function() {

    });
Becky
  • 5,467
  • 9
  • 40
  • 73

1 Answers1

1

You can use a combination of resize and orientationchange event:

$(window).on("resize orientationchange", function() {
    // Fires on both resize & orientation change
    if(this.ab) clearTimeout(this.ab);
    this.ab = setTimeout(function() { 
        $(this).trigger('winresized');
    },1000);
});
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • thanks. So `$(window).resize(function() {` needs to be updated to `$(window).on("resize orientationchange", function() {` ?. and the rest remains the same? Is that what you've said in your answer? – Becky Jun 04 '15 at 12:06
  • Yup, exactly. That will trigger the `winresized` event for both – CodingIntrigue Jun 04 '15 at 12:07
  • Yep.. I did test it while waiting for your reply. it works - brilliant. thanks :) – Becky Jun 04 '15 at 12:12
  • One more thing to add. How do I also write the above using window.addEventListener ? – Becky Jun 04 '15 at 12:20
  • 1
    `window.addEventListener("orientationchange", function() {});` - note though that you can't add multiple events like `"resize orientationchange"` - you need to make multiple `addEventListener` calls – CodingIntrigue Jun 04 '15 at 12:21
  • thanks again. So `$(window).on("resize orientationchange", function() {` should be replaced with `window.addEventListener("orientationchange", function() {` ? Is that it? – Becky Jun 04 '15 at 12:23
  • Exactly. Likewise `window.addEventListener("resize", function() {});` – CodingIntrigue Jun 04 '15 at 12:23
  • I came across [this post](http://stackoverflow.com/questions/23996726/will-window-resize-fire-on-orientation-change). He says using `window.addEventListener("resize", function() {` is more secure? Any ideas on that? – Becky Jun 04 '15 at 12:24