0

Any type of javascript code I write and saves with no errors and when I open the html file which is linked to js and css (no jquery or other APIs). It works in all other online test environment (is it because i linked my js wrong). I did:

<script src="javascript.js">

http://jsfiddle.net/tysvnr8q/

I read alot of answers else where but all of them never worked.

Code in Brackets:

HTML

<div id="circle"></div>

CSS

#circle {
height: 100px;
width: 100px;
border-radius:100px;
background-color: red;
}

JS

document.getElementById("circle").onclick = function () {

       document.getElementById("circle").style.display = "none";
};
user54272
  • 61
  • 1
  • 7

2 Answers2

1

Wherever you put the script tag is where the script is run. E.g. If you put the script at the top of the body section or in the head, the script will run then, before loading the rest of your page. You can either place your code inside a window.onload() or

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

Or you can place the script tag with the reference to the file (which I'm assuming is javascript.js and in the same folder) at the very bottom of the body section. Don't forget to close the tag.

nickRise
  • 96
  • 1
  • 6
0

Assuming the file javascript.js was actually in the same folder as your HTML file, then @nickRise has the correct answer.

But I thought I'd clear up one bit of confusion from your question.

You said in the title that your script doesn't run. Actually the script is running, but if you run that script before your DOM is built, then when your script executes

document.getElementById("circle")

It does not find your element, because the element is not yet created!

As @nickRise says, put the script at the bottom of your body, or have it run in the onload handler.

It would be helpful when developing to look in the developer tools console. It might say something like undefined does not an onclick property (the actual error message might vary). Or, if by some chance the javascript.js file was in the wrong place, you might see an error saying that script was not found.

TL;DR the script was running, it just did not do what you thought.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • thanks i'll remember that from now on. So at what point would you ever have to place the script at the top? – user54272 Jul 26 '15 at 20:46
  • That's a question with many answers. [This StackOverflow question is a good place to start](http://stackoverflow.com/questions/3531314/should-i-write-script-in-the-body-or-the-head-of-the-html). – Ray Toal Jul 26 '15 at 20:50
  • [Here's another good SO question with a good first answer](http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup). – Ray Toal Jul 26 '15 at 20:53