3

Let’s say I had JavaScript that runs when the window is resized, but if you use window.load or document.ready it doesn’t work. (My situation).

I’m not looking for window.load or document.ready (jQuery) alone... I’m looking to literally fake a window resize... to make the resize-only scripts load.

How can I fake a window resize, without resizing the window?

oatmealNUGGY
  • 775
  • 1
  • 6
  • 22
  • 1
    1. write function 2. assign function to `window.onresize` 3. call function elsewhen (by either its name, or `window.onresize()`) –  Dec 20 '18 at 15:13

2 Answers2

4

Do not fake anything if possible. That makes your code harder to read and understand. Restructure your code like this:

function onResize(e)
{
    // does window.resize stuff
}

$(document).load(function(e){
     // when the document is loaded, do resize stuff as well
     onResize(e);
});

// add event listener to window.resize
$(window).resize(onResize);
Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26
3

Just call $(window).trigger('resize'); it will trigger a resize and whatever you register on the resize will be called.

$(window).resize(function() {
  alert("Work done when resize is being called");
});

$(window).resize(function() {
  alert("More work");
});

$("*").click(function(){
  alert("Triggering resize");
  $(window).trigger('resize');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click anywhere to trigger the resize
Itay Gal
  • 10,706
  • 6
  • 36
  • 75