Using jQuery to store the last selected href/button in a cookie for easy retrieval

Recently, I've been working on a document that features a top navigation with 4 different links. Each time a link is clicked, a div right below it changes its size accordingly. My goal now is to implement the use of cookies to remember the last selected link.

Here is the code snippet for the links:

<li><a href="#" class="desktop">Desktop</a></li>
<li><a href="#" class="tablet">Tablet</a></li>
<li><a href="#" class="tabletP">Tablet (P)</a></li>
<li><a href="#" class="mobile">Mobile</a></li>

Next up, we have the jQuery code responsible for controlling the behavior of the div:

$(document).ready(function () {
    $(".desktop").click(function() {
        $(".iframe").animate({"width" : "100%"},{queue: false, duration: 1000 });
        $(".iframe").animate({"height" : "100%"},{queue: false, duration: 1000 });
    });
    // Other click functions for tablet, tabletP, and mobile
});

I am currently using the jQuery Cookie Plugin to create and manage the cookie. Here's an example of how I'm implementing it along with the jQuery code:

// Code snippets for each link click event setting a cookie

Now, my task involves reading the created cookie to automatically select the corresponding link and adjust the div size as needed.

While exploring similar queries, I came across this discussion, which seemed relevant. However, the suggested code in that thread appears somewhat complex.

Below is an excerpt from that discussion showcasing how cookies are utilized to remember link selections:

// Sample code from the mentioned discussion

If anyone could provide guidance on how to effectively read and utilize the cookie value to auto-select the appropriate link, I would greatly appreciate it.

I trust this explanation clarifies my requirements.

Answer №1

The provided code snippet demonstrates how to retrieve the value from a cookie. The specific line responsible for this action is:

cookieVal= $.cookie('lastState')

Additionally, there is a line that checks whether any value was retrieved:

if (cookieVal)

This means you now have the ability to both obtain the value from the cookie and verify if it exists. If a value is indeed present, you can proceed to the next step, which involves selecting a particular link based on the cookie's value.

Since the element's class is stored in the cookie, you can utilize this information when specifying the selector for your simulated click event. For instance:

$('.' + cookieVal).click();

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

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

How is it that my initial response appears correct in the first log, but then suddenly changes to a 1?

I've encountered a strange issue where the response appears correctly in the initial log, but later changes to a '1' when console.log(data); is called. The screenshot illustrates the pattern: https://i.sstatic.net/zaXcg.png If you expand ...

Activating development mode for LessCSS in Node.js

I'm encountering some major difficulties identifying LESS parse errors within a large CSS compilation. The error messages aren't providing much help (at least not for me). Here are my questions: 1. Is there a method to activate more debugging ...

What is the reason for this MongoDB document consistently having the identical nanoid?

Although I've managed to find a solution, my main concern is understanding the root cause of the bug. In the scenarios below, MongoDB documents are being created with identical id and date values respectively. id: { type: String, required: tru ...

Error encountered in Next.js while fetching data: Invalid JSON response received, with an unexpected token "<" at the start of the JSON data

I've been attempting to utilize the getStaticProps function in order to send a request and then pass the retrieved data to a component: However, I keep encountering this error: FetchError: invalid json response body at reason: Unexpected token < ...

Executing a YUI function via HTMLJSGlobal called is feasible

Recently, I stumbled upon the Dial example on the official YUI website and was thoroughly impressed. I managed to get the function working perfectly in a JS file, but now I am facing issues trying to call it within the HTML page with specific parameters su ...

The font remains the same despite the <Div style=> tag

I have a script that loads external HTML files, but I am facing an issue with changing the font to Arial. The script is as follows: <script type="text/javascript"> $(document).ready(function(){ $("#page1").click(function(){ ...

The issue with updating the menu class in Internet Explorer 8 is not being resolved

Here is a code snippet using JavaScript: var x = jQuery(window).innerHeight(); jQuery(document).scroll(function() { if (jQuery(this).scrollTop() >= x) { jQuery('#nav').removeClass('nav').addClass('topfix_nav'); ...

What is the method for incorporating locales into getStaticPaths in Next.js?

I am currently utilizing Strapi as a CMS and dealing with querying for slugs. My goal is to generate static pages using getStaticPaths and getStaticProps in Next.js. Since I'm working with multiple locales, I have to iterate through the locales to re ...

I encountered a SyntaxError indicating a missing ")" right before utilizing jQuery in my code

When trying to run the code below, I encountered an error in the console stating SyntaxError: missing ) after argument list. $(document).ready(function() { $(".blog-sidebar-form form").before("<p class="blog-sidebar-inform>Dummy Text</ ...

Navigating the Google Maps API: Implementing Scroll Zoom to Focus on a Single Marker

I'm looking for a solution for my project where the scroll zoom function will focus on zooming in on a marker or specific point rather than defaulting to the cursor. The current behavior is that the scroll zoom always centers on the cursor. Can anyone ...

Excluding form items that are disabled from a request in ReactJS

In my code, I am dealing with a Form section that contains multiple Collapse.Panel sub-sections. Interestingly, the Form.Item elements within collapsed panels are not included in the form values upon submission. However, I have noticed that certain InputNu ...

Instead of displaying the location attribute in an alert, populate it into a text area

I have a function that can retrieve my current location using longitude and latitude coordinates. However, I am looking to automatically fill a text area (Populate Here) with the results instead of displaying an alert. <!DOCTYPE html> <html> ...

Adding an event listener to the built-in arrow buttons on the `<input type=number>` element is a simple way to enhance user interaction

<input type="number" id="test"> I'm trying to figure out how to set an event listener for the two arrow buttons on the right of this number input field. Typically, we can use jQuery like: $("#test").on("cl ...

What is the best way to adjust the height of the second column downwards?

I am trying to achieve a 2-column layout with both columns at the same height. This is how it currently appears: And this is how I want it to be: Here is my code snippet: html { background-color: lightblue; font-family: Tahoma, Geneva, sans-serif ...

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

Incorporating Recoil with React, a substantial array is experiencing lags due to numerous re-renders

I currently have an array of around 400 objects within my application. The hierarchy of components in my tree is structured as follows: App -> Page (using useRecoilState(ListAtom) for consumption) -> List -> Item (utilizing useSetRec ...