[JS] Can't get .onclick event to work. [solved]

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

[JS] Can't get .onclick event to work. [solved]

Post 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
Last edited by Ark on Fri Sep 16, 2011 9:07 pm, edited 1 time in total.
Orgullo Catracho
User avatar
Lord Strife
Posts: 104
Joined: Wed Oct 28, 2009 3:10 pm

Re: [JS] Can't get .onclick event to work.

Post 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> 
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: [JS] Can't get .onclick event to work.

Post 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.
The indelible lord of tl;dr
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: [JS] Can't get .onclick event to work.

Post by Ark »

Ey it works! Thanks alot lord strife!
Orgullo Catracho
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: [JS] Can't get .onclick event to work.

Post by Ark »

Thanks Jack i'll keep that in mind.
Orgullo Catracho
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: [JS] Can't get .onclick event to work. [solved]

Post 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!
The indelible lord of tl;dr
Post Reply

Return to “Beginner Help and Support”