1

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

Headless Dev
  • 99
  • 11
  • possible duplicate of [How to launch html using Chrome at "--allow-file-access-from-files" mode?](http://stackoverflow.com/questions/18586921/how-to-launch-html-using-chrome-at-allow-file-access-from-files-mode) – Allan Chua Aug 11 '15 at 00:48

5 Answers5

6

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).

Starfish
  • 3,344
  • 1
  • 19
  • 47
3

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.

DylanB
  • 431
  • 3
  • 16
3

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.

Purag
  • 16,941
  • 4
  • 54
  • 75
2

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

Nic
  • 1,014
  • 7
  • 15
0

You can try the jquery:

$('#bob').click(function(){
  $("#bob").html("Changed");
});
aldrin27
  • 3,407
  • 3
  • 29
  • 43