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

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

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 ‘one’.

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

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

Happy Diviing.


Posted

in

by

Comments

36 responses to “Hooking into the onclick event of buttons in Divi”

  1. Staenk Avatar

    Here is the code for Google Analytics :

    jQuery(function ($) {
    $( document ).ready(function() {
    $(“.button-ga”).on(“click”, function(e){
    var id = e.target.id;
    ga(‘send’, ‘event’, ‘Download’, ‘Document’);
    });
    });
    });

    Best 😉

    1. Gary Armstrong Avatar

      To those who aren’t clear about this… you’d need to give the button a custom class of “button-ga” for this to work.

    2. Lucas Marchetti Avatar
      Lucas Marchetti

      Does this code also work to Google Ads??

  2. Sam Avatar
    Sam

    We got different landing pages with a button that goes to our google place listing. (So we reckon we will have to create a different conversion code for each button on different landing page).

    We want to add the google adword conversion onclick tracking to the Divi Button or Call to Action Button.

    We are total noob. So do we need to put that code into the child theme? Which file of the child theme do we put this in? Or how do we put the google onclick code into the Divi button

  3. John Anderson Avatar
    John Anderson

    Jonathon,

    Nice work. what a great little tip.

    Thanks

  4. Gary Armstrong Avatar

    Jonathan, not a big deal, but I’d probably avoid using “1” as an id on an element. I can totally seeing that messing up some javascript or introducing some hard to find bug where a string is being treat like a number. I know it’s technically compliant in html5+ but still, with great power…

    1. Jonathan Avatar
      Jonathan

      Gary, good point. The id value was meant for illustration purposes only, but I’ve updated the article to use a string instead.

  5. Chris Avatar

    This post was really helpful in solving a project I was working on …..
    Thanks

  6. Binbon Avatar
    Binbon

    I’ve tried to follow this example, not sure why the event doesn’t trigger. On the button element in CSS Class I’ve added get_started and then in integration/header added the following code.

    jQuery(function ($) {
    $( document ).ready(function() {
    $(“.get_started.et_pb_button”).on(“click”, function(e){
    var id = e.target.id;
    ga(‘send’, ‘event’, ‘Button’, ‘Get Started’);
    });
    });
    });

    1. Will Avatar

      Me too!

    2. Marcelo Rocha Avatar
      Marcelo Rocha

      It works for me in this way:

      jQuery(function($) {
      $(“.diviButton”).on(“click”, function(){
      alert(“Button clicked”);
      event.preventDefault();
      });
      });

  7. david jacobs Avatar
    david jacobs

    Brilliant and simple explanation thanks..

    Related to my project, is there anyway to update the content of an Image using jquery

    I can update a blurb title and blurb text using

    var myblurb = document.getElementByID(‘testblurb’);
    myblurb.querySelector(“.et_pb_module_header”).innerHTML = “Hello World”;
    myblurb.querySelector(“.et_pb_module_description”).innerHTML = “its a brand new day”;

    but when I try an image

    var myimage = document.getElementByID(‘testimage’);
    myimage.querySelector(“.et_pb_image_wrap”).src = “http://example.com/image/testimage.jpg”;

    nothing happens…

    only way I found to make this work is to use a custom code module and HTML for the image but would like to use the built in modules.

    1. Jonathan Avatar
      Jonathan

      David, you need to use jQuery’s attr() method to change the src attribute of the image tag. See this CodePen for an example:

      https://codepen.io/kman/pen/dXjpoX

  8. Matt Avatar

    Very helpful, was trying to figure out a way to drive a JS lighbox for viralsweep and this worked!

  9. Amanda Avatar

    Hi Jonathan,

    I was wondering how this would work with trying to track a video module being watch in divi ?

    1. Jonathan Avatar
      Jonathan

      It would depend on what’s being clicked to watch the video, but if there was an overlay that needed to be clicked to watch the video, theoretically yes.

  10. Ghulam Avatar

    I want to add 2 click function by clicking just a single click. Is it possible?
    CEO : https://www.divisiteexamples.com

    1. Jonathan Avatar
      Jonathan

      You would need to trigger two on click events in the JavaScript code.

  11. Daniela Avatar

    Hi Jonathan!

    Could something similar be used with the Contact form module for a LinkedIn or Twitter pixel. I’m having a really hard time with this adding the conversion tracking from a specific add to the contact us section on our website.

  12. Tempat nikah cirebon Avatar

    hot to track call button such “tel:” ?

  13. Sandy Avatar

    How would you add Google Adwords tracking snippet to the submit button of the contact form? Right now, I am redirecting to a thank you page, but I don’t like the implementation. Thanks for your help.

    1. Jonathan Avatar
      Jonathan

      Hi Sandy, it’s a little bit trickier to implement Google AdWords tracking, as you would need to trigger a tracking event on the submit click.

  14. Alex Plappert Avatar

    Hey Jonathan,

    I try to get it to work for adwords. Could you help me?

    Thats what i tried so far, but its not working.

    jQuery(function ($) {
    $( document ).ready(function() {
    $(“.et_pb_button”).on(“click”, function(){
    if (typeof(url) != ‘undefined’) {
    window.location = url;
    }
    };
    gtag(‘event’, ‘conversion’, {
    ‘send_to’: ‘AW-XXXXXXXXXXXXXXXX’,
    ‘event_callback’: callback
    });
    return false;
    });
    });
    });

    1. Jonathan Avatar
      Jonathan

      Hi Alex, I’ve looked at the code and I’m not sure what you are trying to do, are you trying to track an adwords conversion when the button is clicked?

      1. Alex Plappert Avatar

        Yes Jonathan, thats what i tried to do.

        1. Jonathan Avatar
          Jonathan

          Ok, so to start with it looks like you have too many closing characters, you need to remove one extra }); at the end of the jQuery function enclosure.

          Then, I don’t work with AdWords or the Google Global Site tag, but I think what you have to do is something like wrapping the gtag call inside the button onclick:


          jQuery(function ($) {
          $(document).ready(function () {
          $(".et_pb_button").on("click", function () {
          gtag('event', 'conversion', {
          'send_to': 'AW-XXXXXXXXXXXXXXXX',
          'event_callback': callback
          });
          });
          return false;
          });
          });

  15. Julio Cibrian Avatar

    How can I make the button validate the email which is a required field?

    jQuery(function ($) {
    $( document ).ready(function() {
    $(“.diviclick”).on(“click”, function(){
    event.preventDefault();
    $(‘#guiarapidaoptin’).submit();
    });
    });
    });

    1. Jonathan Avatar
      Jonathan

      Hi Julio

      You could probably do something like this – https://gist.github.com/jonathanbossenger/a3276f05c08044991ba246719d4893ff

  16. Mike Avatar

    Thanks so much for that Jonathan! Super helpful. I wanted the button to open the Zendesk chat window. Here’s how that can work:

    In ET’s theme options > integration, I put these two scripts in the header (w/ <> removed)

    !– Start Zendesk Widget script —
    script id=”ze-snippet” src=”https://static.zdassets.com/ekr/snippet.js?key=[your key]” /script
    !– End Zendesk Widget script —

    !– Start fire zendesk via ET Button hack —
    script
    jQuery(function ($) {
    $( document ).ready(function() {
    $(“.et_pb_button_chat”).on(“click”, function(){
    var id = $(this).attr(“id”);
    zE.activate();
    });
    });
    });
    /script
    !– End fire zendesk via ET Button hack —

    Then in ET’s Button Advanced tab, I added the CSS Class:

    et_pb_button_chat

    That way I have a custom class so all my buttons don’t fire the chat window. I left your id in there although it’s not needed. I haven’t played with Zendesk enough but seems like there could be some nice integrations with their API.

    Thanks again for this!

  17. Jeffo Avatar

    Thank you Jonathan! Very helpful. You saved me man! 😀 😀

  18. Gokul K S Avatar

    Hi Jonathan
    I was checking the code to get a function like – click on the button to show phone number then click to call – How can i attain this. Please help

    1. Jonathan Avatar
      Jonathan

      Unfortunately, that’s not something I’ve ever been asked to do before, so I won’t be able to help you there.

      1. Gokul K S Avatar
        Gokul K S

        Ok, Thank You

  19. Chantelle Kern Avatar
    Chantelle Kern

    I don’t want all buttons to do this but only specific buttons and each one will have different on click events. What is the best way to set this up?

  20. Chantelle Leigh Kern Avatar
    Chantelle Leigh Kern

    Hello, I am trying to get it to open something else on click

    $(‘.custom-button-click-italy-uncorked’).on(“click”, function(e){
    event.preventDefault();
    (‘click’, function() {“OpenTrekksoftBookingWidget(‘activity-booking’,’327812′)”;
    });

    So the class of the button is custom-button-click-italy-uncorked

    And instead of opening a link i want it to open the booking widget

    Am I missing something?

    1. Jonathan Avatar

      Hi Chantelle.

      It’s hard for me to be sure without seeing the code you’re working with, but based on what you have shared, I’m assuming you have a button with the class “custom-button-click-italy-uncorked” and you want to trigger a JavaScript function “OpenTrekksoftBookingWidget” which accepts two parameters, the “activity-booking” string, and some ID.

      In that case, the code needs to be amended slightly to work.


      $('.custom-button-click-italy-uncorked').on("click", function(event){
      event.preventDefault();
      OpenTrekksoftBookingWidget('activity-booking','327812');
      });

      I can’t guarantee this will work, but hopefully it helps you see what changes were needed.

Leave a Reply to GhulamCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.