Widgets have served WordPress well over the years, but the future is blocks. We advise only to build widgets only when it cannot be avoided. Instead, build blocks. Most widgets can be ported to server rendered blocks.
In the event that you do need to build a widget, here is some useful information:
A quick note on how to do it, and a note on running the JS, so that it doesn't get ran on the html used to create new widget forms, only those in the sidebars on the right.
How to enqueue a widgets scripts and styles, but only if the widget is on the page
Running code when:
- Make use of the ajaxStop event to process javascript when a widget is added or re-ordered
jQuery( document ).ready( function( $ ) {
function doWidgetStuff() {
var found = $( '#widgets-right .mywidgetelement' );
found.each( function( index, value ) {
// process elements
} );
}
window.counter = 1;
doWidgetStuff();
$( document ).ajaxStop( function() {
doWidgetStuff();
} );
} );
- Some js to show how to do things when the form opens and closes