I use window.onload() to create a new div with text inside it. It works if I add it to a button (onclick) but it will not fire when I am using it with window.onload(). I have to other window.onload in the same js file that works well.. Any idea how I can fix this and what the problem might be?
My code:
function addDate() {
var addDiv = document.createElement('div');
addDiv.innerHTML = "test";
document.getElementById('date').appendChild(addDiv);
}
window.onload = addDate();
1)The way you're binding, you can have just one method attached to an event. You need to add an event listener for what you want.
window.addEventListener("load", function() { alert("hello!");});
Setting directly a method to the onload event will replace any previously attached method. But if you use listeners instead, you can have many of them bound to an event.
2)If you comment out the onload in your external file, when the document.getElementsByClassName("bar") is called, your document isn't ready yet, then, it will return 0 items.
3)Use the addEventListener as I explained in the first point. If you apply this in both places, it will work like a charm.
if you want more info on window.onload check it out here
When you say "I have to other window.onload in the same js file" I'm assuming you mean "I have two other...", and that would be the problem right there.
If you say:
window.onload = doThis;
window.onload = doThat;
Only doThat gets called. Also, notice... no parentheses! It's window.onload = doThat, NOT window.onload = doThat().
If you use:
window.addEventListener('load', addDate);
Then you can get the function to be called, and not mess up other functions being called.
I would suggest you use a library such as jQuery to do JavaScript work. It's much easier to deal with problems like those. The initialization makes use of the ready function.
$(document).ready(function() {
addDate()
});
You can add as many ready() calls as you need (one per script).
Under the hood, as mentioned by others, it will use window.addEventListener(<event name>, <inline function>). So we added a little bit of code, things will be a tad bit slower, but you're going to have code that works much faster.
Thanks everyone, the problem was that I was using window.onload two times in my code. And the solution, as you all said, was to use window.addEventListener instead. I also removed the parantheses.
So for anyone else getting the same problem, use window.addEventListener to trigger the code instead. Like:
window.addEventListener('load', databaseToNewElement);
window.addEventListener('load', addDate);
Related
I was having duplicates events with this code that was purposely supposed to run multiples times:
$('selector').on('change', myFunction);
Then I did some Googling and I saw that I could/should do
$('selector').off('change', myFunction).on('change', myFunction);
to unbind it first, which makes sense, but I still had the same issue ending up with multiples bindings.
Then curiously I changed my code to include a () after my function's name on the off() part and it worked!
$('selector').off('change', myFunction()).on('change', myFunction);
So, my question is: am I doing right by using myFunction() instead of myFunction on the off() part?
http://api.jquery.com/off/
There is no off overload that accepts the set of parameters you are calling it with. Your "working" code does the same as
$('selector').off('change').on('change', myFunction);
with unwanted side-effect of executing myFunction in .off('change', myFunction()).
Just delegate the event once on page load and don't add multiple listeners
$(document).on('change','selector', myFunction);
I used document but you can move that to a closer permanant asset in the page that is an ancestor of the element(s)
After researching a bit I got it working properly using
$('selector').off('.myNamespace').on('change.myNamespace', myFunction);
Doing this I don't end up unbinding any other event, I just unbind the one I really need.
PS.: I still don't know why $('selector').off('change', myFunction) doesn't work but I'll move forward.
Thanks.
Well I'm simply playing around with a userscript of GreaseMonkey and here's just something simple I attempt to do;
function test() {
document.getElementById('elementhere').innerHTML = 'test';
}
document.onload = test();
It works if I go to the page I want to use it on and do "run" or "reload & run" - but it won't run automatically, which I'm trying to make it do by using document.onload.
What you need is:
window.onload = function () {
// do the work after everything was loaded (DOM, media elements)
}
document.onload it doesn't exist. It works if you at least target some specific element from document for example:
document.querySelector("img").onload = function ()
{// do your thing after 'img' was loaded}
You have other options if you want to execute some code after the DOM is the only element ready without wait for media elements to load like:
Import an async script tag loading the file with the code:
You can place this tag wherever you want in DOM and it will not interrupt nothing, will load after the DOM finish to load. you should take a look to MDN documentation about that.
If you take a look again in MDN documentation they will recommend you in section Notes to use DOMContentLoaded and DOMFrameContentLoaded events which can be handling by addEventListener. So, if you do this:
document.addEventListener('DOMContentLoaded', handlerFunc);
Will work for you.
I hope this can be helpful for you...
When you write document.onload = test(), you are calling the test function, and assigning its return value to the onload handler. This is clearly not what you intended.
document.onload = test;
This will assign a reference to the test function to the onload handler. When the event fires, that is when your function will be called.
It is because you are assigning the result of the test function instead of the function itself due to the parentheses () on the last line.
Remove them and it may work.
If not then:
Apparently that is by design. [Chrome - v57]
Use document.addEventListener("DOMContentLoaded", <function_name>); instead.
See: Page lifecycle : DOMContentLoaded
Maybe do this:
<body onload="test()">
Or is that not what you're looking for? If you want to do it without the HTML bit above, maybe try and replace document with window:
window.onload = function ()
{
document.getElementById('elementhere').innerHTML = 'test';
}
I would give that a go because of this:
window.onload vs document.onload
I know that posting a link to a link is lame, but you will see why I did that (hopefully).
Cheers!
No Need to call the function on the page .. just you need to use below code which is best practices of coading
window.onload = function() {
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
}
It's working but you can use alternate
window.init = test;
If you are using Greasemonkey then you don't really need a using onload event since the Greasemoneky script is called only when DOMContentLoaded is fired.
The code in a Greasemonkey user script gets invoked when the
DOMContentLoaded event fires (during event capture as of GM 0.8.6). It
is a DOM event implemented by Mozilla, similar to window.onload.
However, since it waits only for the DOM to load, instead of the
entire page (including images, style sheets, and etc.) it happens
sooner.
http://wiki.greasespot.net/DOMContentLoaded
I think you would just need to call test() without any event listeners.
did you try this?
<body onload="test()">
or
$(document).ready(function test() {
document.getElementById('elementhere').innerHTML = 'test';
}
I'm having the strangest issue when I'm calling in functions on an event. I'm trying to get a function to run when the window is resized using $(window).resize() but it seems to fire the function as soon as the DOM loads then never again.
I'm probably missing something really simple here but I've been looking at it all day and I need a bit of outside help.
I've created a watered down version on JSfiddle that does the same thing but using $('a').click() instead of $(window).resize() so it's a bit easier to test. As the same issue is cropping up I have a feeling there's something wrong with my function but I just can't see it.
Link is here http://jsfiddle.net/sambeckhamdesign/APLZ2/1/
Try:
$('a').click(function(){
alert('hello');
}, imageResizer());
You are running the function and sending it's output into the jQuery thingy as a parameter:
$('a').click(alert('hello'), imageResizer());
instead, try this:
$('a').click(function() {alert('hello'); imageResizer(); });
This provides an anonyomous function, which will be run when the item is clicked, calling imageResizer(), whereas the way you had it, it ran the imageResizer() function and put it's return value into the onclick handler. The reason it didn't work later on was because it would have been treating whatever the return value of the imageResizer() function was as code that it was trying to run.
You are triggering the event instead of assigning an handler to it
$('a').click(alert('hello'), imageResizer());
Should be
$('a').click(function(event) {
event.preventDefault(); // I suppose you will want that ... it will avoid your window jumping to the top when you click due to the href="#"
alert('hello');
imageResizer();
});
JS BIN Attempt
Attempting to follow along with the example, but it doesn't seem to work. A little confused, as it is Mozilla.
Mozilla
As #Xaerxess mentions, you need to call the "setupButtons" function when the DOM is ready for manipulation; typically one does that by adding an event handler to the window "load" event, which happens when the page is entirely loaded (which is what the jQuery idiom $(document).ready(function(){...}); does.
Try adding this snippet to the end of your existing <script> element to accomplish that goal using plain JavaScript, no jQuery needed:
window.onload = function() { setupButtons(); };
Another typical way of doing this is to use the element.addEventListener function; the difference is that you can add multiple event callbacks this way and they won't overwrite each other:
window.addEventListener('load', function() {
setupButtons();
}, false);
You didn't call setupButtons function on page load, only defined it. If you include jQuery, add:
$(document).ready(setupButtons);
in you script tag and it'll work.
What is the difference betwen setting the onclick function in this way:
obj.onclick=new Function('functionname')
and
obj.onclick=function(){ functionname();};
How can i set the onclick event removing all previrius attached? (using jquery or simply javascript)
i try something like this:
$(obj).unbind('click');
$(obj).click(function() {
functionname();
});
but the unbind seems to remove even the next attached events.
thanks
EDIT:
I set the click event using jquery:
function ON(){
$('#makecorr').unbind('click');//i unbind for some reason..
$('#makecorr').click(function() { OFF(); });
}
function OFF(){
$('#makecorr').unbind('click');//i want to remove prev attached fun
//and replace it with new event
$('#makecorr').click(function() { ON(); });
}
this doesnt work for me, when i click the object 'makecorr' it goes in loop , if i put an alert, it comes up infinitely
but when i use: '
function ON(){
$('#makecorr').get(0).onclick=new Function('OFF()');
}
function OFF()
{
$('#makecorr').get(0).onclick=new Function('ON()');
}
it works. strange where am i wrong?
This pair of lines:
$(obj).unbind('click');
$(obj).click(function() { functionname(); });
...if executed in the order above should result in just the handler you've defined there being attached. If you're seeing other behavior, it must be something else in the script.
Regarding
What is the difference betwen setting the onclick function in this way:
obj.onclick=new Function('functionname') and
obj.onclick=function(){ functionname();};
If you're dynamically adding handlers to an element and you're already using jQuery for other reasons, you don't want to use the onclick property at all; stick to the jQuery API, to avoid really confusing yourself. :-)
Even if you're not using jQuery, you almost never want to use new Function(...). There are only very special situations where you'd need that. Mostly stick to function() { functionname(); } (or just use functionname directly).