Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade in text over an image

Tags:

jquery

css

Two things don't seem to work with this code.

  1. I want to be able to hover the larger DIV in order to bring the smaller one into view.

As it stands, it only works if you hover over the smaller DIV. 2. The smaller DIV doesn't disappear when I stop hovering.

<div class="one">
    <div class="two"></div>
</div>

<div class="one">
    <div class="two"></div>
</div>

.one {
    position: relative;
    width: 100px;
    height: 100px;
    margin: 10px;
    background-color: #CCC;
}
.two {
    position: relative;
    top: 20px;
    left: 20px;
    height: 40px;
    width: 40px;
    background: #333;
}

/* Fade-in text over images */
$(function(){
    $(".two").css("opacity",0).fadeTo(0, 0);
    $(".two").mouseover(function () {
        $(this).fadeTo(200, 1);
    });
    $("two").mouseout(function () {
        $(this).fadeTo(200, 0);
    });
});
like image 966
Andy Avatar asked Feb 20 '23 09:02

Andy


2 Answers

You should target the larger div, .one, and then change the smaller div, .two within the context of this whenever hovering .one. When fading from visible to invisble you can most of the time use fadeIn/Out, and just set the element to display:none in the CSS.

$(function(){
    $('.one').on({
        mouseenter: function() {
            $(".two", this).fadeIn(200);
        },
        mouseleave: function() {
            $(".two", this).fadeOut(200);        
        }
    });
});​

FIDDLE

like image 126
adeneo Avatar answered Feb 24 '23 09:02

adeneo


jsFiddle demo

$(".one").on('mouseenter mouseleave',function ( e ) {
      var fade = e.type=='mouseenter'?
      $('.two', this).stop().fadeTo(200, 1):
      $('.two', this).stop().fadeTo(200, 0);
});
like image 38
Roko C. Buljan Avatar answered Feb 24 '23 07:02

Roko C. Buljan