I'm trying to determine which jQuery event would be more beneficial for my needs - should I go with

I'm facing a dilemma

On my website, I need to capture the value of a span within a modal. The value changes when the modal is opened and reverts to the old value when closed. This particular value represents the cart total in my online store. Whenever I click on the "add product to cart" button, the modal with the updated value appears.

I attempted to achieve this using the following code:

$('.ajax_add_to_cart_button').click(function()
{
        if($('#layer_cart').css('display') == 'block')
        { 
            var total_product = $('.ajax_block_products_total').text().replace('€', '').replace(',', '.');
            alert(total_product);
        }  
});

However, this only returned the old value because the modal is not yet opened when the "add to cart" button is clicked, causing it to have a display-none status.

What would be a more suitable event to check if the modal has truly opened? Since there is a slight delay due to an AJAX request to fetch cart details from the server, I am unsure which event timing would be appropriate for capturing the new value.

I initially tried implementing the action on the "add to cart" button's onclick event, but since the modal had not yet opened, it retrieved the outdated value.

Any assistance or suggestions are greatly appreciated.

Answer №1

To begin, you must display the layer_cart in order to check for the visibility set by the display:block css rule.

Next, to update the value of your total_product, you will need a variable where the new and old values can be added together to get the total value.

Take a look at this example:

var total_product = 0;

$('.ajax_add_to_cart_button').on("click", function()
{

  $('#layer_cart').show();
  
  if($('#layer_cart').css('display') == 'block')
  { 
    total_product += parseInt($('.ajax_block_products_total').text().replace('€', '').replace(',', '.'));
  }  
  
  alert(total_product);
});
#layer_cart
{
  border: 1px solid red;
  height: 200px;
  width: 200px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="ajax_add_to_cart_button">Add to cart</div>

<ul id="layer_cart">

</ul>

<div class="ajax_block_products_total">€100</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

Dealing with a surprise JSON error in Express.js using Javascript

Dealing with Unexpected JSON in my express js application using try and catch. I attempted to achieve this as follows: try{ let body = JSON.parse(req.body); }catch(e){ res.json({ error:e }) } However, the Unexpected JSON error is not caught in ...

React does not accept objects as valid children

Currently, I am working on developing a stopwatch using reactive js. Here is the code snippet that I have been working on: <div id="root"></div> <script src="https://unpkg.com/library/react.development.js"></script> <script sr ...

Manage the number of items in each column using flexbox or grid layout strategy

Here's a similar situation .items { width: 100%; display: flex; align-items: center; justify-content: flex-start; flex-wrap: wrap; background: #cecece; padding: 10px; margin: 20px; } .item { height: 100%; flex: 0 0 calc(50% ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

The JQuery $post() function appears to be unresponsive

I have a HTML/JavaScript frontend and a PHP backend. I am trying to transmit a JSON string array from my frontend to backend using AJAX, but it is not working as expected. The code snippet below shows the implementation that is causing issues: <html> ...

The onclick event seems to be malfunctioning on the website

My goal is to implement a modal box that appears when a user clicks a button and closes when the user interacts with a close button within the modal box. I have created two functions for this purpose: check() : This function changes the CSS of an element ...

Executing a function after the completion of another

Here is my function: function functionName($results) { //do some stuff disableSave() } When this function runs, I want to call the enableSave() function. How can I achieve this? I attempted to pass the function as a callback but I am unsure wher ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Expanding the table area in bootstrap

I am currently working on a video slider using bootstrap. I have added a table within the slider (carousel) and it is functioning perfectly. However, I am now looking to update the layout to resemble the image below. I have successfully applied the backgro ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

Is there a way to trigger both the link and the div element simultaneously?

Is there a way to make both the button and the link light up simultaneously when hovering over the div element, instead of just the button lighting up first? <div id="b1"; class = b> <a href="test.html">BUY</a> < ...

How can I retrieve XML through a URL using HTML5 and JavaScript?

Currently, I am looking to access an XML file through a URL link. My main goal is to retrieve the file automatically and extract its contents for further processing. However, I am facing difficulties in finding the appropriate method to obtain and read t ...

Tips on updating a specific value within an element stored in an array

I'm currently in the process of setting up a table where each row contains unique values. Using a for loop, I am able to generate these rows and store them in an array. Now, my question arises when I consider modifying a particular value with the id " ...

What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked. However, there ar ...

Error message: Metro bundler is unable to access the properties of an undefined object (specifically, 'transformFile')

Having encountered a problem after updating my project to expo SDK 43, I have experimented with different LTS node versions (14.8.1, 16.1.3, and 17.0.1) without success. Interestingly, my colleagues using Macs with Intel chipsets do not face this issue, le ...

jQuery validation does not work properly when using .element(element) in a custom method

I am struggling with a custom rule that is supposed to check dependencies by validating other inputs it relies on. However, when I implement this validation, it seems like all other validations are being ignored. Here is my custom validation rule: jQuery ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

Ways to stylize bullet points in lists with CSS in HTML document

I am currently working on a Q&A page using simple HTML. This is the current appearance of my page. Check it out here on JSFIDDLE. My task involves adding an 'A' to the answer for each question. Some answers have multiple paragraphs, so the ...

Is it acceptable to compare a boolean with a string?

In my code, I have a variable called isRefreshed which is initially declared like this: var isRefreshed = ''; Sometimes, in certain scenarios, isRefreshed can be assigned a boolean value, for example: isRefreshed = false; Now, there is an if ...

What is the best way to ensure that my grid remains contained within its designated area?

I need to incorporate a grid of 16x16 or 64x64 into my layout without it overflowing. I'm considering using flexbox, but unsure of the implementation process. My goal is to have the grid resize based on the container size rather than exceeding its bou ...