Hiding and displaying a div with jQuery cookies

I'm in the process of setting up a cookie using jQuery Cookie to display an alert for new visitors. When the "close" button is clicked, a cookie will be set to prevent the alert div from displaying again. Additionally, I want this cookie to expire after 24 hours.

After experimenting with some code, I was able to achieve the desired functionality, but there's one issue. The alert div is shown by default and only hidden when the close button is clicked. However, when the cookie exists, the alert still displays briefly before being hidden.

How can I modify the code below so that the div is hidden by default? If the cookie doesn't exist, it should be displayed, and if the close button is clicked, a cookie is generated to hide the alert for 24 hours?


if ($.cookie('alert')) {
    $('.alert-box').hide();
} else {
    $(".close").click(function() {
        $( ".alert-box" ).slideUp( "slow", function() { });
        $.cookie('alert', true);
    });
}

Answer №1

To make the alert-box hidden by default and only show it when there's no cookie, you can utilize CSS and JavaScript:

CSS:

.alert-box {
    display: none;
}

JavaScript:

// Check for a cookie
if (!$.cookie('alert')) {
    $( ".alert-box" ).show();
    $(".close").click(function() {
        $( ".alert-box" ).slideUp( "slow" );
        // Set the cookie to expire in 24 hours
        var date = new Date();
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000); 
        $.cookie('alert', true, { expires: date });
    });
}

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

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

AngularJS: Optimizing load times by consolidating all partial views/templates for production

My goal is to maintain views in a highly modular way. This entails using numerous small, generalized HTML snippets that come together to form the actual HTML page. While ng-include and custom directives with templateUrl work well for me during development, ...

Creating interactive animations in Jquery by clicking on one object to trigger animation of another object

I've created a cool soundboard with interactive buttons. Each button plays a unique sound when clicked and changes appearance when hovered over. However, I'm facing a challenge in animating an image to move from the left side of the screen to 500 ...

Incorporate a new tab based on specific conditions in Excel 2016/365 using office add-ons (Javascript API)

I am currently in the process of developing an Office Add-in for Excel that requires the addition of a worksheet conditionally. I need to ensure that if the worksheet is not already present, it must be added and filled. If it already exists, I just need to ...

The submit button on the HTML form is not functioning properly and requires activation

Currently, I am a student focusing on honing my skills by working on an app for a blog post. To kickstart my project, I downloaded the "clean-blog" template from the startbootstrap website. If you are interested, here is the link to the template: My curr ...

"Want to know the trick to make a Vuetify component stretch to fill the rest of the screen's

Imagine a scenario where there is content above and below a table on a webpage. The goal is to get the table to occupy the remaining height of the page without affecting other elements. This ensures that the content below the table is always visible at the ...

Adjust the color of radio button text with Jquery

Here is a sample of radio buttons: <input type='radio' name='ans' value='0'> Apple <input type='radio' name='ans' value='1'> Banana <input type='radio' name='ans&apo ...

What is the easiest way to switch a checkbox on and off after pasting a value from

checklist = [ '1', '2', '3', '4', '5', '6'...]; user = {[ {"name": "tom", "checkbox": [ '1_A', '3_B' ]}, {"name": "sam", "checkbox": [ '1_C', '3_A&apo ...

If an element contains a specific class, then set its display property to none

I am attempting to utilize the hasClass method in JavaScript to determine whether a div should be hidden (display: none) or kept visible as usual. Below is the snippet of code I currently have: if (!$('cool').hasClass('hot')) { ...

working with received data from a JavaScript object

Looking for code assistance, I have a data object serving as my data source. var data = [ { "label":"May 7", "value":25736.6, "proID":"ISB" }, // more data objects... ]; I'm manipulating this data to generate another ...

Conflicting encoding of BeautifulSoup object extracted from a webpage containing duplicate meta tags. How can I ensure that the encoding remains consistent?

After fetching data from a website using the BeautifulSoup module, I discovered that the source encoding for the document is 'iso-8859-1' but BeautifulSoup automatically transcodes to 'UTF-8' upon creation of the object. import requests ...

Store the response token from a Request.post in a variable

To complete a URL, I only need to extract the token provided in the API response. The response body must be saved in a variable for later use. I am currently using Protractor for automated testing, and as part of this process, I need to consume an API tha ...

There seems to be an issue with `loading.tsx` not functioning properly while generating a page for

When navigating in a Next JS 14 app using the router, one may notice that when clicking on a Link component, the URL does not change immediately. Instead, there is a delay before the new page loads. During this transition period, the content from the loadi ...

Using JavaScript to load content with AJAX on skip links

Is there a way to prevent the error "loadWithAjax is not defined" from occurring while using the script below? addEventListener('click', function (ev) { if (ev.target.classList.contains('bpb')) { ev.preventDefault(); ...

Each time the Jquery callback function is executed, it will return just once

Whenever a user clicks on the "customize" link, I trigger a function to open a dialog box. This function includes a callback that returns an object when the user clicks "save". The problem is, each time the user clicks "customize", the object gets returned ...

Troubleshooting Issue: jQuery Scroll Feature Unresponsive

I'm having an issue with my website where it's not scrolling down when I click on an arrow. You can see the site here. Despite trying on different divs, nothing happens when I click. I've also tested it on other sections with no success. & ...

Difficulty encountered when attempting to generate a Firestore document with the Firebase ID of a user

I am in the process of building a web application using Vue.js + Firebase. Currently, I am working on implementing a sign-up feature for the project. The sign-up feature utilizes a Firebase auth function and it is functioning correctly. However, I also ne ...

Is there a way to replace a CSS class applied within an iframe?

I have a third-party iframe widget component embedded in my page. The only HTML string present in the body of my page is this iframe, which includes a custom button styled by the widget.jsp. In Chrome's inspector, I can only see the <iframe> com ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

Issues with utilizing Fetch API and JSON Data

I'm encountering some difficulties while trying to interact with my json file. I am using the fetch API to retrieve my json file but, unfortunately, when I log the response to the console, I don't see any data returned. Instead, what appears is a ...