Easy JavaScript on Divi Buttons

Divi

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.

Button Module Advanced Settings

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.

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

Share

Related Posts

Time to Update

Maintenance of High Turnover WooCommerce Stores

What to do when plugin updates suddenly cause problems for a high-traffic online store? We were faced with this task when a maintenance interval looked promising at first, but then led to inaccessibility of our client’s high-volume WooCommerce store under load.

GET IN TOUCH

Contact.