Iven Posted July 24, 2018 Share Posted July 24, 2018 (edited) Hello 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. html <html> <head> </head> <body> <div class="a" >Sample Text1</div> <div class="b">Sample Text2</div> <div class="c" >Sample Text3</div> </body> <script src="js.js"/></script> </html> js function alt() { alert(d.innerHTML); } 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 EDIT 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 July 24, 2018 by Iven Link to comment Share on other sites More sharing options...
justsomeguy Posted July 24, 2018 Share Posted July 24, 2018 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 More sharing options...
davej Posted July 25, 2018 Share Posted July 25, 2018 What JustSomeGuy says is also true if you use element.addEventListener(). The function name is used without the argument parens. Link to comment Share on other sites More sharing options...
Iven Posted July 25, 2018 Author Share Posted July 25, 2018 Thank you for replying and explaining that makes sense haha. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now