I can't seem to get window.onblur to work properly.
window.onblur = console.log('blur');
When the listener is applied to the window, it just runs when the page is loaded, but not when the window looses focus.
Ryudice has told you what to do, but didn't explain why it didn't work your way. Understanding the mechanics of it will help you work out how to proceed further.
The reason is that your original code is running the console.log('blur') command immediately, and using the return value of that call as the window onblur event.
The return value of console.log() varies between browsers, but for the sake of argument, lets say it returns a boolean true value. This means that your original code is the equivalent of writing this:
window.onblur = true;
Which clearly isn't going to work as you expect.
What you need is for window.onblur to be set to a function that will be called each time the onblur event is triggered. This is achieved by wrapping the code in a function() {}, as per Ryudice's answer.
You can also achieve it in simple cases by not supplying the brackets on the function name you want to call. But this method only works if you don't have any arguments you want to pass to the function, so wouldn't be suited to your console.log example.
Hope that helps. If you're still puzzled, there's lots of resources on the web. Try googling for phrases like "javascript passing functions as arguments", and see what comes up.
window.onblur = function() { console.log('blur'); }
window.onblur = () => console.log( "blur" );
Related
I'm facing a weird issue. The console.log() outside the onload function works, but the console.log() inside doesn't work... Would it mean that my page never fully loads ? I had a look at the developer tools of Chrome and it shows me that the page is loaded, so I don't really understand... (here is a screen of the devtool)
Here is my code:
console.log("hello1");
window.onload = function()
{
console.log("hello2");
};
(I'm using this in a WordPress website, but I don't think it changes anything)
Thanks in advance,
ArbreMojo.
Some other code is probably assigning another function value to the window.onload method, so it basically overrides your assignment.
Instead of window.onload = function you can do:
window.addEventListener('load', function() {
console.log('loaded')
})
which allows attaching an arbitrary number of handlers for that event. This ensures nothing can override your callback function.
See: EventTarget.addEventListener for more info.
Why can’t I bind a function () to the onload event and the resize event the same way?
I want to bind my own functions to javascript’s onresize and onload events.
This is test code in a .JS file.
I made it work by using two different ways to bind my functions to the events.
And it works well.
window.addEventListener('resize', function() {
alert (“Hi from resize”);
}
window.onload = function () {
alert (“Hi from onload”);
}
However, when I try to use the same way to bind them, one always fails. I.e. Neither of these work:
window.resize = function () {
alert (“Hi from resize”);
}
window.addEventListener('onload', function() {
alert (“Hi from onload”);
}
I’ve found endless posts on how to make specific examples work one way or the other.
But I can’t find anything that hints at why the same way won’t work for both.
Can anyone help me figure this out:
--- Someone wrote that addEventListener () is the preferred. And that direct assignment was not. Is that true?
--- Should direct assignment still work for both events?
--- Should addEventListener () work for both?
--- Am I missing something else that I should know?
I mean the code I have works fine. It’s just inconsistent, and that always seems to indicate I’ve screwed up somewhere.
And I guess if either way is "Supposed To" work for both events I can go back and search for typos. But it would help to know which way is preferred, if either. Or I'm missing something important.
Thank you.
You have it backwards in your second block. When you're assigning to the window property, the name is on<eventname>; when you're using addEventListener() you just use <eventname>. So it should be:
window.onresize = function() {
alert("Hi from resize");
};
window.addEventListener("load", function() {
alert("Hi from resize");
});
addEventListener is preferred these days for a few reasons:
You can have multiple listeners, which all execute when the event occurs. When you assign to a property, it replaces the previous value. If you want to remove an event listener, you can use removeEventListener selectively (this requires binding to a named function, because you need to pass the same function when removing).
It can be used with custom events defined by the application; onXXX properties can only be used with standard events.
addEventListener is preferred because if you assign you will override any other event that has been assigned to that event.
the event for onload when using addEventListener is just "load"
I have a troublesome feature which probably has been answered somewhere before but i did some searching and brain totally froze. So i have this code:
function createTimeLink(){
var link = document.createElement('a');
link.id = "link_"+vooru_nr;
link.textContent = "VOOR "+vooru_nr;
link.onclick = timeHelper();
var headrow = document.getElementsByClassName("elem_"+vooru_nr);
headrow[0].textContent = "";
headrow[0].appendChild(link);
}
function timeHelper(){
console.log("clicked");
}
I create an element and try to give an onclick property to it. However if i call out function createTimeLink() in window.onload, "clicked" will be logged in the console but will not be logged each time i click the link again. How could i make it in a manner that if i click my link then something would happen? In future i would like to open a modal after clicking a link but currently it won't even display 'clicked' in console when clicking on the link.
you are setting link.onclick to the RESULT of a function call. Leave out the parentheses, and it will probably work:
link.onclick = timeHelper;
In JavaScript, functions are objects, so you can either call them (what you're usually doing with functions, that is what the parentheses do), or pass them around (in that case, you don't write parentheses!).
So these two are very different:
someFunction(); (runs the function, returns its result)
someFunction; (does not run the function)
#w3re correctly points out, that addEventListener is probably the cleanest approach. It does not change functionality here, but you may encounter examples later, where you would like to have more than one event listener.
If you haven't worked with addEventListener and its counterpart removeEventListener yet, i'd highly recommend it!
You're executing timeHelper() and assigning the result of that function to the onclick handler. On top of that, if you're working in JavaScript, the preferred method of adding events is the addEventListener() function.
So, change
link.onclick = timeHelper();
to
link.addEventListener("click", timeHelper);
I want bind to an event but I am not sure if its possible. I have several coders on a project of which some use the standard alert() function. I want to catch that event when its fired off and display a jquery ui module. Is this even possible? I know I can go through and replace the alerts with a dialog() but i'd rather not sore through thousands of lines of code cross several files to do it if I don't have to.
The alert function does not fire an event, but you can override it:
//Save the old alert function if necessary
var savedAlert = window.alert;
window.alert = function(str){
//Show dialog
}
This would have to run before any calls to alert().
You could directly overwrite the window.alert method with one of your own functions that creates a jQuery UI Dialog instead. This would destroy the alert box for every other scenario, but you could cache it first in case you still wanted to use it.
var _alert = window.alert;
window.alert = function (message) {
// create/show dialog
};
I'm experiencing difficulties trying to invoke document.ready( function() {}) in my unit tests. Suppose I have multiple of them in my javascript file, and one of them called inside a named function i.e.
function myFunction() {
$(document).ready(function() {
//...
});
}
How do I actually invoke them in my unit tests so I can actually test them? I'm using JsTestDriver to unit test my javascripts.
Thanks.
If it's a unit test, I'm guessing you check the function outputs when given certain inputs?
Here's my opinion:
You should prepare for the case where document.ready is called and the case where it isn't.
So your unit test should run each function twice - once to simulate a pre-ready call and one to simulate a post-ready call. That is, you should have one run-through where anything that happens on document.ready DOES run, and one run-through where it's just ignored (presumably to be called later on in the lifecycle).
EDIT:
Just reread the question and understood it a bit more. You could just override $(document).ready to do what you want it to (which is NOT to wait for the DOMLoaded event to fire, but instead to run the functions immediately). This snippet will replace the $(document).ready function with a function that does exactly that. It should run before any unit tests.
var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
if(postReady && fn) fn();
}
Example test case:
<html><head><title>whatever</title>
<script type="text/javascript" src="/JS/jquery-1.3.2.js"></script>
<script type="text/javascript">
var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
alert("We stole ready!");
if(postReady && fn) fn();
}
$(document).ready(function()
{
alert("The function is called.");
});
</script>
</head><body></body>
</html>
You know document.ready... works so just start with calling the functions within it. Ideally, if you just have an init function called by the ready function then you call one function, it does what you need, and you can continue with your tests.
You can take unit testing too far, in this case you need to ask yourself what you are testing, and why. The JQuery document.ready function works, and work well (you know this because it's been tested by many many people).
I would assume the trick would be to, instead of creating an anonymous function, naming one, and using it.
//So instead of this...
$(document).ready(function() {...});
//Do the following
$(document).ready(my_function);
Then you just test my_function and make sure that it is working. Make sure that you test the functions in the order their going to be loaded for an accurate test.
I suggest you to refactor the code. Even if you find a way to call it, it will be hard to understand for other developers.
Also (IMHO, I am not quite sure) you have to call the ready handlers even after the pages ready event was triggered, because if you "install" the ready() handler, if the document.ready event was already trigger, jquery calls that handler immediately (so it never loses that event, even if your code added a handler too late - that is, way after document.ready was still done).
Couldn't you just create a user my_on_read() event ? Or something the like?
Well, in the end, please just take care of ready() events and handlers that will be installed after the document.ready() is already done :)
Part of the answer to this question can be found here.
Below is the sample code to answer this question based on the above answer:
myFunction();
$.readyList[1]();
The index assumes that there is only 1 document.ready function in the source file. Index 0 refers to something else which I believe is info on the browser.