Search code examples
javascripthtmlonmouseoveronmouseout

the difference between calling object and function in javascript


I'm writing in two files - one is html and one is JavaScript. So to call an object I do

 document.getElementById("nameObj").onmouseover = changeMe;

and in the JavaScript file I do

changeMe = function()
{
 //and here i write the function
}

but now I'm trying to optimize my code and to call a function with objects in it. I created sections (4 of them) and I'm trying to change the color with onmouseover and onmouseout. Here is the code of the html:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"> </script>
        <title> test 2</title>
    </head>
    <body>
        <header> </header>
        <div id="wrapper">
        <main>
        <section class="mysection" id="section1"> </section>
        <section class="mysection" id="section2"> </section>
        <section class="mysection" id="section3"> </section>
        <section class="mysection" id="section4"> </section>
        </main>
        <div class="clear"> </div>
        </div>
        <footer> </footer>
                <script>
            (function(){
                var sec = document.getElementsByClassName("mysection");
                for(var i=0; i<3; i++)
                {
                    sec[i].onmouseover=changeMe(sec[i], i);
                    sec[i].onmouseout=changeBack(sec[i]);
                }
            })();   
        </script>
    </body>
</html>

and here is JS:

function changeMe(t_section, count)
{
    if(count==0)
    {
        t_section.style.background="yellow";
    }
    if(count==1)
    {
        t_section.style.background="blue";
    }
    if(count==2)
    {
        t_section.style.background="green";
    }
    if(count==3)
    {
        t_section.style.background="red";
    }
};

function changeBack(t_section)
{
    t_section.style.background="gray";
};

But it's not working. What did I do wrong?


Solution

  • Change your script tag to this code:

    (function(){
      var sec = document.getElementsByClassName("mysection");
      for(var i = 0; i < 4; i++)
      {
        sec[i].addEventListener('mouseover', function() {
          var index = i;
          return function() {
            changeMe(sec[index], index);
          };
        }());
        sec[i].addEventListener('mouseout', function() {
          var index = i;
          return function() {
            changeBack(sec[index]);
          };
        }());
      }
    })();
    

    Check here about event listeners.
    Please check this fiddle for the complete working example.