2

I am struggling with onmouseover and onmouseout.

Every site I have been to shows this syntax almost exactly. I practically copied pasted it from Mozilla. The problem I’m having is that it calls the largeDiv and smallDiv functions immediately. (Eventually, I am hoping to apply a new class to the div when during the mouseover event, and return to the old class when mouseout.) I am pretty sure that my mouse events are to blame. I was also wondering if my onload function caused any problems, but when I commented it out, the only thing that changed was the small div did not load, as expected.

I tried to use an event listener, thinking I wasn’t calling the event properly, but that did not work at all, although I am not sure I coded it properly, and didn’t spend more than an hour on the damn thing! I have tried numerous tweaks, camelcasing onmouseover, using parenthesis, etc… Anyway, here is the code:

var introEl = document.getElementById("intro");

//display large div by default and 
//use small div with js enabled
window.onload = function(){
    introEl.className = "small";
}

    function largeDiv(){
    console.log("It Worked");
};

    function smallDiv(){
    console.log("Mouse Out!");
};

introEl.onmouseover = largeDiv();
introEl.onmouseout = smallDiv();

I coded this in my browser and when I copied it to jsFiddle to ask this question it wouldn’t load the small div on load, but it did log the statements. I put it on CodePen and it worked as I have described. Not sure what caused this but this is the second time this has happened.

By the way, if you go to CodePen or jsFiddle, I know my design skills are lacking. I am just doing this for a playground, and for a place to keep code that works, like a notebook. I promise you it will get much much worse.

As always, any help is appreciated.

SnareChops
  • 13,175
  • 9
  • 69
  • 91

2 Answers2

3
var introEl = document.getElementById("intro");

//display large div by default and 
//use small div with js enabled
window.onload = function(){
    introEl.className = "small";
}

    function largeDiv(){
    console.log("It Worked");
};

    function smallDiv(){
    console.log("Mouse Out!");
};

introEl.onmouseover = largeDiv; // here you don't need "()" with your defined functions
introEl.onmouseout = smallDiv; // here you don't need "()" with your defined functions
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
  • YES! Accept that it seems VERY sensitive. If I move the mouse too quickly it fires off several times. Not just my mouse, it happened the same with the touch pad. But at least it waits for me to mouse over! Thank you very much. – user1929081 Dec 27 '12 at 06:15
2

Please go to following fiddle i have made some small changes and its working fine for me

fiddle

Also You could have used

<div id="intro" onmouseover="largeDiv();" onmouseout="smallDiv();">
    Mouse over this text
</div>

See working example here fiddle 2

ameya rote
  • 1,116
  • 1
  • 9
  • 13