1

I've written a small widget that uses JS for setting up some tabs in the settings panel. Is there a way to re-trigger the tab JS when the widget is done saving?

Looking at the WP JS source it doesn't look like it, as it simply blows away the existing HTML & re-renders the entire form. I could potentially overwrite wpWidgets.save & do something nutty there but that seems really drastic.

Solution

After some hacking based upon One Trick Pony's idea, here's what I ended up with.

<script>
jQuery(document).ready(function($){
    if(parseInt("<?php echo $this->number; ?>", 10)) {
        $("[id$='<?php echo $this->id; ?>'] .tabs").tabs();
    }
});
</script>

Basically I just send down some JS w/ some Widgets values hardcoded in & do some checks & fun CSS3 selectors to find the right DOM nodes.

1
  • why don't you make the number check with PHP, and include the script only if it's set? ps: related question Commented Sep 1, 2011 at 22:55

2 Answers 2

2

Put your javascript code inside the widget form, and it will be triggered whenever the widget is refreshed.

If you're tabs are hooked on a click event, a better way would be to use $.delegate on the widget instance wrapper. That way you don't need to include the js inside every widget instance...

4
  • I don't need delegation because I'm not listening for any clicks, just need the tabs to be there when the widget is expanded/saved.
    – Tivac
    Commented Sep 1, 2011 at 22:14
  • Your method is currently working, but does incur the cost of one extraneous tab setup call (for the copy of the form that WP outputs w/ fake IDs in it). I could do some work to avoid that but it isn't worth it right now. This solution isn't perfect & kinda kludgey but I'll take it, thanks!
    – Tivac
    Commented Sep 1, 2011 at 22:19
  • Another solution is to use the livequery plugin to trigger your function whenever a new widget form element is added in the DOM. But I still think you should delegate(). Typical tabs can be styled with CSS, you only need JS for user-interaction - ie. the click handler... Commented Sep 1, 2011 at 22:33
  • I'm really not interested in re-implementing tabs, jQuery UI tabs are fine for my needs. I'd rather have some extra junk floating around than doing tabs myself using delegation.
    – Tivac
    Commented Sep 1, 2011 at 22:37
1

This is an old thread, but in case someone else winds up here:

There are js actions triggered when widgets are added or saved. Reasonably called widget-added and widget-updated.

Trac ticket: https://core.trac.wordpress.org/ticket/19675

You can use them like so:

    // On the Widget Actions, run.
$( document ).on( { 'widget-added widget-updated': function ( e, widget ) { //do stuff. }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.