In this document, we’ll cover:
- Setting an ID or class in an Elementor widget.
- Writing JavaScript to handle the onClick event.
Setting an ID or Class for an Elementor Widget
First, let’s add an ID or class to the Elementor widget so that we can target it with JavaScript.
Within this tutorial, we will work with Vanilla JS with no dependency.
Steps to Add ID or Class in Elementor:
- Open Elementor Editor: Edit the page or post using Elementor.
- Select the Widget: Click on the widget you want to add an ID or class to (e.g., a Button or Image widget).
- Go to the Advanced Tab:
– In the widget’s settings, navigate to the Advanced tab. - Add ID or Class:
– CSS ID: Enter a unique ID in the CSS ID field, such as custom-button.
– CSS Classes: Alternatively, add a class name in the CSS Classes field, such as my-button-class. - Example:
– CSS ID: custom-button
– CSS Classes: my-button-class - Update the Page: Save your changes and update the page.
Ensuring the Custom CSS/JS Feature is Enabled
To add custom JavaScript, ensure that the Custom CSS/JavaScript feature is enabled in Elementor.
Adding JavaScript Code in the Page Settings
After setting up your ID or class, you can now add JavaScript to handle the onClick event.
Adding JavaScript Code in the Page Settings
- Go to Page Settings: In the Elementor editor, open the Page Settings by clicking on the gear icon in the bottom left corner.
- Navigate to the Advanced Tab: In the Advanced tab of Page Settings, locate the Custom CSS/JavaScript section.
- Add the JavaScript Code: Copy and paste the JavaScript code below into the Custom JavaScript section:
4. Update or Publish the Page: Save and update/publish the page to apply your changes.
<script>
document.addEventListener(‘DOMContentLoaded’, function() {
// Select both ID and class elements using querySelectorAll
const buttons = document.querySelectorAll(‘#custom-button’);
// Loop through each selected element and add the onclick event
buttons.forEach(button => {
button.onclick = function() {
alert(‘Button clicked!’);
// you can call functions also.
};
});
});
</script>
Testing
Once the page is updated, preview it in the frontend. Click the button or element with the assigned ID/class to verify if the onClick event is working as expected.
And that’s it! You should now have a fully functioning onClick event for your Elementor widget.