Sachin Menon
Sachin Menon

Reputation: 69

how to give image fade effect on hover?

How to make fade hover change on a parent div when we hover over a child div? I want the hover to have a fade effect and change the background image of the parent div. The change is happening very fast. I want the change to happen and slowly and smoothly.

<script>
		$('#hoverdiv').on('mouseover', function(){
  $(this).parent().addClass('is-hover');
}).on('mouseout', function(){
  $(this).parent().removeClass('is-hover');
})
	</script>
.bground {
  width:100%;
  position:relative;
  background: url(../img/bg1.jpg) no-repeat top center;
}

.bground:after {
	content: url(../img/bg2.jpg);
	width:0;
	height:0;
	display:none;
}

.is-hover {
  background: url(../img/bg2.jpg) no-repeat top center;
}

#hoverdiv
{
	width:auto;
	height:auto;
	margin:0 auto;
	padding:0;
}
<section id="bground" class="bground">
  <div id="hoverdiv">
  <div class="display">
    <img src="img/logo.png" alt="Logo">
  </div>
  <div class="page-scroll">
    <a href="#about" class="btn btn-circle" style="color:#000000">
      <i class="fa fa-angle-double-down animated"></i>
    </a>
  </div>
    </div>
</section>

Upvotes: 1

Views: 559

Answers (3)

user2053945
user2053945

Reputation: 11

.bground {
  width: 400px;
  height: 300px;
  background: #aaa url("http://placehold.it/300x200/ffff00") no-repeat top center;
  position: relative;
}

.bground:after {
  content: "";
  background: url("http://placehold.it/300x200/ff0000") no-repeat top center;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  visibility: hidden;
  opacity: 0;
  transition: all .5s linear 0s;
}

.bground:hover:after {
  visibility: visible;
  opacity: 1;
  color:#fff;
}
<div class="bground"></div>

Upvotes: 1

marvinhagemeister
marvinhagemeister

Reputation: 3154

There is no need for javascript. You can easily achieve this with css transitions:

.bground {
  width: 400px;
  height: 300px;
  background: #aaa url("http://placehold.it/300x200/ffff00") no-repeat top center;
  position: relative;
}

.bground:after {
  content: "";
  background: url("http://placehold.it/300x200/ff0000") no-repeat top center;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  visibility: hidden;
  opacity: 0;
  transition: all .3s;
}

.bground:hover:after {
  visibility: visible;
  opacity: 1;
}
<div class="bground"></div>

Upvotes: 1

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10197

You are adding and removing class with js which cannot be slow down.

What you can do is add transition in css

.is-hover {
  background: url(../img/bg2.jpg) no-repeat top center;
  transition:all ease-in-out 0.3s;
  -moz-transition:all ease-in-out 0.3s;
  -ms-transition:all ease-in-out 0.3s;
  -o-transition:all ease-in-out 0.3s;
  -webkit-transition:all ease-in-out 0.3s;
} 

It is important to add prefix like -moz-, -webkit- etc to let it work in all browsers.

Upvotes: 3

Related Questions