anonym
anonym

Reputation: 155

How do I change color with onmouseover?

I wonder how I can do those 2 functions into 1 function instead.

 function test1() {
                document.getElementById('div1').style.color = 'red';
            }
 function test2() {
                document.getElementById('div1').style.color = 'blue';
            }


    <div onmouseover="test1()" onmouseout ="test2()" id="div1">
    </div>

Upvotes: 1

Views: 335

Answers (4)

Tornike Shavishvili
Tornike Shavishvili

Reputation: 1354

I would recommend CSS :hover Selector

If you want to change class from javascript, i would recommend jQuery:

jQuery addClass() Method,

jQuery removeClass() Method,

hover()

mouseover()

hasClass()

As for your request to do this with one function, you could write:

function manageHoverColor(){
   if( $("#hoverTestDiv").hasClass("mouseHovered") ){
      $( "#hoverTestDiv" ).removeClass('mouseHovered');
   }else{
      $( "#hoverTestDiv" ).addClass('mouseHovered');
   }
}


$( "#hoverTestDiv" ).mouseover(manageHoverColor);
$( "#hoverTestDiv" ).mouseout(manageHoverColor);

or you could do:

$( "#hoverTestDiv" ).mouseover(function() {
    $( "#hoverTestDiv" ).addClass('mouseHovered');
  });

$( "#hoverTestDiv" ).mouseout(function() {
     $( "#hoverTestDiv" ).removeClass('mouseHovered');
  });
.ordinaryText {
    color: #00FF00;
}

.ordinaryText.mouseHovered {
    color: #FF0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="hoverTestDiv" class="ordinaryText" > I am div to test jQuery mouse hover <div>

Upvotes: 1

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15290

If you want to do with JavaScript you can do in this way.

JS :

window.onload  = function(){
        var htmlDiv = document.getElementById("div1");

        htmlDiv.addEventListener('mouseover',function(){

          htmlDiv.style.color = "red";    
        })

         htmlDiv.addEventListener('mouseout',function(){  
           htmlDiv.style.color = "blue";    
        })
      }

HTML :

<style>
      #div1{
        width:100px;
        height : 100ppx;
        border :1px solid black;
      }
      #div1 { 
        color:blue; 
      }
    </style>

Here is the plunker

Upvotes: 1

Aman Verma
Aman Verma

Reputation: 320

you can achieve this with just css

https://jsfiddle.net/dango_x_daikazoku/404o04co/1/

#test1{
  color:red;
  cursor:default;
}
#test1:hover{
  color:blue;
}

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

pass the object and color to the test method

 function test(thisObj, color) 
 {
    thisObj.style.color = color;
 }

 <div onmouseover="test(this, 'red')" onmouseout ="test(this, 'green')" id="div1"></div>

Upvotes: 1

Related Questions