Reveal a secret div on the page by clicking a link to unlock its contents

I'm working on an HTML page where a hidden div is supposed to become visible when a button is clicked. The code snippet I have is:

$('#display').click(function(){
    $('#itemList').removeClass('hide');
    ...
})

Now, on another page, there's a link that takes the user back to the first page. When this link is clicked, the element with id='itemList' should also become visible. Here's the code for that link:

<a href='firstHTML.php'> View items</a>

I'm not quite sure what else I need to add to ensure that the other page loads with the previously hidden element now visible. Any suggestions or help would be greatly appreciated.

Answer №1

If you're looking for a reliable solution, localStorage is one of the most suitable options. Alternatively, you could also consider using Cookies or passing values through string queries to another page.

Let me demonstrate how you can utilize localStorage by storing an ID on click of an anchor:

<a href='firstHTML.php' data-showId='itemList'> View items</a>

Next, attach an event to the anchor:

$("[data-showId]").bind('click',function(){
    var idToShow=$(this).attr('data-showId');
    if(idToShow)
      store('visibleId', idToShow);
});

Now, all that's left is defining these essential functions:

   function setup() {
        var tmp = get('visibleId');
        if (tmp)
          showDiv(tmp);
    } 
    function showDiv(cls) {
        $("#"+cls).removeClass('hide');
    }
    function get(name) {
        if (typeof (Storage) !== "undefined") {
          return localStorage.getItem(name);
        } else {
          window.alert('Please use a modern browser to properly view this template!');
        }
    }
    function store(name, val) {
        if (typeof (Storage) !== "undefined") {
          localStorage.setItem(name, val);
        } else {
          window.alert('Please use a modern browser to properly view this template!');
        }
    }

Don't forget to invoke setup() when the DOM is ready.

Answer №2

To start, I would implement the jQuery function to toggle the visibility of the list instead of relying on a separate CSS class:

$('#display').click(function(){
    $('#itemList').toggle();
    ...
})

One potential solution for your issue could involve using a query parameter, like so:

<a href='firstHTML.php?list=show'> View items</a>

And using jQuery:

  1. Create a helper function (Adapted from Get url parameter jquery Or How to Get Query String Values In js):

    $.urlParam = function(name) {
    
      var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    
      if (results==null){
        return null;
      }else{
       return results[1] || 0;
      } 
    }
    
  2. Retrieve the specified property:

    var listStatus = $.urlParam('list');
    
  3. Show the list if necessary:

    $( document ).ready(function() { 
      if(listStatus == 'show') {
        $('#itemList').show();
      }
    });
    

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

Remove the browser cache for the user through Javascript

Can JavaScript be used to clear the browser cache? Occasionally, when updating a new release in my application, I need to instruct users to clear their browser cache in order to view the latest changes. This application is developed with Vue. ...

JQuery is unable to access the initial JQuery objects when a new div is loaded during an AJAX event

My page contains many JQuery objects. Also, there is a form where users can input search terms in different fields and click a search button to send an AJAX request to the server. The resulting HTML is then loaded into a div. However, I am facing an issue ...

Prevent the ng-model from updating a disabled input field within an ng-repeat loop

In my table, I have 5 days of the week displayed using an ng-repeat for each day. Additionally, there is a button on the page that fills all inputs with data retrieved from the backend. Here is a snippet of my code: <thead> <tr> <th&g ...

Utilizing data attributes over classes for styling in CSS

Programming Languages <span data-bar> ... </span> JavaScript span[data-bar]{ ... } Do you agree with this coding practice? Are there any potential pitfalls? I believe implementing the data- attribute is beneficial when dealing with a large ...

The date functionality is malfunctioning on Internet Explorer 8

Below is the code snippet that functions well on Chrome: function calculateTimeDifference(str1,str3,str4) { var dym1 = str1.split("/"); var d=new Date(); var dym2 = d.getMonth() + 1 + " " + d.getDate() + " " + d.getFullYear() + " " + d.getHo ...

Flick user media cards left or right to uncover the following one

I am currently working on creating a widget that will display user media objects in a horizontal layout using ng-repeat. The goal is to allow users to swipe left or right to reveal the next media card, similar to the image shown below. In the example, you ...

The django-filters form seems to be experiencing some display issues where only the submit button is visible and

custom template code snippet <form method="get"> {{ filter.form.as_p }} <input type="submit" value="Press" /> </form> {% for obj in filter.qs %} {{ obj.WorkType }} - ${{ obj.desired_wage }}<br ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

What is the best way to stack three boxes on top of one another in Nextjs Tailwind?

Currently, I am working on creating a design with 3 boxes stacked vertically and then adding an image to it. You can see the example below: https://i.sstatic.net/jViO.png I have successfully implemented this layout, but I am facing an issue where the box ...

Unveiling Fresh URLs within an iFrame

Here is the current situation: www.mywebsite.com/Pagex.html - On this page, there is an iFrame with a default URL (src) from a different domain than the host page (Pagex.html). The code inside the iFrame is a user input form with a submit button. Upon su ...

What is the best way to retrieve the maximum date associated with a particular foreign key in SQL Server?

I'm currently developing a NodeJs application that involves a SQL Server database for storing data and running queries. However, I've encountered an issue with one specific query which I believe is due to my limited experience in SQL. The &apos ...

Using the `form` method with `get` works perfectly in Node.js, however, the status remains pending when checking in the developer tools

I am currently developing a website that utilizes forms for user voting. The goal is to submit these votes to a Mongo database using Node.js. However, I have encountered an issue where the code successfully updates the database but causes a stuck pending o ...

The request to sign up at 'https://identitytoolkit.googleapis.com/v1/accounts:/signUp? from the origin 'http://localhost:8080' has been denied

My attempt to create a new user in Firebase using Axios in Vue.js is resulting in an error message regarding CORS policy. The specific error states: "Access to XMLHttpRequest at 'https://identitytoolkit.googleapis.com/v1/accounts:/signUp?key=AIzaSyDvZ ...

A simple way to clear an input type=number field with JavaScript when clicked by the user

Currently, I am experimenting with the implementation of a numeric input field using the <input type="number" ...> and the list option to display a predefined set of 'favorite' values while still allowing users to input other valu ...

Collect data from website submissions via email

Is it possible to receive the results via email when someone submits their details on my site using a script? My server does not allow .php or .asp files, only .css. How can I achieve this? ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...

What is the best way to create a clickable entity that is being dynamically generated in a networked A-Frame environment?

I'm attempting to use a networked A-frame to create a new entity upon page load. I want to incorporate various functionalities, such as hover and click events, on these entities. However, my attempts to make them clickable have been unsuccessful. f ...

Ways to invoke jQuery(this) within an anchor tag's onclick event handler

My task involves working with HTML code and I need to apply a class name to the parent li tag using jQuery. Here is the HTML code snippet: <ul> <li><a onclick="setSelectedTestPlan();" href="javascript:void(0);">New Test</ ...

Unable to view videos shared by users in PeerJS and WebRTC video chat application from different tabs

Recently, I embarked on the task of creating a Video chat Website using Peer Js. Initially, everything seemed to be working fine as I was able to see my own video stream. However, a problem arose when attempting to view the video stream from another tab or ...

Issue encountered while utilizing PHP sessions

I'm currently developing a basic login page that utilizes JS, JQuery, and PHP. login.php <!DOCTYPE html> <head> <title>AJAX Login Learning Activity</title> <link rel="stylesheet" type="text/css" href="login.css"> ...