Jump to content

Accordion Javascript to change button text


absolutebeginner
 Share

Recommended Posts

I have some W3.CSS accordions on a webpage based on this tutorial.

They work fine, but I'd like to change the button text too (not just show/hide the div)

When shown, I'd like the button to show "Click for details".

When hidden, I'd like the button to show "Hide details".

Thanks in advance for any assistance/advice you can give me.

 

 

 

Link to comment
Share on other sites

  • absolutebeginner changed the title to Accordion Javascript to change button text

I worked out how to it using some jQuery. Don't know if it's good practice to mix (regular?) Javascript and jQuery, but here's how I did it. (You guys probably do this better in your sleep)

In the button tags, I added IDs named the same as the div IDs, but with "_btn" on the end.

The Javascript/jQuery code is this (using a link to google.apis at the top for the jQuery, jQuery code is shown in blue)

            function Accordion(id) {
                var x = document.getElementById(id);
                if (x.className.indexOf("w3-show") == -1) {
                    x.className += " w3-show";
                    $("#"+id+"_btn").text("Hide details");
                } else { 
                    x.className = x.className.replace(" w3-show", "");
                    $("#"+id+"_btn").text("Click for details");
                }
            }

Tested on Chrome, FF, IE, Edge and Safari (PC version and iPhone)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...