0

I have html file:

<html>
  <head>
    <script type="text/javascript" src="new.js"></script>

  </head>
  <body>
    <p id="contentBI" >you should click here! </p>
  </body>
</html>

and javascript file:

function doAlert() {
  alert("hi!");
}

function addevent () {
  theBI=document.getElementById("contentBI");
  theBI.addEventListener("click",doAlert);
}

document.addEventListener("load",addevent);

Javascript doesn't run.

6
  • 1
    Have you linked the JavaScript file ? Commented May 11, 2015 at 13:32
  • @VigneswaranMarimuthu yes I put it in head tag. but I don't know why it is not displayed in question. Commented May 11, 2015 at 13:39
  • what kind of browser do u use ?addeventlistener won't work below IE8。a more better way to do this is using jquery library。 Commented May 11, 2015 at 13:48
  • "I don't know why it is not displayed" There is no load event that is triggered on document. Commented May 11, 2015 at 13:50
  • @FelixKling I updated the question, before the head tag was not displayed. Commented May 11, 2015 at 13:54

3 Answers 3

3

use window.addEventListener("load",addevent); instead of document.addEventListener("load",addevent);
DEMO

Sign up to request clarification or add additional context in comments.

Comments

2

So you want a document ready like jquery, try this:

document.addEventListener("DOMContentloaded",addevent, false);

Demo here

Comments

0

Assuming this is all of your code, the first issue you should tackle is telling your page where your Javascript is at.

Try placing your script between <script> </script> tags within your HTML file.

</head>
<body>


<p id="contentBI" >you should click here! </p>


<script>
function addevent (){

theBI=document.getElementById("contentBI");
theBI.addEventListener("click",doAlert);
}
document.addEventListener("load",addevent);
</script>  


</body>
</html
  • It still won't work, most likely. But it's a start.

6 Comments

Nothing is wrong with using src. But to use src in a static site, you have to know the path to the .js file, and I don't. (In this case.)
Hopefully the OP knows the right path, so suggesting to inline it as a solution to the problem seems.... useless?
Perhaps. But, the OP has updated his question based upon responses like mine. The original response didn't indicate that he had linked the files at all.
Ah I see, you answered before the edit. I have to disappoint you though. The whole code was there from the very beginning, the answer was just poorly formatted. : stackoverflow.com/revisions/…
Ah, very nice. I suppose i should view the source before answering huh?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.