0

Can someone give me and example of how I can use window.location.hash for adding to the end of the url when I click on a drop-down content area I created? Here is the code I have so far...

jQuery:

$('.dropdown').click(function(){
    if($(this).hasClass('active')){
        $(this).removeClass('active');
        $(this).next('.dropdown_content').slideUp(300);
    }else{
        $(this).addClass('active');
        $(this).next('.dropdown_content').slideDown(300);
    }
});

HTML:

<div class="dropdown_wrapper">
   <h3 class="dropdown">Title of Dropdown<span></span></h3>
   <div class="hidden dropdown_content">
      <p>Content</p>
   </div>
</div>

What I want is for when a dropdown-content window is open to have something added to the url so that when you copy a link and send it to someone, it will already have that particular drop-down open.

This is my first time ever using this so the more detail the better if you can! And if you need more details from me I'll provide them!

Thanks!

jtv_24
  • 53
  • 7

2 Answers2

0

Add an ID

<div id="dropdown" class="dropdown_wrapper">
   <h3 class="dropdown">Title of Dropdown<span></span></h3>
   <div class="hidden dropdown_content">
      <p>Content</p>
   </div>
</div>

We can link to it:

<a href="#dropdowm" id="link">Goto Drop down</a>

We can URL to it:

www.url.com/#dropdown

So in any anchor tag or in a url, you can use "#idOfElement".

Sources:

page jump from div to an anchor

http://www.w3schools.com/jsref/prop_loc_hash.asp

URL hash format, what's allowed and what's not?

Community
  • 1
  • 1
Jon Crawford
  • 193
  • 11
0

You might want to give your dropdowns unique IDs. This will let you find them more easily. They will also cause the browser to scroll that dropdown into view when pasted in the URL, but you still need to open the dropdown yourself.

$('.dropdown').click(function(){
    if($(this).hasClass('active')){
        $(this).removeClass('active');
        $(this).next('.dropdown_content').slideUp(300);
        history.replaceState(null, null, "#");
    }else{
        $(this).addClass('active');
        $(this).next('.dropdown_content').slideDown(300);
        history.replaceState(null, null, "#" + escape($(this).text()))
        // If the dropdown had an ID:
        //    history.replaceState(null, null, "#" + $(this).prop('id'))
    }
});

$(document).on("load", function(){
   var preselect = location.hash.replace(/#/, ''),
       $dd = [];

   if (preselect.length > 0) {
      $dd = $(".dropdown").filter( dd => $(dd).text() == unescape(preselect) );
      // If the dropdown had an ID:
      //    $dd = $("#" + preselect)
      $dd.addClass('active');
      $dd.next('.dropdown_content').slideDown(300);
   }
});
Malk
  • 11,855
  • 4
  • 33
  • 32