Easy JavaScript on Divi Buttons


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 on facebook
Share on twitter
Share on linkedin

Related Posts

WooCommerce SQL

Howto Manipulate WooCommerce Metadata via SQL

With Germanized on board, WooCommerce has several ways to save article numbers. Has the intern spent two days entering the EAN in the wrong field for the 3000 articles in the WooCommerce online shop? Then an SQL superhero has to save the day who can copy content from one field to another in no time.

eCommerce Sales

5 eCommerce Lockdown Tips

eCommerce is booming because since Corona everyone understands the importance of online stores and digitization. We have been supporting online stores since the beginning of the millennium, when you still had to program them yourself, and we would like to tell you here how your eCommerce tools can make good sales and keep you afloat in a crisis.