JS hide div if it has a class added via JS

2019-03-06 17:12发布

问题:

I am working on a code where an active class is added to a div via JS.

What I would like to do is, when that div has active class, hide another div. But, due to the active class was added via JS, this code doesn't work:

if($("#section3").hasClass("active")) {
    $(".menu").fadeOut("fast");
}

I think I would need to use the on function: .on()

Something like this, but it's not working... Any ideas?

$("#section3").on( function() {
    $(this).hasClass('active') {
        $(".menu").fadeOut("fast");
    }
});

EDITED:

I'm afraid I cannot paste the code because I am using a plugin. This is the one that I am using, so you can see the functionality there.

I've added this bullet menu to it:

<ul id="menu">
    <li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
    <li data-menuanchor="slide3"><a href="#slide3"><span></span></a></li>
    <li data-menuanchor="slide4"><a href="#slide4"><span></span></a></li>
</ul>

Each slide has a active class when it's on viewport, so what I would like to achieve is when the last slider is active, hide the menu

回答1:

oth the section and the li have active classes so you could use something like this or use the afterSlideLoad event if it is depeding of the slideshow

$(window).on("scroll",function() {
  if ($('#menu li:last-child').hasClass("active")) {
    ("#menu").fadeOut("fast")
  }
})

or you can use slideIndex to check if you are on the last slide. see here > afterSlideLoad



回答2:

$(document).ready(function(){
$('section').click(function(){

$(this).addClass('active');
if($('section').hasClass('active')){

$('ul#menu').hide();

}
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>check</section>
<ul id="menu">
<li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
    <li data-menuanchor="slide3"><a href="#slide3"><span></span></a></li>
    <li data-menuanchor="slide4"><a href="#slide4"><span></span></a></li>


</ul>