Ways to continuously monitor a div for a specific class

Is there a way to continuously check if an area has the class "top-nav" in order for the alerts to work every time it lacks or contains the class? How can I achieve this functionality?

Check out the code on 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>

Answer №1

Use this code snippet to achieve your desired outcome. I hope it proves helpful!

$('.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 display data in console in blue color
    }else{ 
        console.info("Our div does not have class='top-nave'");
    }
});

Answer №2

When you click on the ".push" element, it seems like you have two tasks in mind:

  1. To toggle the class of ".view-projects" with "top-nav" and...
  2. To display an alert indicating whether or not ".view-projects" has this class.

Instead of continuously checking with an interval, you can achieve both actions using the click handler since they are dependent on it:

$('.push').click(function(){
    // Toggle the class initially
    $('.view-projects').toggleClass('top-nav');

    // Determine the current class state and show appropriate alert
    var hasTopNav = $('.view-projects').hasClass('top-nav'); // returns true or false
    if (hasTopNav) {
        alert("Class 'top-nav' is present");
    } else {
        alert("Class 'top-nav' is not present");
    }
});

Answer №3

Utilize the .is() function with the parameter ".top-nav" attached to .toggleClass() inside a click event handler. Keep in mind that according to the logic presented in the question, an alert with "hey" will appear when the element has the className of top-nav, and "has" will be alerted when .view-projects does not have the className of top-nav.

 $(".push").click(function(){
   alert($(".view-projects").toggleClass("top-nav").is(".top-nav") ? "hey" : "has")
 });

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

 }else if($('.view-projects').hasClass("top-nav")){
  alert('hey');
   
 }
 
 $(".push").click(function(){
   alert($('.view-projects').toggleClass("top-nav").is(".top-nav")? "hey" : "has");
 });
.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>

Answer №4

If you want to achieve a similar effect, you can follow this example

 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');
              if(!$('.view-projects').hasClass("top-nav")){
                 alert('has');
              } else if($('.view-projects').hasClass("top-nav")){
                 alert('hey');
              }
         });
.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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information from a DELETE request using PHP

I have successfully implemented a jQuery plugin for uploading multiple files. However, I am facing an issue with deleting images. When using Firebug, it shows that the JavaScript is sending a DELETE request to the function. How can I retrieve data from thi ...

Learn how to properly display the state array within a React component. Even though the array is present in the state, you may encounter issues where it

I am facing an issue while trying to display data from firestore in my React component. I have updated the global state array with the firestore data and it is being updated, but when I try to render that array, it shows as undefined. Initially, I attempt ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Update the Material-UI theme to a personalized design

I am currently using Material-UI in my React project. However, I'm facing some difficulties in applying a theme globally. Up until now, I have only managed to apply the theme to individual components like this: import { MuiThemeProvider, createMuiTh ...

Is it possible to enhance controllers in Sails.js through extension methods?

There are times when I need to execute a certain action on every page of my web application or make a specific method available to all controllers. Previously, in object-oriented MVC frameworks, I would have my controllers extend a base controller and de ...

What is the best way to center text on an HTML canvas?

Is it possible to center an h1 tag in the middle of an HTML canvas using either JavaScript or HTML? I already have a CSS file for canvas styles. HTML <body> <canvas id="myCanvas"></canvas> <script src="canvas.js"></scri ...

How can you display Unicode characters within an HTML input element with type=submit value?

I am having trouble displaying a right facing triangle character after the main text on a form button based on a designer mockup. The code snippet causing issues is as follows: <input type="submit" value="Add to basket &#9654;" /> The desir ...

Modify the heading color of elements in a class to a distinct color when the cursor hovers over the element

I currently have 3 heading elements: elem1, elem2, and elem3. When I hover over elem1, I want elem1 to turn yellow and elem2 and elem3 to turn purple. If I hover over elem2, I want elem2 to be yellow and the others to be purple. Once I release the hover, I ...

How to create HTML buttons with CSS that maintain proper proportions?

How can I ensure that my HTML buttons adjust proportionally to different screen sizes? I've been working on coding an Android app using HTML and CSS, and everything seems to be running smoothly. However, when I share the file with a friend, he compla ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Integrating custom non-NPM JavaScript files into Angular 2

Currently, the application I am working on is running in an environment with angular 2.0.0 final using typescript and also utilizes angular-cli 1.0.0-beta.15. Since the development of the application involves multiple developers who all use typescript, I ...

Is there a way for me to instruct jQuery to revert an element back to its initial value, prior to any dynamic alterations?

My question is regarding changing the content of a div using the `html()` method in JavaScript. I am currently working on implementing a "cancel" button and would like to revert the content back to its original value without having to completely reset it w ...

What steps can I take to resolve the Unknown browser query issue in React when using Webpack?

Currently, I am engaged in a learning process through egghead.io on integrating React with Webpack. My objective is to customize target browsers and exclusively load essential features using Browserslist. However, I am encountering a complication during th ...

Seeking a jQuery tooltip plugin that offers support for inline popups similar to overLib

Let's dive into the code: <form name='form 1' action='$action'> input tags <table> some tr tags along with td tags and after some lines in the same table under a td tag <td> <a href="javascript:void(0);" oncli ...

Incorporate fresh Google sites into different web pages using iFrame integration

Wishing you a fantastic day! I am currently working on embedding a brand new Google site into another webpage. I attempted to use an iframe for this purpose, but unfortunately it did not work as expected. Here is the code snippet: <iframe width="1280 ...

Building VSCode on Windows: A step-by-step guide

I am currently in the process of compiling https://github.com/Microsoft/vscode from the source code, but I am facing some challenges. After successfully running scripts\npm.bat install, I proceeded to run scripts\code.bat and a strange window app ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...

"Obtaining a MEAN response after performing an HTTP GET

I'm currently in the process of setting up a MEAN app, however I've hit a roadblock when it comes to extracting data from a webservice into my application. While returning a basic variable poses no issue, I am unsure how to retrieve the result fr ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Alter the status of a checkbox programmatically

There are two checkboxes available: <input type="checkbox" id="id3"></input> <input type="checkbox" id="id4"></input> The desired functionality is that when clicking on id3, id4 should also be checked. Initially, this works as e ...