JavaScript on MouseOver change BODY style. Reverse on MouseOut

1.9k views Asked by At

I wish to use JavaScript to apply the style given below to the body of the HTML or another div on mouseover. And reverse on mouseout. Both with a fade if possible?

Style:

.box-style_img2 {
    background-image: url(img.png);
    background-size: auto;
    background-repeat: repeat;
    background-attachment: scroll;
    background-color: #00a0b0;
}

Thanks in advance. P.S. Just beginning to learn Javascript.

2

There are 2 answers

1
NaYaN On BEST ANSWER

It is always better to do things in CSS if you can avoid Javascript

Try using :hover property of css. For animation use transition property

<div class="box-style_img2">    
</div>

.box-style_img2 {
    background-size: auto;
    height: 100px;
    width: 100px;
    background-repeat: repeat;
    background-attachment: scroll;
    background-color: #00a0b0;
    transition: all 1s ease;
}
.box-style_img2:hover {
    background-size: auto;
    height: 100px;
    width: 100px;
    background-repeat: repeat;
    background-attachment: scroll;
    background-color: #000000;
    transition: all 1s ease;
}

Also you can check this fiddle

4
HIRA THAKUR On
function on_mouseover(){
document.body.className += "your-class-to be applied";//for body
or
document.getElementById("div-id").className ="your-class-to be applied"
}

function on_mouseout(){
document.body.className += "your-initial-css-class";//for body
or
document.getElementById("div-id").className ="your-initial-css-class";
}

Your HTML:

<div id="div-id" onmouseover="on_mouseover()" onmouseout="on_mouseout()"></div>

Or you can use addEventListener if you dont want to write javascript inline

document.getElementById('your-id').addEventListener("mouseover",on_mouseover);
document.getElementById('your-id').addEventListener("mouseout",on_mouseout);

Note:This task can also be done using plain css also.

.your-class{
//properties to be applied on mouseout
}
.your-class:hover{
//properties to be applied on mouseover
}