Reputation: 78
I'm trying to get something to fade in using Jquery. I am gathering the info via scrollTop(). So, when the scroll top equals the offset().top of the div, it will fadein. Or just appear.
#myDiv {
background: #990000;
height: 500px;
width: 100%;
overflow: hidden;
opacity: 0;
}
.fade-in {
opacity: 1.0;
}
There's my CSS.
var winHeight = $(window).height();
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
$("#myDiv").each(function() {
var $this = $(this);
var trigger = $(this).offset().top;
if (scrollTop >= trigger) {
$this.addClass("fade-in");
}
});
});
And there is my Jquery. The funny thing is that if I use $this.css it works fine.
I am just wondering how CSS and Jquery interact when it comes to opacity.
Upvotes: 0
Views: 1266
Reputation: 1896
The id-selector(#myDiv
) class gets more priority than the class-selector(.fade-in
) in css. So the opacity property in the #myDiv
gets more priority when your div has both the classes added. Just changing the .fade-in
class a bit, your code should work fine.
.fade-in {
opacity: 1.0 !important;
}
Hope it helps :)
Upvotes: 1
Reputation: 4755
The jQuery .addClass() method just instantly adds the specified class to the element, and once it's added, the css rules are instantly applied just like they would be if you had added the class in the HTML. There's absolutely nothing special or jQuery-specific about how the rules are applied, so opacity shouldn't be applied any differently than any other CSS rule would be. If you believe you're getting a different result when applying the rule via $(this).addClass("fade-in") rather than using $this.css, I'd suggest setting up a jsFiddle to show the issue so folks can take a look at it for you.
Upvotes: 0