Jump to content

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
Link to comment
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;
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...