Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a jQuery script attached to the widget.php page via an add_action('admin_footer') call.

The jQuery executes fine on widget items that were in place when the page loaded. However, on newly installed widgets (widgets that are added to the sidebar after the page has loaded), the handler does not fire.

Any ideas how to work around this issue?

if ($pagenow == 'widgets.php'){
    add_action('admin_footer', 'my_load_widgets_script');
    function my_load_widgets_script()
    {
    wp_enqueue_script('jquery');
    ?>
    <script>
    jQuery(document).ready(function()
    {
        jQuery('.toggleExtras').on('click', function(e){
            jQuery('.extras').toggle();
            jQuery(this).text(function(el, old){
                return old == "Show Advanced Options" ? "Hide Advanced Options" : "Show Advanced Options";
            });
        });

    });
    </script>
    <?php
    }
}

HTML

<span class="toggleExtras">Show Advanced Options</span>
share|improve this question

closed as off topic by s_ha_dum, Wyck, Eugene Manuilov, kaiser, brasofilo Feb 26 '13 at 8:58

Questions on WordPress Development Stack Exchange are expected to relate to WordPress within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

    
How are you adding widgets "after the page has loaded"? Also, so far this does not sound WordPress specific which would make it off-topic per the faq. –  s_ha_dum Feb 26 '13 at 5:12

1 Answer 1

up vote 3 down vote accepted

Off topic here, but for the sake of solving your problem:

For delegated events, the on part should be

jQuery(document).on('click','.toggleExtras', function(e){

share|improve this answer
1  
^ This is exactly how I handle binding events onto dynamically added items, good answer. –  DigitalSea Feb 26 '13 at 5:35
    
Good solution. Thanks! –  N2Mystic Feb 26 '13 at 7:12

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