Nikhilesh Sharma Nikhilesh Sharma - 10 months ago 40
CSS Question

WordPress: Use button to add class to a div element

I am working on a WordPress website and I want to add a button that once clicked will expand all fields of the accordion.
But the problem is that I can only assign a CSS class to the Button (theme developer only allows me to do that).
once the user clicks on the button, can I use CSS to execute a jQuery (or any other language that will do the trick) file that will contain the code to expand all sections of the accordion?

Answer Source

CSS is quite a powerful styling language, but that's all it is actually designed for: styling elements. It isn't really going to be capable of executing any type of Javascript or related client-side code on its own.

You have a few options depending on how much you are able to actually change about the site.

If you can add / change Javascript

If you can actually add a small script to the site, then this should become fairly trivial. You would simply need to add a CSS class to your specific button and then wire up an event handler to capture the click event in jQuery to perform your action :

<button class='your-special-button'>Click Me!</button>
             // Your button was clicked, do something...

Depending on the functionality, you could potentially handle this inline via an onclick event as well :

<button onclick='DoSomethingHere();'>Click Me!</button>

If you cannot add / change Javascript

Depending on your exact functionality, it may be possible to handle this purely through CSS if the markup is in a state that supports it to create a basic accordion as seen here.

There are a variety of tutorials out there and different ways to implement it, consider a quick search for "pure CSS accordion" in your favorite search engine.