< Back to Coding, jQuery

Toggle Buttons

To make a button toggle the visibility of things when clicked use:

$(".toggleBtn").click(
    function(event) {
        event.preventDefault();
        $(this).toggleClass("current");
        var contentClass = $(this).attr("href").substring(1);
        if (contentClass == "") {
            $(this).next().slideToggle();
        } else {
            $("." + contentClass).slideToggle();
        }
    }
);

Then give a button the class of ‘toggleBtn’ and in it’s href attribute put in the class name of the thing you want to toggle starting with a hash eg. #div1.

View the demo

Download the demo

 

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *