Jump to content
Sign in to follow this  

Javascript events firing at pageload

Recommended Posts


I am doing a bit of javascript testing and I came around the following problem.

I want my page to firing a function(simple alert) when my mouse moves over a certain div.

However the function fires when the page loads the first time and then also the function doesn't work when I move my mouse over the div.



  <div class="a" >Sample Text1</div>
  <div class="b">Sample Text2</div>
  <div class="c" >Sample Text3</div>
  <script src="js.js"/></script>


function alt()

var d = document.getElementsByClassName("b")[0];
d.onmouseover = alt();

Can anyone please explain why it is behaving like this instead of how one would expect.

Thank you



The same if you use getElementsByTagName("div")[1];

It works like expected if you add the event to the tag in the html itself but I want to know why it is not working with javascript only.

Edited by Iven

Share this post

Link to post
Share on other sites

When you do this:

d.onmouseover = alt();

you're telling it to execute the function alt, and assign the return value to the onmouseover event.  If you want it to run the function when you mouse over, just tell it which function to run:


d.onmouseover = alt;

Share this post

Link to post
Share on other sites

What JustSomeGuy says is also true if you use element.addEventListener(). The function name is used without the argument parens.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...