How to Execute JavaScript on Divi Buttons

I had to set a cookie via button-click the other day in accordance to achieve the Google Analytics Opt Out required in Germany. I could have queued a JavaScript file  in my functions.php, but 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.

Button Module Advanced Settings

We then add a Code Module to the post to hold the JavaScript that will attach to the #js-caller click event and execute the payload. Just exchange the alert(‘Payload executed!’); with the JavaScript you need executed.

We want to prevent the default behaviour (event.preventDefault) because the click would otherwise do what clicks on buttons usually do: go to the Button URL specified in that Button Module.

That was easy! Why did we even waste time talking about this, eh? And if you ever feel like programmatically performing clicks on mouseover-events you could read about it here here.