Saint Robson
Saint Robson

Reputation: 5525

Add class when div visible on screen

I have this HTML code :

<ul>
    <li class="menu" id="menu-features">
        <a href="#features">Features</a>
    </li>
</ul>

<a id="features"></a>
<div id="div-features">
<!-- SOME CODE HERE -->
</div>

and I have this jQuery script :

    $(document).ready(function(){
        if $('#div-features').visible(){
            $('#menu-features').addClass("active");
        }
    });

now, here's the problem :

I want to add a class to list item, in this case #menu-features only when div #div-features visible on the screen. once it's not visible then the class will be removed.

but, it seems that jQuery .addClass not affecting anything on #menu-features.

what did I do wrong here? thank you.

UPDATE : I tried also, but still failed

$(document).ready(function(){
    if ($('#div-features').is(':visible')){
        //$('#menu-features').addClass("active");
        alert('Hello, World!!');
    }                               
});

Upvotes: 0

Views: 15335

Answers (2)

Igor Garcia
Igor Garcia

Reputation: 39

I'm doing this on scroll

waypoint

is opacity 0 to hide the element then

animated

shows the element if it is 30% visible on window

$(window).scroll(function () {
        $('.waypoint').each(function (i) {
            var bottom_of_object = $(this).offset().top + ($(this).outerHeight() * 0.3);
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            if (bottom_of_window > bottom_of_object) {
                $(this).addClass('animated');
            }
        });
    

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this :Your if condition having error, please follow below code

$(document).ready(function(){
   if ($('#div-features').is(':visible')){
         $('#menu-features').addClass("active");
    }
 });

Upvotes: 0

Related Questions