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);
Related
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"
Sorry if this may be deemed a slight duplicate, however I couldn't find an answer that helped me understand why myFunc() is firing on page load and not when I click el1 or el2. How can I make the following code behave as expected?
function myFunc(param){
//yadayada
}
el1.onclick = myFunc('string1');
el2.onclick = myFunc('string2');
Thanks.
document.getElementById('el1').onclick = function() { myFunc('string1'); };
document.getElementById('el2').onclick = function() { myFunc('string2'); };
You need to get the elements on the page first and then assign a function to them, otherwise the parser will execute them onload because it thinks that myFunc() is returning a value to be assigned to onclick as opposed to the actual function myFunc().
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" );
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 understand the difference between an addEventListener and the onclick property and know how to use both. I am wondering if there is a draw back to always using EventListener's instead of using the onclick property. The EventListener appears to be much more powerful than just using the onclick atleast when dynamically generating the HTML from javascript.
Is there a memory/cpu drawback or am I safe to only use EventListeners?
This probably isn't the direction you were going in, but there are a few instances where you would be unable to remove an event listener.
Event handlers are completely public, and can be modified (to a certain extent) by anyone:
// You do this
myLink.onclick = function () {
alert('hello, world');
};
// Another developer who hates you because
// he thinks that you're hitting on his girlfriend
// but you're not, you're just friends, but
// he's jealous so he doesn't understand
// does this
myLink.onclick = function () {
alert('muahahahaha');
};
// Someone else could even get rid of
// the handler entirely:
myLink.onclick = null;
But there is no publically accessible list of event listeners. The only way to remove an event listener is if you still have access to the original function:
myLink.addEventListener('click', function () {
alert('hello, world');
}, false);
There is now no way to remove that event listener. You gave it an anonymous function, so even you wouldn't be able to remove it if you wanted to.