简体   繁体   中英

toggle element on page load with a hash link not working

I am new to javascript and using jQuery toggle effect on a button to open and close the following div. Here is my html:

<article id="book-section">
<h3>The new collection</h3>
<a class="btn" href="#book-list-one">Book list</a>
<div>
<ul>
   <li>Book one</li>
   <li>Book two</li>
   <li>Book three</li>
   <li>Book four</li>
</ul>
</div>
</article>

Here is my javascript

$(document).ready(function() {
$(".btn").click(toggle);
function toggle() {
    {
        $(this).toggleClass("open").next().slideToggle();
        return false;
    };

    $("a[href='" + window.location.hash + "']").parent(".btn").click();
}
});

It's supposed to be opening the div containing the book list when the user types in index.html#book-list-one but it doesn't. The toggle effect works just fine. I can't figure out what the issue is. Any help would be appreciated!!! Thanks in advance!

Update: Here is the JSfiddle

You have closing bracket incorrectly setup on function :

$(document).ready(function() {

  $(".btn").click(toggle);

  function toggle() { 
    $(this).toggleClass("open").next().slideToggle();
    return false;
  }

  // and seems like the a tag in html snippet posted
  // doesn't have parent with the class name `.btn`,
  // $("a[href='" + window.location.hash + "']").parent(".btn").click();
  // instead try access it directly
  $("a[href='" + window.location.hash + "']").click();

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM