Title: Can widgets.php invoke a js function?
Last modified: August 22, 2016

---

# Can widgets.php invoke a js function?

 *  [Reggiebus](https://wordpress.org/support/users/spasarok/)
 * (@spasarok)
 * [11 years, 5 months ago](https://wordpress.org/support/topic/can-widgetsphp-invoke-a-js-function/)
 * WordPress widgets are activated in a theme’s `widgets.php` file. The `Foo_Widget`
   example in the [WordPress Widgets API](http://codex.wordpress.org/Widgets_API)
   shows that widgets should call a `widget` function, an `update` function, and
   a `form` function, with the `widget` function containing the code that will be
   activated when widgets are displayed.
 * **Is there a way to have the widget function invoke a JavaScript function stored
   in a separate js file?**
 * Here’s what I have tried with the Foo_Widget example linked above. The “fooey!”
   alert works fine, but instead of displaying a widget all that appears in the 
   widget space is the word “undefined.” Any idea what I’m doing wrong? Thanks!
 * **Header Text**
 *     ```
       //header text
       <?php wp_enqueue_script( 'foo', get_template_directory_uri()."/js/foo.js" ); ?>
       ```
   
 * **foo.js**
 *     ```
       function foo( $args, $instance ) {
   
           alert("fooey!");
   
           document.write($args['before_widget']);
   
           if (!empty($instance['title'])) {
               document.write($args['before_title'] + $instance['title'] + $args['after_title']);
           }
   
           document.write("Hello world!");
           document.write($args['after_widget']);
       }
       ```
   
 * **Updated Widget Function**
 *     ```
       public function widget( $args, $instance ) {
           echo '<script type="text/javascript">foo(' . $args . ',' . $instance . ')' . ';</script>';
       }
       ```
   

The topic ‘Can widgets.php invoke a js function?’ is closed to new replies.

## Tags

 * [javascript](https://wordpress.org/support/topic-tag/javascript/)
 * [js](https://wordpress.org/support/topic-tag/js/)
 * [php](https://wordpress.org/support/topic-tag/php/)
 * [widgets](https://wordpress.org/support/topic-tag/widgets/)
 * [widgets.php](https://wordpress.org/support/topic-tag/widgets-php/)

 * 0 replies
 * 1 participant
 * Last reply from: [Reggiebus](https://wordpress.org/support/users/spasarok/)
 * Last activity: [11 years, 5 months ago](https://wordpress.org/support/topic/can-widgetsphp-invoke-a-js-function/)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
