简体   繁体   中英

Toggle element in page when clicking a hash link

I have some jQuery that converts a definition list into an expandable/collapsible list of FAQs.

// Toggle expand/collapse
$('.faq a').click(function () {
    $(this).toggleClass('active').next().slideToggle('fast');
});

var hash = document.URL.substr(document.URL.indexOf('#'));
$(hash).addClass('active').next().show();
$(hash).parent().parent().prev('a').addClass('active').next().show();

I have several links to FAQs throughout the site and clicking on them sends you to the FAQ page and expands the relevant question, the problem is that some of the FAQ answers have links to other questions and while the hash link jumps to the relevant question it doesn't expand the answer.

Is this because the jQuery is in an $(document).ready(function() so the code only activates after the page is reloaded? Do I need to trigger a reload?

CHeers

See my jsFiddle for full code.

Clicking a hash link doesn't reload the page, it just navigates within the page.

You can bind a click event to the hash links that does the work for you. for example:

$('ul li a').click(function() {
   $($(this).attr('href')).toggleClass('active').next().slideToggle('fast');
});

Try

//for the demo in fiddle you need to use the selector ul li a
$('.faq dd a[href^="#"]').click(function(){
    $($(this).attr('href')).trigger('click')
})

Demo: Fiddle

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