Search code examples
jquerytoggleslidetoggletoggleclass

Link to go to and open toggle div


I want a working .jquery toggle to be activated from a nav menu link. I also want the page to scroll to the opened div at the same time. This is working:

$(document).ready(function(){   
$(".toggle_container3").hide(); 
$(".trigger3").click(function(){
    $(this).toggleClass("").next().slideToggle("slow");
    return false; //Prevent the browser jump to the link anchor
})

});

with this HTML:

<h4 class="trigger3 dark_grey">
<a href="#">Research Themes</a></h4>
<div class="toggle_container3" id="research"> content </div>

And this menu link goes to the research themes section on the page:

<li><a href="#research">Research Themes</a></li>

But I want the Research Themes link to go to and toggle open the research div. I tried adding the class .trigger3 to the , no luck. The #research stopped working. After researching on this forum, I tried:

$('#research').click(function (e) {
e.preventDefault();
$(this).toggleClass("").next().slideToggle("slow");
    return false;
window.location.hash = ($(e.currentTarget).attr("href"));
});

But no luck. Is there something I can add to the original .trigger3 click function, that will make it work with the as well? Plus go to that spot on the page?


Solution

  • All you need is the code below, above each div you wish to show/hide add a button with class .trigger and it will toggle the div below it. This would create an accordion. If the buttons cannot be right above each div to toggle you can add a data-toggle='div name' to each button and use that tag to select the div to toggle.

    $(".trigger").click(function(){
        $(this).next().slideToggle("slow"); // toggle div below button
        $('.' + $(this).data('toggle')).slideToggle('slow'); // toggle div specified in data-toggle attribute on trigger element
        return false; //Prevent the browser jump to the link anchor
    })