简体   繁体   中英

jquery slidetoggle where show/hide links are different

Here is the code I'm using (found elsewhere on this site) for a pretty straight-forward slideToggle.

<script>
    $(document).ready(function () {
        $(".slidingDiv").hide();

        $('.show_hide').click(function (e) {
            $(".slidingDiv").slideToggle("fast");
            e.preventDefault();
        });
    });
</script>

HTML:

<div class="section-hold">
    <h4>Section</h4>
    <p><a href="#" class="show_hide">find out more >></a></p>       
</div>

<div class="slidingDiv">            
    <h4>My content.</p>
</div>

What I would like though is for when I click to show the slidingDiv, my "find out more" link disappears and the toggle to hide the slidingDiv content is a different link, contained within that div itself. So the HTML would become something like this:

<div class="section-hold">
    <h4>Section</h4>
    <p><a href="#" class="show">find out more >></a></p>        
</div>

<div class="slidingDiv">            
    <h4>My content.</p>
    <p><a href="#" class="hide">close this section</a></p>
</div>

Any thoughts on how I could accomplish that? Note that there are also a couple sections on this page so ideally the code would be reusable to do this several times on the page.

I'm currently using jQuery 1.11.0 if it makes a difference.

Thanks so much.

This may be what you're looking for. I've coded it so it should be reusable on the same page.

Firstly (to help with the re-usability), wrap your html in another <div> so you have:

<div class="sliderContainer">
    <div class="section-hold">
        <h4>Section</h4>
        <p><a href="#" class="show">find out more >></a></p>        
    </div>

    <div class="slidingDiv">            
        <h4>My content.</p>
        <p><a href="#" class="hide">close this section</a></p>
    </div>
</div>

Then you need a function to show the .slidingDiv while also hiding the .show link which you have just clicked on.

$('.show').click(function (e) {
    var slider = $(this).closest('.sliderContainer').find('.slidingDiv');
    slider.show('slide');
    $(this).hide();
    e.preventDefault();
});

This uses the extra <div> I added in order to find the related .slidingDiv so that you can use this safely elsewhere on the page.

You then need a function to hide the .slidingDiv and then show the .show link again. So like this:

$('.hide').click(function (e) {
    var slider = $(this).closest('.slidingDiv');
    slider.hide('slide');
    $('.show').show();
    e.preventDefault();
});

And that should be it. Here is a jsfiddle of the working code: http://jsfiddle.net/d9UeL/

Hope that helps.

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