How to control Elementor popups with popup events

· wordpress · 2 min read, Steve Monsen

What if you want to add an event listener to a mobile menu button that opens a popup? This tutorial will show you how to do that.

Background

Are you using Elementor popups but struggling to control them independently with JavaScript? Elementor includes popup events, but there is more to it than just adding an event listener to an element and then triggering the popup.

What happens when the visitor clicks or taps…

  • the Escape key?
  • outside the popup?
  • a menu’s close icon?
  • [other scenarios]

You need to make sure that your custom event listeners stay in sync with the Elementor popup state. Otherwise, a number of undesirable results may occur.

For example, the popup might not close when the visitor clicks the close icon. Or it may require multiple clicks to open the popup again, etc.

Here’s the Gist and a quick summary…

Summary of the code

  1. Initialize the popup toggle state variables.
  2. Add an event listener to the mobile menu button.
  3. When the mobile menu button is clicked, toggle the popup.
  4. Add two Elementor event listeners to monitor the opening and closing of the popup.
  5. Set a 50-millisecond delay on the popup toggle to ensure that the popup state is updated before any of the Elementor event listeners fire again.

Originally, the code was written without a delay, but that resulted in the elementor/popup/show event firing multiple times and leaving the toggle variable (window.mytheme_mobile_menu_toggle_open) with incorrect state.

The delay ensures that the popup state is updated before the Elementor event listeners fire again. There are other ways to address this logistical issue, but this is the simplest solution that I’ve found.

Unfortunately, I couldn’t find any official documentation about these events, and a quick search of the Elementor GitHub repository didn’t yield any results.

This code could be expanded to include more than one popup, but I didn’t have a need for it. Others seem to be having issues with that, though, so check the issue tracker referenced below for more information.

References

Back to Blog