1

I have some jquery that I need to apply to a view that's being displayed as a block. The only template we're using for this particular view is views-view-grouping--my-view.tpl.php. I've tried adding the jquery to the beginning of this file, but as expected (because it runs recursively for each group) it's being added to the rendered source before every rendered group, instead of just once.

Where is the best place for me to add jquery code so that it's only added to the rendered source once? It's just two lines of code aside from the document.ready declaration, so I'd rather not have to put it in a separate file and call it conditionally from various page templates.

1 Answer 1

3

One quick way could be to add it inline in a preprocess function.

    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
      }
    }

If you prefer you could also add it as a file that you store in your theme. This would include a file called myfile.js under the folder for your theme /js

    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         global $theme_path;
         drupal_add_js($theme_path . '/js/myfile.js');
      }
    }
2
  • Well, we only want it to happen on the block display, not anytime the view is displayed in a page. Is there any way to check for that?
    – EmmyS
    Aug 27, 2012 at 15:05
  • Updated with specific display id identifier also. The first block display added to a view will be block_1. You could also do a dpm($view->current_display); to find out your display id or hover the name of the display in Views UI. Aug 27, 2012 at 15:08

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.