Trouble with the display none function

I am trying to achieve the following:

If my shopping cart is empty, I want another div to display over the top of it. Instead of seeing the cart, users should see a message saying 'your cart is empty'.

Currently, I have set the other div to display:none in my CSS, but it seems to always be displayed! I am attempting to use JavaScript to hide or show it. The cart I am using is simplecart.js.

Here is my CSS for the cart and the cart-empty div:

.cart{
margin: 30px 0 0 0;
background:red;
position:relative;
}
#if-cart-empty{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
display: none;
background:w

This is the HTML:

<div class="cart">',
<div class="simpleCart_items"></div>',
<span class="simpleCart_quantity"></span> items - <span class="simpleCart_total"></span>',
<div class="checkout">',
<a href="javascript:;" class="simpleCart_checkout">Checkout</a>',
</div>',
<a href="javascript:;" class="simpleCart_empty">Empty Basket</a>',
<div id="if-cart-empty" style="display: none">Your cart is empty.</div>',
</div>

And this is the JavaScript:

checkCart();
$('.itemremove').click(function(){    
$('.itemContainer').remove();  
checkCart();
});

function checkCart(){
var item = $('.itemRow');
if (item.length > 0) {
$('#if-cart-empty').hide();
} else {
$('#if-cart-empty').show();
}
}

Can someone help me get this to work? Thanks!

Answer №1

Typically, in a scenario like this, when you set display: none; in the CSS styles and then try to use jQuery to .hide() or .show() the <div>, it may not work as expected on the first try. One way to work around this issue is to:

  1. Create a class class="hide" and toggle this class using .toggleClass("hide").
  2. Hide the div by using the .hide() method within $(document).ready();.

This behavior can be considered a bug/feature of jQuery/JavaScript, and these methods provide a reliable workaround. If there is no display: none in the element's style attribute, jQuery will treat it as visible by default. For further illustration, I can share a fiddle with you.

Fiddle: http://jsfiddle.net/praveenscience/r8y6E/

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

Shorten a value within an array of objects using JavaScript

How can I truncate a value in an array of objects based on specific criteria? Let's use the following example: var items = [ { name: "CN=arun, hjsdhjashdj,jsdhjsa,kshd", status: "Present" }, { name: "CN=manohar, abcdefghij,111111,2222222", s ...

Transmit an Array using Ajax and retrieve it on an ASP Classic page

I am facing a challenge where I need to pass an array using AJAX on an ASP page. After trying to send it as GET method and checking the data being received, I noticed that only the LAST record of the array is being processed by ASP. How can I successfu ...

The error message "ReferenceError: express is not defined" indicates that Node.js is

Recently, I started using Nodejs to develop web servers, utilizing the express module. To install it, I used the command: "sudo npm install -g express". However, upon running the program, an error occurred: "ReferenceError: express is not defined ...

php$insert new field into mysql table using form insertcell

How do I insert a column in MySQL? I am struggling with the insertCell form. I have tried but I can't seem to add a MySQL column using my JavaScript code with PHP. I am familiar with Php PDO, but this seems difficult to me. Can someone guide me on ho ...

Attempting to establish both the minimum and maximum time date in a jQuery datepicker across two separate inputs

I've been working on a project for my classes that requires setting minimum and maximum dates for two input fields. The first input should allow dates from now to 12 months in the future, while the second input should be restricted to dates picked wit ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

"Owlcarousel Slider: A beautiful way to showcase

Currently, I am working on a project that involves implementing a slider. Since I lack expertise in JavaScript, I opted to use a plugin called owlcarousel. The challenge I'm encountering relates to the sizing of the container for the items. I'm ...

JavaScript horizontal slider designed for a seamless user experience

Currently, I am in the process of developing a slideshow that includes thumbnails. While my slideshow is functional, I am facing an issue with limited space to display all thumbnails horizontally. I am considering implementing a horizontal slider for the t ...

Click Event for Basic CSS Dropdown Menu

My goal is to develop a straightforward feature where a dropdown menu appears below a specific text field once it is clicked. $(".val").children("div").on("click", function() { alert("CLICK"); }); .container { display: inline-block; } .val { d ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

Synchronization Issue between Ionic Popover templateURL and Angular ng-model

In my project utilizing the Ionic framework, I encountered an issue with the code snippet below: $scope.loginCountryCode; $scope.loginPhone; // Code continues... <div class="container"> <label class="item item-input&quo ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Vertical scroll through a list of columns with a stationary header, while allowing both the list and the header to

Check out this JSFiddle example: https://jsfiddle.net/jefftg/1chmyppm/ The layout currently has orange header columns and white list rows that scroll together horizontally. However, the goal is to have the white list rows scroll vertically while keeping t ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

What is the procedure to switch the state using useState when an event is activated?

I'm trying to learn React by implementing a basic shop. One idea I had was to have multiple product images and when a user clicks on an image, it flips around to display additional information such as comments and ratings for the product. For this pr ...

Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upo ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...