Update
After some troubleshooting, I realized that the background image was indeed fading out. The issue was that the background image was being removed before the fade effect could be seen. By removing .css('background','')
, I was able to achieve the desired fade out effect. However, despite this fix, some of my CSS styles were still not affecting the element. It seems that a background-repeat: initial;
property was overriding the class styles. Could this be due to JavaScript manipulation?
New:
I have gone through several similar questions here, and while they have helped me make progress, I am still struggling to find a solution.
The problem I am facing involves fading background images on hover. I am using jQuery to set the background of a div to an image URL stored as a data attribute in a list of links when hovering over the link.
I have managed to assign the background image and add a class to make it visible. The fading effect works when transitioning in, but not when transitioning out. Manually removing the visibility class in Chrome Dev Tools results in the expected fade out effect, but the same is not achieved when done via jQuery. Additionally, other "background-" CSS styles do not seem to work unless I use !important. I am unable to determine what is causing these overrides.
JSFiddle
HTML
<div class="backdrop"></div>
<ul>
<li><a href="#" class="item" data-img="http://goo.gl/hbKhMi">one</a></li>
<li><a href="#" class="item" data-img="http://goo.gl/7p0Kki">two</a></li>
<li><a href="#" class="item" data-img="http://goo.gl/EHW4Xs">three</a></li>
</ul>
CSS
.backdrop {
width:450px;
height:400px;
opacity: 0;
-webkit-transition: opacity 0.75s;
transition: opacity 0.75s;
background-position:center;
background-repeat: no-repeat;
}
.visable{
opacity:1;
}
JS
$(document).ready(function() {
$('.item').mouseenter(function() {
$('.backdrop').css('background','url('+$(this).data("img")+')').addClass('visable');
});
$('.item').mouseleave(function() {
$('.backdrop').css('background', '').removeClass('visable');
});
});