Headless Dev
Headless Dev

Reputation: 99

JavaScript onclick() doesnt work

I'm trying to make a div have text put inside when clicked. But the code I use doesn't seem to work on Chrome. I'm just viewing the html document, not hosting it or anything. Anyone know the reason as to why this is happening?

file:///c%3A/Users/Brett/Documents/1_HTML/js_practice/js_practice.html

var bob = document.getElementById("bob");
bob.onclick = function() {
  bob.innerHTML = "words";
};
#bob {
  width: 200px;
  height: 200px;
  background-color: black;
  color: white;
}
<body>
  <div id="bob"></div>
</body>


P.S I can run the html document just fine, it's the code that's the problem

Upvotes: 1

Views: 164

Answers (5)

Purag
Purag

Reputation: 17061

You need to wrap your Javascript inside a function that is bound to the window.onload event:

window.onload = function () {
    // your code here
};

This is because the browser processes HTML documents top-down, so it will execute your Javascript before the element has loaded.

When you bind to the onload event, it will wait for the entire page to load before executing the code, so you can guarantee that your element has been processed by the browser.

The reason it works in the snippet in your question is because the snippet engine adds the Javascript after the body tag, and since pages are rendered top-down, your element is processed before we ever reach the Javascript.

Upvotes: 3

Starfish
Starfish

Reputation: 3574

Wrap your Javascript code inside a window.onload event like this:

window.onload = function() {
  var bob = document.getElementById("bob");
  bob.onclick = function() {
    bob.innerHTML = "words";
  };
}

or load your Javascript-file at the end of the HTML file (just before the </body>)

Documentation window.onload

The window.onload fires when the entire page is loaded, including its content (images, css, scripts, etc.). When you load your script before the HTML is loaded it will not find the required elements on your page. When you load the script after the HTML is loaded it will find all required elements in your HTML (if coded correctly ofcourse).

Upvotes: 6

aldrin27
aldrin27

Reputation: 3407

You can try the jquery:

$('#bob').click(function(){
  $("#bob").html("Changed");
});

Upvotes: 0

DylanB
DylanB

Reputation: 431

Only thing I can think of is you're running the JS before the DOM is loaded so the element doesn't exist, this will fail silently in JS. The solution to this would be to place your code in a window.onload function.

Upvotes: 3

Nic
Nic

Reputation: 1024

Hi Decapitated Rainbow,

I don't see any problem with it. The expected result is click on the black box and it show word with white font.

I'm using Google Chrome Version 44.0.2403.130 m is working fine

Upvotes: 2

Related Questions