Instructions on how to open the <details> element from a link on a different page

Imagine a scenario where you have a Home Page with a link to a second page that features some content enclosed by a <details> element. However, the <details> element on the second page is initially closed, and you wish for the link on the home page to redirect to this element and automatically open it.

You want to accomplish this using basic HTML, CSS, and JavaScript. Below is what has been attempted so far:
home.html

<html>
  <head>
    <script type="text/javascript">
      window.onload = function() {
        var a = document.getElementById("mylink");
        a.onclick = function() {
          var b = document.getElementById("mydetails");
          b.open = true;
          b.style.color = "red"; // testing another property
          return false;
        }
      }
    </script>
  </head>
  <body>
    <h1>Home Page</h1>
    <h2><a id="mylink" href="second_page.html#mydetails">Go to 2nd page</a></h2>
  </body>
</html>

second_page.html

<html>
  <body>
    <h1>2nd page</h1>
    <details id="mydetails" open="false">
      <summary>Hello,</summary>
    </details>
  </body>
</html>

However, despite the code running without errors, clicking on the link in the home page does not open the <details> element on the second page as intended. What steps should be taken to achieve this?

Extra points if one can figure out how to pass the IDs of both the link and target element as parameters to the JS function.

Similar queries:

  1. How to use a link to call JavaScript?, which was used as a reference source
  2. Automatically open <details> element on ID call, appears to address the desired outcome, but implementation details still remain unclear

Answer №1

If you want to modify a page that is not currently active using Javascript, you will need to find another approach. Javascript functions only on the active page and can manipulate the Document Object Model (DOM) of that specific page. In order to make changes on a different page, you must transfer the necessary data to the target page.

One method involves utilizing HTML5 Session Storage to transmit data:

    home.html
    <script type="text/javascript">
        window.onload = function() {
            var link = document.getElementById("mylink");
            link.onclick = function() {
                localStorage.setItem("open", "true");
            }
        }
    </script>

    second_page.html
    <script>
         var value = localStorage.getItem("open");
         if (value == "true") {
             var details = document.getElementById("mydetails");
             details.open = true;
             details.style.color = "red";
             localStorage.removeItem("open");
          }
    </script>

Answer №2

function(link,target){
  //create a onclick event for the specified id (link)
  $('#'+link).click(function() {
    //retrieve the details panel from the next page
    var details = $(target+'#mydetails');
    //change its state to true
    details.open = true;
    //navigate to that page
    window.location.replace(details);
});
}

This implementation should be effective. Utilizing jQuery for this task, assuming it is suitable.

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

Transform HTML content into a PDF document

I am dealing with a string that contains HTML data and my goal is to convert it into a PDF using ASP.Net. After searching support pages and using Google extensively, I have not been able to find a straightforward snippet of code for this common task with a ...

How to automatically insert a page break after a certain string in an array using JavaScript

I've created a code that is intended to implement page breaks after a specific number of new lines or words. I have defined an array that indicates where these breaks should occur within my element. In the example provided in my jsFiddle, you can see ...

Verifying that phone numbers and email addresses are accurate prior to submitting the form

As a PHP newcomer, I apologize if my question appears somewhat naive. Currently, I am working on a contact form that is functioning well, but I need to implement validation for two specific fields: the phone number and the email address. For the phone numb ...

Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console. One of the errors I see is: Property or method "show" is not defined on the instance but referenced during render. Make sure that this proper ...

What is the advantage of using functions rather than values as parameters in jQuery?

Many jQuery methods accept functions instead of values as parameters, including .append(). Instead of the traditional syntax: something.append( '<div></div>' ); you could write it like this: something.append( () => '<div ...

Enhancing visuals with THREE.js and the power of transparency through EffectComposer

I am attempting to blend texture passes in a way that preserves the alpha channel. I have experimented with several methods to achieve this. The renderer has the alpha property set to true. Renderer with various setClearColor settings. The material on th ...

Is there a way to lock the eye icon in place within the password field using Vue.js?

I added an eye icon to the right side of my password input fields. However, occasionally error messages may pop up on the page to signify issues with the input fields. When these error messages appear below the relevant input field, the position of the eye ...

Associate information from a modal to a knockout model

I am attempting to utilize a Twitter Bootstrap modal that opens a window containing an editable text area. Upon saving, the relevant data should be saved. The current code I have is as follows: HTML: <table class="display table table-striped"> ...

Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format: { "Dates": ["January", "January", "March", "March", "March", "November", "November"], "Values": [45.6, 0.5, 59.3, 46.56, ...

Generate a standard Wordpress menu containing all pages without the need to manually add each page in the menu editor

I'm struggling to figure out how to display all pages in WordPress without manually adding them to a menu. Instead of creating a new menu and selecting specific pages, I want to automatically show all existing pages in the menu. For example, if I ha ...

Guide to adding items to an array in json-server using a JavaScript-created database

I built a JSON-server app that dynamically generates the database using JavaScript when it starts running. The data I create is organized within a 'users' object, as illustrated below: { "users": [ { "id": "user_id_0", ...

"Learn the steps to include a success message in an HTTP POST response once a button has been

Currently, I am utilizing nodemailer along with express... I aim to incorporate a text message and loading indicator on the front-end to indicate whether the form submission is in progress or not. .ts deliverEmail(value) { console.log('em ...

Enhancing user experience with a jQuery autocomplete feature for dual language support

There are two input fields, one for English and the other for Spanish. {!! Form::text('titulo_en', null, array('placeholder' => 'Title','class' => 'form-control buscador')) !!} {!! Form::text('t ...

Sign up for our Joomla website by completing the registration form and agreeing to our terms and conditions

I am currently working with Joomla 1.5 and I need to incorporate a checkbox for users to agree to the terms and conditions. I attempted to use the code below, but it is not functioning as expected. Even when the checkbox is ticked, it still triggers an a ...

Reset the Bootstrap carousel following an Ajax request

Assembling the carousel from the bootstrap carousel after the Ajax call has been completed. Elements and classes are being appended post page load as shown below. async function ajaxCall() { let data = await fetch('ApiLink'); let jsonData ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

Window displaying multiple product options

Having an issue creating modal windows for multiple products, where only the last product is being displayed in each window. Attempted to assign id identifiers, but faced a problem where only the modal window of the first product functions correctly. wi ...

Show the Angular table header only once, and automatically hide it if there is no data available

I am currently working with Angular 5. My goal is to show the table header only once when the typeId is equal to 3. Additionally, if none of the data items have a typeId equal to 3, I want to hide the entire table along with the header. Below you will fi ...

Customizing the color of pagination in Bootstrap

Here is the pagination control I am working on: https://i.sstatic.net/iVufm.png I have been trying to change the color of the pagination labels to purple, but my CSS overrides are not working. Here is what I currently have in my stylesheet: /* Paginatio ...

Load a Javascript file from the local server

My website is encountering a problem when trying to load a script from a localhost server. The error message displayed is PROTOCOL ERROR: https://localhost:4200/script/test.js net::ERR_SSL_PROTOCOL_ERROR Here is the code snippet causing the issue: <!DO ...