Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
The following code isn't working

Code:
JavaScript
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:

Code:
JavaScript
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 snippets)

What I have tried:

JavaScript
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>");
}
Posted
Updated 21-Jun-16 22:00pm

1 solution

First of all there is a very huge different between these two:
JavaScript
var v1 = welcome("member");
var v2 = welcome;

Furthermore, onfocus is a attach point for a event handler function. The signature of that function already fixed without parameters, and that because of the way it gets its parameters - via the global Event object...

To be of further service, you have to explain what is your purpose...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900