January 6, 2011

JQuery – Fade To Color On Mouse Hover

Question by anon445699

I have the following JQuery code to fade the background color of a div to a different color when the mouse hovers over the div element. It works great but it requires jqueryui.js to work. My pages already use the jquery.js for other purposes, so I have to load both frameworks.

Can this be done only with jquery instead of jqueryui?

<!-- fade page onload -->
$(document).ready(function(){
    $('#page_effect').fadeIn(1000);
});
<!-- fade login form to color on hover -->
$(document).ready(function(){
$("#frmLogin").hover(
function() {
$(this).stop().animate({ backgroundColor: "#fff"}, 800);
},
function() {
$(this).stop().animate({ backgroundColor: "#e6e6e6" }, 800);
});
});

Thank you!

Answer by Damien-at-SF

Little bit hacky, but its the best I could come up with…

Working example: http://jsfiddle.net/Damien_at_SF/paDmg/

Code:

<div id="frmLogin">
    <div id="bg"></div>
    <div id="text">BLAH BLAH HAHAHAH</div>
</div>

Fade in the ‘bg’ div (which is the background colour) when hovering over the content…

$(document).ready(function(){
$("#text").hover(
function() {
$("#bg").stop().fadeOut();
},
function() {
$("#bg").stop().fadeIn();
});
});

CSS for positioning:

#frmLogin {

    position:relative;
    height:400px;
    width:800px;

}

#bg{

    position:absolute;
    width:100%;
    height:100%;
    border:1px solid black;
    background:#e6e6e6;

}

#text {
    background:transparent;
    position:absolute;
    width:100%;
    height:100%;
    border:1px solid black;
}

jQueryUI is an awesome tool, I’d definitely use it over my solution…

Hope that helps 🙂

Answer by Starx

If you are OK with Jquery UI, a better solution would be just this

$(document).ready(function(){
    $("#sample").mouseover(function() {
         $(this).animate({ backgroundColor:'#f00'},1000);
    }).mouseout(function() {
        $(this).animate({ backgroundColor:'#ccc'},1000);
    });       
});

DEMO: http://jsfiddle.net/Starx/KpEMc/1/

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!