Use jQuery to apply a class to the body element whenever it contains content

When the body loads the text 'added to your shopping cart.', jQuery needs to add a class to the div with the ID #header-cart.

<span> added to your shopping cart.</span>

The class should be added and then removed after 5 seconds.

Answer №1

If you're looking to achieve a certain effect, consider trying the following script:

$(document).ready(function(){

    //define the specific text you are searching for
    var searchText = " added to your shopping cart.";
    //specify the target element where the text might appear
    var targetElement = "#header-cart";
    //set a temporary class that can be added for styling purposes
    var tempClass = "skip-active";

    //check if there is an existing span element containing the desired text
    if($("span:contains('" + searchText + "')").length > 0){
       //if the text is found, add a class to the element and remove it after a set delay
       $(targetElement).addClass(tempClass);
       setTimeout(function() { 
           $(targetElement).removeClass(tempClass);
       }, 5000);
    }
});

Feel free to explore this JSFIDDLE demo

Answer №2

To enhance the functionality of your cart experience, my suggestion would be to trigger a function when an item is added to the cart instead of constantly checking for changes in the DOM.

For instance, if a user clicks on the #add-to-cart button to add a product, you can use the following script:

$(document).on('click', '#add-to-cart', function() {
    $('body').addClass('yourClass').setTimeout(function() { 
       $('body').removeClass('yourClass');
    }, 5000);
    // Add any additional code here
});

If you still want to monitor specific text insertion, you can check it whenever an event occurs (such as page load or button click):

// This snippet will only work if the page is refreshed and the text appears in the specified span upon loading
$(window).load(function() {
    var span = $('li.success-msg span').text();
    if (span.indexOf('added to your shopping cart') >= 0) {
       // Perform desired actions here
    }
});

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

Is there a way to set the background image to scroll vertically in a looping pattern?

Is it possible to achieve this using only HTML5 and CSS3, or is JavaScript/jQuery necessary? ...

What could be the reason for my array being nested inside another array as a value in a dictionary

I am having some difficulty understanding how the selected array is being returned in my dictionary. Could you please provide me with an explanation? The language being used is javascript. I have constructed a dictionary with arrays as values. However, wh ...

Tips for implementing jQuery functions such as lightbox and other features on a page loaded via ajax requests

I have a specific requirement for my page. I designed a section to display various departments, where clicking on $('.getDetails') will reveal a list of employers from each department along with some details. Furthermore, clicking on an employer& ...

Jquery AJAX request encountering a syntax error due to an invalid label

I'm having trouble with an ajax call to the server that should return a JSON object. I can't seem to figure out what's wrong, so any help would be greatly appreciated. Here's the snippet of code: $.ajax ({ type : "GET", ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...

The change event for the select element is malfunctioning

Currently, I am deep diving into Nodejs with the second edition of the node cookbook. This book has caught my attention because it explains concepts using practical sample code, making it easier to grasp. The example code I am working on is related to Br ...

Creating interactive dropboxes in PHP and JavaScript to dynamically change options and display the selected value

Currently, I am in the process of working on a dynamic dropdown menu that involves select boxes. These values are being pulled directly from a MySQL database (if you're interested, here is how I set up the database). I have successfully retrieved and ...

Revise the color of the selected image

click here for image description I'd like the area's color to change when the mouse hovers over it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA ...

What is the best way to create pages that showcase 10 posts each?

Currently, I am facing a challenge with displaying 100 posts using the Fetch API on one single page. I am looking for a way to create separate pages where each page would showcase only 10 posts. Below is my existing JavaScript code: fetch('htt ...

Using PHP and AJAX to send a form

Currently, I am attempting to integrate ajax functionality into my form in order to submit it without refreshing the page. However, I have encountered an issue with the php echo command not functioning as expected. When I remove the ajax code, the form s ...

How can I customize button colors in react-bootstrap components?

Changing colors in react-bootstrap may be a challenge, but I'm looking to customize the color of my button beyond the primary options. Any suggestions on how I can achieve this using JS and SCSS? ...

Empty JSON response returned from PHP using Ajax is currently null

I am facing an issue where the geolocation JavaScript array that I pass to a PHP script via ajax is always NULL. I have tried multiple approaches but cannot seem to figure out the root cause of this problem. Here is a snippet of my JavaScript/jQuery code: ...

Why aren't my div items appearing when clicked on?

I'm currently working on a single-page website and looking to show content based on the menu item clicked without refreshing the page. I'm attempting to achieve this using jQuery but seem to be running into some issues. Can someone please help me ...

What steps should be taken when handling an AJAX request that returns a false result from PHP?

I need help with a form I'm creating that includes a text box labeled "mobileNo" to search for records in a PHP database using AJAX. When a record is found, it should display "Record found". If no record is found and PHP echoes "Record not found", I w ...

Challenges with placement of Div elements

Check out my jsFiddle example here: http://jsfiddle.net/pqCGd/. Within the jsFiddle, you will find a large messages div that contains multiple message divs. In this example, I have manually provided an example of a message div instead of using auto-genera ...

Rails database is not properly embedding into Javascript when using as_json.to_json method. (results in "&quot" characters)

I have scoured nearly every SO past question without success. Within my main.html.erb file, I am mixing html/erb/javascript. (I understand it's not ideal, but I'm still grappling with asset pipelines and this is just a small project.) My goal i ...

Issues with Firefox's -moz-placeholder functionality were observed not being functional as

I'm having trouble styling this placeholder in Firefox 13.0.1 Here is the input field with a placeholder: <input class="textFieldLarge" placeholder="Username" id="username" name="username" type="text" /> This is the CSS associated with it: . ...

Reduce the occurrences of mouseover events being triggered

Is there a way to reduce the number of mouse over events triggered? I want to maintain the functionality of mouse over, but with fewer event triggers occurring. $(clientFrameWindow.document.body).on("mouseover",function () { //I am looking to slow down t ...

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

Ways to adjust the size of v-btn

Objective: My current task involves enhancing the customization options for Vue components, specifically focusing on adjusting the size of a button component based on user input. Our project utilizes Vuetify. Previous Code: <v-btn @click.prevent=&quo ...