I write in two files: one is html and one is JavaScript. Therefore, to call the object, I do
document.getElementById("nameObj").onmouseover = changeMe;
and in the javascript file i do
changeMe = function() {
but now I'm trying to optimize my code and call a function with objects in it. I created partitions (4 of them) and I am trying to change the color using onmouseover and onmouseout . Here is the html code:
<!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 does not work. What have I done wrong?
source share