Home / Documentation / Confetti / How to trigger the confetti effect on click

How to trigger the confetti effect on click

By default, the confetti effect shows when the page is loaded. However, you can have the confetti triggered when any element on your page is clicked.

Loading the necessary JavaScript

In order for the Confetti to run, it needs to have the required JavaScript files included. There are two ways to load those files.

Using the shortcode

You will need to start by putting the shortcode anywhere on the page using the ‘onload’ attribute set to false. Confetti knows to load the JavaScript files when this shortcode is included on a page. By setting the “onload” attribute to false, Confetti will not automatically run on the page load as is default and then allows it to be manually triggered by your custom code.

[confetti onload="false"]

Using code

Otherwise, you can enqueue the necessary JavaScript with code:

add_action( 'wp', 'wps_enqueue_confetti_scripts' );
function wps_enqueue_confetti_scripts() {
 	WPS_Confetti()->enqueue_scripts();
}

Two ways to manually trigger confetti

Use pre-existing class

If you add the class “wps-confetti” to any element, it will trigger when it is clicked. Example:

<div class="wps-confetti">Click me to trigger confetti</div>

Custom JavaScript

You can use any custom JavaScript you want and use the wps_launch_confetti_cannon() function. Example using jQuery:

$( '#my-element' ).on( 'click', function() {
    wps_launch_confetti_cannon();
});

This could be customized to trigger the confetti cannon on any interaction you want such as click, hover, etc.

If you do not want to use jQuery, you can also use vanilla JavaScript:

<div onclick="document.dispatchEvent( new CustomEvent( 'confetti' ) );">Click me div</div>