0

Let's say I have an Home Page that contains a link to a second page which has some kind of content, say a <details> element. Now, the <details> element in the second page is closed “by default” but I would like the link in the home page to redirect to the <details> element and open it.

I would like to to this with basic html/css and javascript. Here is what I have 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"; // just to try 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>

Unfortunately, the code runs but when I click on the link in the home, the <details> in the second page doesn't get opened. How could I go about this?

Bonus points if I could pass as parameters to the JS function the ids of both the link and target element.

Related questions:

  1. How to use a link to call JavaScript?, from where I got most of my code
  2. Automatically open <details> element on ID call, this seems to be what I want to achieve, but I don't know how to get it to work
Community
  • 1
  • 1
Pier Paolo
  • 878
  • 1
  • 14
  • 23

2 Answers2

1
function(link,target){
  //set the click function of the given id (link)
  $('#'+link).click(function() {
    //get the details panel from the next page
    var details = $(target+'#mydetails');
    //set its state to true
    details.open = true;
    //redirect to that page
    window.location.replace(details);
});
}

Something along these lines should work. This is using jquery, hopefully that's ok.

Shtut
  • 1,397
  • 2
  • 14
  • 28
1

You cannot modify another page that is not active using Javascript. Javascript only runs on the active page and can modify the DOM of the active page. You will have to send the value to the next page.

HTML5 Session Storage to send data:

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

    second_page.html
    <script>
         var val = localStorage.getItem("open");
         if (val == "true") {
             var b = document.getElementById("mydetails");
             b.open = true;
             b.style.color = "red";
             localStorage.removeItem("open");
          }
    </script>
Ayush
  • 741
  • 9
  • 19