Utilizing jQuery to Execute a Function Upon Addition or Removal of Class Names

Currently, I am working on a function that includes a conditional statement to display an alert when a specific class name is removed from a div layer. Below is the code snippet:

<div class="ui-tabs-panel ui-tabs-hide">panel</div>
<div><a href="#" class="control">control</a></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js?ver=3.0"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
    $('.control').hover(
        function() {
            $('.ui-tabs-panel').removeClass('ui-tabs-hide');
        },
        function() {
            $('.ui-tabs-panel').addClass('ui-tabs-hide');
        }
    );
    if ($('.ui-tabs-panel:not(.ui-tabs-hide)')) {
        alert('hello');
    }
});
//-->
</script>

The purpose of the "control" link and its associated function is solely to manage the addition and removal of the specified class name.

Currently, the alert pops up upon loading the page, which is not intended. This issue might be due to incorrect syntax usage in my code. Additionally, removing the ui-tabs-hide class from the div containing the "control" link does not trigger the alert as expected. It seems like I need to include some kind of event binder, but my knowledge of event binders is limited.

If anyone can assist me with this problem, I would greatly appreciate it.

Answer №1

It's uncertain whether detecting an "event" like manipulating a class name on an element is possible.

The reason the alert appears upon page load is because it is inside an if block within jQuery's $(document).ready function, which triggers once when the page loads. Essentially, you have not linked this to any event besides DOM ready, so it activates when the page loads and the DOM is ready, with the if statement being true.

Furthermore, using the .length property in your expression is necessary:

if ($('.ui-tabs-panel:not(.ui-tabs-hide)').length) {
    alert('hello');
}

// Or...
if ($('.ui-tabs-panel').not('.ui-tabs-hide').length) {
    alert('hello');
}

NOTE

I want to highlight that the above code relies on what you intend to achieve with your class change detection actions - .length provides the total number of matching elements, so if you have multiple .ui-tabs-panel's, there may be a false positive. If dealing with more than one result, consider using an .each() call on the jQuery outcome or another approach.

One method could involve setting a timeout to verify if the ui-tabs-panel class elements also possess the ui-tabs-hide class:

http://jsfiddle.net/userdude/4cF5v/

$(document).ready(function(){
    $('.control').hover(
        function() {
            $('.ui-tabs-panel').removeClass('ui-tabs-hide');
        },
        function() {
            $('.ui-tabs-panel').addClass('ui-tabs-hide');
        }
    );
    runCheck();
});

function runCheck(){
    if ($('.ui-tabs-panel').hasClass('ui-tabs-hide')) {
        alert('hello');
    }
    setTimeout(function(){runCheck()},5000);
}

I introduced a runCheck() function, placed the .hasClass() call inside it, and initiated a timeout, ensuring that runCheck() repeats, sets the timeout again, creating a continuous loop.

The 5000 millisecond timeout prevents the browser from entering an infinite loop (checking every 5 seconds). Typically, a range between 50 and 500 milliseconds should suffice; 1000 equates to 1 second.

With a 50 millisecond timeout and an alternative method to avoid locking your computer into an alert() loop, here is the updated version:

http://jsfiddle.net/userdude/k44qR/

Hover over the control link, hover out, then hover over again to observe it start, stop, and restart.

Answer №2

If you want to create a custom event, follow these steps:

Check out this demo on how to implement it: http://jsfiddle.net/k44qR/2/


$(document).ready(function(){
    $('.control').hover(
        function() {
            $('.ui-tabs-panel').removeClass('ui-tabs-hide').trigger("displayPanel");
        },
        function() {
            $('.ui-tabs-panel').addClass('ui-tabs-hide');
        }
    );

    $('.ui-tabs-panel').bind("displayPanel",function(){alert("hello")});

});

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

When the mouse is moved, display a rectangle on the canvas

I am having an issue with drawing a rectangle on canvas. The code below works fine, except that the path of the rectangle is not visible while the mouse is moving. It only appears when I release the mouse button. Any assistance would be greatly appreciate ...

Guide to Using Jquery to Locate YouTube or Vimeo Videos Embedded in HTML

Is there a way to use Jquery, javascript or php to choose a YouTube or Vimeo video directly from a webpage? I would greatly appreciate any assistance! Many thanks ...

Simultaneously sending jQuery.ajax data while submitting a form

I'm facing a bit of a dilemma here. I have a form with multiple fields, including one for entering links. When you input a link and click the add button, the link is added to a link_array using jQuery. My goal is to send this array through the jQuery. ...

Stop the automatic hiding of the sticky header when reaching the bottom of the page

I have implemented the position: sticky property for my website's header. However, I am facing an issue where the header becomes hidden when I scroll halfway down the page (bottom on mobile devices). Can anyone suggest a solution to fix this problem? ...

The icon is being displayed as text instead of the actual Fontawesome icon

Using jquery version 3.3.1 I am dynamically creating an anchor tag: let link = $("<a>"); link.attr("href", "#"); link.text("My anchor" + ' <i class="fas fa-people-carry"></i>'); However, when I try to display ...

Retrieve the server code periodically and automatically refresh the form elements

Let's kick things off by explaining how the application functions: (please note there are multiple users on the page such as Patient M, Patient E, and so forth) 1) Check In: Next to Patient X's name, you will find a button labeled Check In. This ...

Troubleshooting: jQuery AJAX not Invoking C# Method in ASP.NET MVC Application

I am attempting to initiate a call to the controller from the views using jQuery ajax, however, it seems like the controller is not being called. The goal is to pass the token value obtained on the registration page to the controller in order to utilize it ...

What is the best way to use absolute positioning in React Native to align an element with its grandparent?

I am trying to position a Font Awesome icon in a React Native project using absolute positioning relative to the grandparent element, rather than its direct parent. After some research, I came across the following information on this page: https://reactna ...

Unable to create a responsive layout because of the use of inline CSS with "margin"

Currently, I am working on a design for a webpage that must be responsive to large, medium, and small screens. To achieve this responsiveness, I am using Material UI Grid container and placing Chips inside it with the style={{ marginLeft: 60 }} from the se ...

Appium successfully triggers a click action on an obscured WebElement

I am facing an issue with my android appium test for an android application. The app contains a webview with a loader that appears at the start. There is a link within the app that I need to click on, which should navigate to another web-page. Although ...

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 ...

I am in search of a container that has full height, along with unique footer and content characteristics

I have set up a jsfiddle to demonstrate the scenario I am facing: There is a basic header, content, footer layout. Within the content-container is a messenger that should expand to a maximum of 100% height. Beyond 100% height, it should become scrollable. ...

Is it possible to access an external website by clicking on a link within a DIV element?

I have a basic website set up like this sample.php <html> <head></head> <body> <a id="myLink" href="http://sample.com">Click!</a> </body> </html> I displayed this website within a DIV-Container on a ...

Is it okay to make multiple calls using jQuery/AJAX if confirmed?

I am currently working on an ajax feature to delete a comment. Before the deletion process is executed, I prompt the user for confirmation. However, there seems to be an issue where if the user initially selects 'CANCEL' and then decides to proc ...

Enhancing User Experience in VueJS with Pug Templates and Transitions

Managing multiple 'pages' of content within a multi-step process can be challenging, especially when trying to incorporate VueJS's transition feature for a carousel-like slide in/out effect. The contents being transitioned are stored in sepa ...

"Incorporate Bootstrap drop-down and button together for a stylish group feature

I am looking to format the code below to resemble the layout shown in the image using Bootstrap 3.3. When there isn't enough space to show all elements in a single line, I want them to stack vertically so that each element utilizes the entire width of ...

What is the best way to create a responsive grid layout for my form using Bootstrap?

I have designed a form using bootstrap 5 with 1 row containing 4 columns (1 dropdown menu and 3 buttons). While it looks fine on my desktop, the problem arises when I view the page on a mobile device. The buttons shrink and remain on the same row instead o ...

What is the reason behind the reversal of the response list by $.getJSON?

Here is the code I am working with: // Setting up an array for tooltip content var Data = []; var search = $("input#field_search").val(); var combo = $("select#search_option").val(); var jsonUrl = "ajax.php?module=formation&action=get_participant_list ...

Unable to get jQuery waypoints to function on local server

Currently, I am working with jQuery. I downloaded an example shortcut for infinite scroll from jQuery Waypoints and tried to use it. However, when the page reaches the end, the web console displays the following error: XMLHttpRequest cannot load file:// ...

Load Bootstrap CSS file externally on a website dynamically

Although my knowledge of JavaScript is limited, I am the recipient of a small web application from a friend that is being utilized by multiple companies. As each company requires specific modifications in the appearance and CSS of certain webpages, it can ...