Page 1 of 1
[JS] Can't get .onclick event to work. [solved]
Posted: Fri Sep 16, 2011 8:24 pm
by Ark
Hey guy's Can somebody please help me make this code work properly?
Code: Select all
<p id="p1">Testing testing</p>
<script type="text/javascript">
document.getElementById("p1").onclick="this.style.backGroundColor='red' ";
</script>
I know there're other ways to make the onclick event to work, but I need it this way xD
Re: [JS] Can't get .onclick event to work.
Posted: Fri Sep 16, 2011 8:40 pm
by Lord Strife
Code: Select all
<p id="p1">Testing testing</p>
<script type="text/javascript">
var p1 = document.getElementById("p1");
p1.onclick=function() {
p1.style.background="red"
}
</script>
Re: [JS] Can't get .onclick event to work.
Posted: Fri Sep 16, 2011 8:48 pm
by Jackolantern
Just putting the script block below the content to modify doesn't always ensure that the DOM is fully loaded by the time the script block is parsed. Something like this can work:
Code: Select all
window.onload = function () {
//insert your DOM-altering code here
}
It is generally considered a good idea to make sure the page is loaded through this event before trying to alter the DOM.
Re: [JS] Can't get .onclick event to work.
Posted: Fri Sep 16, 2011 8:50 pm
by Ark
Ey it works! Thanks alot lord strife!
Re: [JS] Can't get .onclick event to work.
Posted: Fri Sep 16, 2011 8:52 pm
by Ark
Thanks Jack i'll keep that in mind.
Re: [JS] Can't get .onclick event to work. [solved]
Posted: Fri Sep 16, 2011 10:19 pm
by Jackolantern
Really, the load event works much better in jQuery. In vanilla JS, the load event is not triggered until after the entire DOM is loaded, which can cause delays if the user is on a slow internet connection and/or your page includes high-definition images. The load event code in jQuery is quite long and complicated, but you don't have to know or understand it. In jQuery, the load event is raised after only the raw DOM is loaded and it does not wait until all resources are loaded, which is exactly what you want!