I’m working on a widget that do some magic with jQuery (slide,fades elements). The problem is that the jQuery script attached to widget is not called when I delete and then replace the widget in the sidebar .

Even If I have in the form function something like this :

public function form( $instance ) {

    wp_register_script('script', get_template_directory_uri() . '/script.js', array('jquery'), null, true);
    wp_enqueue_script('script');
}

The script is present in the page (If I view source it is there) but the document.ready function is not triggered so all the onclick action are disabled.

Refreshing the page resolve the problem but it’s there a way to resolve this somehow ?

I need something like document.on("widget-attached-to-sidebar", function(){});

EDIT:

Steps to reproduce this problem :

  • refresh the page
  • my jQuery script works
  • delete the widget
  • add it again
  • my jQuery script is not working anymore (need to refresh the page again)

The script.js is still there in the page (view source) through all those steps .

4 Answers
4

You can hook into the DOMNodeInserted event to find out when your widget has been added to the side bar.

jQuery(document).on('DOMNodeInserted', '.widget-top', function () {
      alert(jQuery('.widget-title', this).text());
});

The code above will alert to any newly added widget. Once you’re hooked into the newly created widget, you can traverse it to find your specific class and take action, if it is your widget that was added.

Tested only with Firefox.

You can find out more information with this jQuery question https://stackoverflow.com/questions/15268661/jquery-on-create-event-for-dynamically-created-elements

Leave a Reply

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