skip to Main Content

How can i call a simple function in Javascript, for example:

function doSmt() {
   alert("hello world")
}

whenever the user is going to resize the window in any way. So if he for example just resize it with the mouse, or if he zoom into or out the website.

I already tried:

window.onresize = doSmt()

as it stands on some websites, but that doesnt work.

2

Answers


  1. You need to pass the function itself, not call it:

    window.onresize = doSet;

    Login or Signup to reply.
  2. You could do it in two ways:

    The first one is almost the same as you already have, but you’re calling the function instead of binding it:

    window.onresize = doSmt;
    

    The second way allows you to get the event as well:

    window.onresize = function ( event ) {
        doSmt();
    }
    

    Extra

    User Silviu Burcea added the useful information that when your doSmt function accepts parameters it can also use the event parameter:

    function doSmt(event) {
        alert("Hello world");
    }
    
    window.onresize = doSmt;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search