简体   繁体   中英

Function with arguments not working with window.onblur and onfocus

The following code isn't working

window.onfocus = welcome("John Doe");
window.onblur = bye("John Doe");

function welcome(name) {
    $("p").append("Welcome back " +name+ " <br>");
}

function bye(name) {
    $("p").append("Good bye " +name+ " see you soon <br>");
}

However I noticed that this code works for custom functions that dont take any argument. See code below. The following code is working:

window.onfocus = welcome; //No Argument here so this code works
window.onblur = bye; //Same here... No argument for the function

function welcome(name) {
    $("p").append("Welcome back John Doe <br>");
}

function bye(name) {
    $("p").append("Good bye John Doe see you soon <br>");
}

I am new to jquery and javascript and this stuff is confusing me. Can someone please explain why exactly it isn't working. and how can I make a custom function with arguments work with window.onfocus and onblur method. (reason for working or not working is more important for me as I want to understand the mechanics rather than cramming up the syntax)

()(parenthesis) after function-name will invoke/call the function by the time you are assigning the handler to the events.

Use anonymous-function instead of invoking-function and invoke/call the function inside it.

In your second(working) example, you are assigning function definition(body of the function) as a event-handler hence function is invoked after particular event.

 window.onfocus = function() { welcome("John Doe"); }; window.onblur = function() { bye("John Doe"); } function welcome(name) { $("p").append("Welcome back " + name + " <br>"); } function bye(name) { $("p").append("Good bye " + name + " see you soon <br>"); } 

Try $(window).focus() and $(window).blur() event:

 $(function() { $(window).focus(function() { welcome("John Doe"); }); $(window).blur(function() { bye("John Doe"); }); }); function welcome(name) { $("p").append("Welcome back John Doe <br>"); } function bye(name) { $("p").append("Good bye John Doe see you soon <br>"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <p></p> 

Your code is working fine. Add JavaScript file on page.

 window.onfocus = welcome("John Doe"); window.onblur = bye("John Doe"); function welcome(name) { $("p").append("Welcome back " + name + " <br>"); } function bye(name) { $("p").append("Good bye " + name + " see you soon <br>"); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <p></p> 

View on JSFiddle

Both code is working fine for me. Try to put jQuery code in body section.

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