Creating Custom Actions on Click

Creating Custom Actions on Click

Give this text a little click and see what happens to the blog title. Click it again to change it back.

This is how jQuery toggles work. They can be a pretty useful way of allowing your users to initiate an action. You could hide or show content on click, change the size of an iframe to emulate a mobile device.. The list is endless.

If you’re interested in using this technique, here’s how to do it with Divi.

We’re using the jQuery “addClass” method to append Divi’s #page-container ID with the class “action” whenever an element with the class “custom-action” is clicked. This way we can make changes to any element nested inside of the page container… so everything.

The jQuery

Add this code to the head of your Divi site. You can do this under the integrations tab in Divi theme options.

add code

<script>
jQuery(document).ready(function(){
 jQuery(".custom-action").click(function(){
 jQuery("#page-container").toggleClass("action");
 });
});
</script>

To use this to create toggle actions, all you have to do is add the class ‘custom-action’ to an element you want the user to click on. You could add the class to a menu item, span element, button or anything else. In our example at the beginning of this blog post we used this html…

Give this <span class="custom-action" style="color: red; font-weight: 900; ">text a little click</span> and see what happens to the blog title.

See how it works? Now to make changes happen ONLY when you click on any of those elements, you just add “#page-container.action” in front of your CSS.

For example, turning titles red when a toggle element is clicked would look like this…

#page-container.action h1 {
    color: red;
}

I hope this helps you level up your site interaction. If you use this technique, please include a link in the comments so we can check it out 🙂

Stephen James

SJ is a web developer living in the coastal town of Southsea, England. He is a Divi and WordPress advocate and the founder of Divi Space.