Home > OS >  Make background image of a div appear slowly using JQuery
Make background image of a div appear slowly using JQuery

Time:05-23

I'm using following code to achieve appearance of div's background image appear slowly:

$('#stepOne').on('mouseenter', function () {
    $('.stepImage').css("background-image", "url(/Content/Images/Eligibility.png)");
    $('.stepImage').css("-webkit-transition", "1s all");
    $('.stepImage').css("-moz-transition", "1s all");
    $('.stepImage').css("-ms-transition", "1s all");
    $('.stepImage').css("-o-transition", "1s all");
    $('.stepImage').css("transition", "1s all");
        }).on('mouseleave', function () {
    $('.stepImage').css("background-image", "none")
        });

But to no avail. Can someone please help. Thanks in advance.

CodePudding user response:

$('#stepOne').on('mouseenter', function () {
    $('.stepImage').css("background-image", "url(/Content/Images/Eligibility.png)");                
    $('.stepImage').css("transition", "transform 2s ease");
    $('.stepImage').css("transform", "scale(0.75)");
        }).on('mouseleave', function () {
    $('.stepImage').css("transform", "scale(1)");
    $('.stepImage').css("background-image", "none");
        });

CodePudding user response:

You cannot transition a background image so I would create an extra div that you can transition the opacity on instead.

The main idea is to position the container relative and then have your background element absolutely positioned to fill the container with a z-index of -1 to push it behind and then animate the opacity of that

$('.hover').on('mouseenter', () => {
  $('.background').addClass('active');
}).on('mouseleave', () => {
  $('.background').removeClass('active');
});
.test {
  width: 400px;
  height: 400px;
  position: relative;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
  background: url(https://www.fillmurray.com/400/400) top left no-repeat;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.background.active {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >hover me</div>
<div >
  <div ></div>
</div>

  • Related