How to constantly check div for class

It works once when you click on the area to check if it has "top-nav", but how do I make it continually check so that the alerts work every time it doesn't, or has the class "top-nav"

jsfiddle: https://jsfiddle.net/jzhang172/117mg0y1/

 if(!$('.view-projects').hasClass("top-nav")){
 alert('has');

 }else if($('.view-projects').hasClass("top-nav")){
  alert('hey');
   
 }
 
 $('.push').click(function(){
 $('.view-projects').toggleClass('top-nav');
 });
.view-projects{
  height:100px;
  width:100%;
  background:black;
}
body,html{
  margin:0;
  padding:0;
}
.push{
  height:200px;
  width:100px;
  background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="view-projects"></div>

<div class="push"></div>

Answers 1

  • This should do what you want. Hope it helps!

    $('.push').click(function(){
        //toggle the class 'top-nav' for element with class='view-projects'
        $('.view-projects').toggleClass('top-nav');
        //checks if our element/tag has class='top-nav'
        if($('.view-projects').hasClass("top-nav")){
            console.info("Our div has class='top-nave'");//this will print data in console in blue color instead of the old school alert
        }else{ //Else your div don't have the required class
            console.info("Our div does not have class='top-nave'"); //this will print data in console in blue color instead of the old school alert  
        }
    });
    

Related Articles