d24
d24

Reputation: 97

Hover on element, fade in background on parent div

I have an »element« on a fullscreen div. I want to hover on the »element« and fade in a background-image in the div ».section«. It's no problem to just show the background-image but I have no idea how I add a fade-animation.

$(function() {
  $('.element').hover(function() {
    $('.section').css('background-image', 'url(https://ih0.redbubble.net/image.87373734.8395/flat,800x800,075,t.jpg)');
  }, function() {
    // on mouseout, reset the background
    $('.section').css('background-image', '');
  });
});
.section {
  width: 400px;
  height: 400px;
  border: 1px solid black;
  text-align: center;
  transition: 1s ease all;
}

.element {
  margin-top: 45%;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section">
 <div class="element">hover me</div>
</div>

https://jsfiddle.net/sr1qj1pc/

Could you help me?

Upvotes: 2

Views: 884

Answers (2)

ssaket
ssaket

Reputation: 36

Another quick approach -

   $(function() {
  $('.element').hover(function() {
    var section =  $('.section');
    section.fadeOut(0, function(){
        section.css('background-image', 'url(https://ih0.redbubble.net/image.87373734.8395/flat,800x800,075,t.jpg)');
        section.children().fadeIn();
        section.fadeIn(1500);
    });
  }, function() {
    // on mouseout, reset the background
    $('.section').css('background-image', '');
  });
});

Upvotes: 0

the_lorem_ipsum_guy
the_lorem_ipsum_guy

Reputation: 474

I have updated your fiddle.

You can use CSS alone no need to use jquery. You can use a pseudo element to get the effect that you want.

In this case, if you hover the children element which is the .element then display the background of the parent which is the .section you can use pointer-events which specifies under what circumstances (if any) a particular graphic element can become the target of mouse events. https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

CSS:

.section {
  width: 400px;
  height: 400px;
  border: 1px solid black;
  text-align: center;
  transition: 1s ease all;
  position: relative;
  pointer-events: none;
}

.section:after {
    background: url(https://ih0.redbubble.net/image.87373734.8395/flat,800x800,075,t.jpg) repeat;
    content: "";
    opacity: 0;
    width: inherit;
    height: inherit;
    position: absolute;
    top: 0;
    left: 0;
    /* TRANSISITION */
    transition: opacity 1s ease-in-out;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
}

.element {
  position: relative;
  top: 50%;
  z-index: 1;
  pointer-events: auto;
}

.section:hover:after{   
    opacity: 1;
}

https://jsfiddle.net/sr1qj1pc/3/

Upvotes: 4

Related Questions