How to Execute JavaScript on Divi Buttons
I had to set a cookie via button-onclick the other day. For GDPR compliance we want to offer a Google Analytics Opt Out to our visitors. I could have queued a JavaScript file in my functions.php for that. I decided to take a more elegant road.
I would not recommend anything to you I’ve not been using enthusiastically myself. Bold links are affiliate links. I recommend what you’ll find there and If you make a purchase, I will get a commission without additional costs to you.
Imagine you’d need the Button Module of our beloved Divi theme to execute JavaScript on click like this:
This is very convenient to do if you know the Divi Code Module. We need a button with an id first so we enter js-caller at our Button Module Settings Advanced tap into the CSS ID field.
We then add a Code Module to the post. This will hold the JavaScript we will attach to the #js-caller click event to execute the payload. Exchange the alert(‘Payload executed!’); with the JavaScript you need executed.
We want to prevent the default behaviour (event.preventDefault). Otherwise the click would do what clicks on buttons usually do: go to the Button URL specified in that Button Module.