4
I’m trying to use in my project the scrollleft
with the button, it works normal on jsfiddle
But when I put in my project it returns me this error:
Uncaught Typeerror: Cannot read Property 'addeventlistener' of null.
4
I’m trying to use in my project the scrollleft
with the button, it works normal on jsfiddle
But when I put in my project it returns me this error:
Uncaught Typeerror: Cannot read Property 'addeventlistener' of null.
9
Probably in the script on your machine you didn’t use window.onload
or DOMContentLoaded
, jsfiddle works because the script runs after the DOM loads, see how it is in your jsfiddle:
So to adjust can do something like:
window.onload = function () {
var mover = document.getElementById("mover");
var painel = document.getElementById("painel");
mover.addEventListener("click", function (event) {
painel.scrollLeft += 100;
});
};
Another way with onload
would be:
window.addEventListener("load", function () {
var mover = document.getElementById("mover");
var painel = document.getElementById("painel");
mover.addEventListener("click", function (event) {
painel.scrollLeft += 100;
});
});
The
addEventListener
can makes it a little easier to use multiple functions with the same type of event
Or with something faster:
document.addEventListener("DOMContentLoaded", function () {
var mover = document.getElementById("mover");
var painel = document.getElementById("painel");
mover.addEventListener("click", function (event) {
painel.scrollLeft += 100;
});
});
The difference of onload
and DOMContentLoaded
you can see here:
If you need something that will do the same DOMContentLoaded
for old browsers you can try this example:
Thank you.. It worked PERFECTLY, THAT’S WHAT I WANTED. Thank you.
William, how can I reproduce this first image you posted in this answer ? Ultlize the "window.onload" solution in my code and it worked perfectly. Does that mean all my js should be inside onload ? This is because js is being loaded before the page ?
@Railanesteps should be inside the onload if you need to manipulate the DOM/HTML, but it doesn’t have to be onload, as I explained in the reply, Domcontentloaded will be faster pq will only wait for the page to load and will not expect images and videos and other things, then you can already get the HTML elements
Thank you William !
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
Easy, just call your file "js" at the end of the html </body> <script src="SEUFILE.js"></script> </HTML page>
– Mauro Silva