Jump to content
Sign in to follow this  

Accordion Javascript to change button text

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.




Share this post

Link to post
Share on other sites

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)

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...