Reputation: 151
I'm trying to hide an image after I scroll down my page. When scrolling my header
gets a class fl-theme-builder-header-scrolled
. My image div has a class hiding-image
and I want to add a class image-off
when the fl-theme-builder-header-scrolled
class shows up in the header
.
This is what I have:
$(document).ready(function() {
if($( 'header' ).hasClass( 'fl-theme-builder-header-scrolled' )) {
$( '.hiding-image' ).toggleClass( 'image-off' );
}
});
but this doesn't work. Any advice? Thx.
Upvotes: 0
Views: 84
Reputation: 151
I finally managed to make it work doing this:
(function($){
$(function(){
var headerThemer = $( '.fl-builder-content[data-type=header]' ).eq(0);
$(window).on( 'scroll.fl-theme-builder-header-scrolled', function(){
if ( headerThemer.hasClass('fl-theme-builder-header-scrolled') ) {
$('.hiding-image').hide();
}
else {
$('.hiding-image').show();
}
});
})
})(jQuery);
Upvotes: 0
Reputation: 304
Check condition like this:
`$(window).scroll(function() {
if($( 'header' ).hasClass( 'fl-theme-builder-header-scrolled' ))
{
$( '.hiding-image' ).addClass( 'image-off' );
}
else
{
$( '.hiding-image' ).removeClass( 'image-off' );
}
});`
Upvotes: 0
Reputation: 840
As pointed out in the comments, I think the best approach would be to find where the fl-theme-builder-header-scrolled
class is already being controlled.
However, If you really would want to put the logic in a separate area, you can do it like this:
$(document).ready(function () {
$(window).scroll(function () { //attach to window scroll event
if ($('header').hasClass('fl-theme-builder-header-scrolled') && !$('.hiding-image').hasClass('image-off')) {
$('.hiding-image').addClass('image-off'); //add class only if it does not already exist;
} else {
if ($('.hiding-image').hasClass('image-off')) {
$('.hiding-image').removeClass('image-off'); //remove class
}
}
});
});
Upvotes: 0
Reputation: 683
Try something like this.
$(window).scroll(function() {
if($( 'header' ).hasClass( 'fl-theme-builder-header-scrolled' )) {
$( '.hiding-image' ).toggleClass( 'image-off' );
}
});
Upvotes: 0
Reputation: 1372
Your code only runs once after the document ready, as soon as the page loads. So if the header doesn't have the fl-theme-builder-header-scrolled
class and only gets added later, your code will not run again.
You need a a mutation Observer. Check this thread: Event trigger on a class change
Alternatively you can do as @Brewal is saying, putting the code evaluation on the scroll event. Although be careful so you don't run the code every time the scroll event is triggered since it can slow your website performance, specially on mobile devices.
Upvotes: 2