Reputation: 53
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)
Upvotes: 1
Views: 411
Reputation: 1150
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>
Upvotes: 0
Reputation: 19
Both code is working fine for me. Try to put jQuery code in body section.
Upvotes: 0
Reputation: 36609
()(parenthesis)
afterfunction-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>");
}
Upvotes: 1
Reputation: 5039
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>
Upvotes: 1