Hooking into the onclick event of buttons in Divi

In the Divi Theme Users & Elegant Marketplace group, Brett Bumeter asked, “anyone ever find a quick way to add an onclick event to a Divi Button?”

More specifically, Brett needs to replicate the onclick event on a regular html button, but using a Divi button.

<button onclick="myFunction()">Click me</button>

First thing we need to do is look at a Divi button’s html.

<a class="et_pb_button  et_pb_button_0 et_pb_module et_pb_bg_layout_light" href="">Button</a>

So a Divi button is really just a styled anchor tag. That’s fine, we can use the onclick event on an anchor tag. However we can’t edit a Divi button’s html, so we can’t add a function to the onclick event. What we can do is use some jQuery to bind a function to the anchors onclick event.

Here’s what that would look like:

$(".et_pb_button").on("click", function(){
    event.preventDefault();
    alert("Button clicked"); 
 });

So what this does is bind to the onclick event of any element that has a class of “et_pb_button”, prevent the default action of that element (in this case opening a url) and then performs whatever functionality you need (in this case showing the alert).

Pretty simple really. You can use this Javascript snippet in a child theme as is, or you can insert it into the Divi Theme Options -> Integrations -> Add code to the < head > of your blog’ area. If you are going to go the second route, you will need to wrap the snippet above in a document ready enclosure and some script tags, like so

<script>
jQuery(function ($) {
    $( document ).ready(function() {
        $(".et_pb_button").on("click", function(){
            event.preventDefault();
            alert("Button clicked"); 
        });
    }); 
});
</script>

You could also take this a step further, and use it to pass some data to the onclick event, by using a custom button id or class. Let’s say we give the button a custom id of ‘1’.

$(".et_pb_button").on("click", function(){
    var id = $(this).attr("id");
    alert("Button " + id + " clicked");
});

In this instance the custom id of 1 would be passed to the ‘id’ variable, which could then be used to call some other function, which needs that value.

Happy Diviing.