Search code examples
javascriptonmouseoveronmouseout

Struggling with onmouseover and onmouseout


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.


Solution

  • 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