Adding Debounce To A Window Resize Event Using Underscore In WordPress

In this blog, we will learn about how to add a debounce to the window’s resize event using Underscore in WordPress.

WordPress already provides you access to the underscore library.

All you have to do is add that as a dependency while enqueing the JavaScript file where you need it like so:

namespace YourNameSpace;
function asset_loader() {
   wp_register_script( 'app', 'url-to-your-js-file-app.js', [ 'jquery', 'underscore' ], false, true );
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\asset_loader' );

Then we can use it like so :

windowEl.on( 'resize', _.debounce( ( event ) => {
   const windowWidth = event.target.outerWidth;
   yourFunctionToBeExecuted( windowWidth );
}, 500 ) );

That’s all folks


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *