Use hook_views_pre_render() to load a custom script just for a specific view

Public

This snippet is really useful when you want include a custom script to apply a display effect in a view. In this example I'm loading the awesome jQuery plugin bxslider to implement a responsive carousel on my view.

First you have to create your view and display it as an html list. The create and enable a feature with this view and optionnally the content type used in this view.

In a second time you'll need to create a library for the bxslider plugin, really easy... : enable the libraries module and put your bxlsider plugin in the sites/all/libraries folder... that's it !!!

Then insert this hook in the .module of your feature.

</> CopyGet raw version
php
  1. /**
  2. * Implements hook_views_pre_render().
  3. */
  4. function my_module_views_pre_render(&$view) {
  5. if ($view->name == 'view_name') {
  6. // Load the bxslider library
  7. drupal_add_js(libraries_get_path('bxslider') . '/jquery.bxSlider.min.js');
  8. // Load your custom script to call the jQ plugin
  9. drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');
  10. }
  11. }

Then in your my_modules.js, call the plugin...

</> CopyGet raw version
javascript
  1. (function ($) {
  2. Drupal.behaviors.my_module = {
  3. attach: function(context, settings) {
  4. $('.view-class .item-list ul', context).bxSlider({
  5. minSlides: 2,
  6. maxSlides: 2,
  7. slideWidth: 360,
  8. slideMargin: 10,
  9. auto: false,
  10. infiniteLoop: false
  11. });
  12. }
  13. };
  14. })(jQuery);

Comments

Nicos's picture

Thanks bro'

carks's picture

What do you mean ? In the JS file ?

mriffault's picture

You shoud enventually specify the context in your jQuery selector :

  1. Drupal.behaviors.my_module = {
  2. attach: function(context, settings) {
  3. $('.view-class .item-list ul',context).bxSlider({
  4. minSlides: 2,
  5. maxSlides: 2,
  6. slideWidth: 360,
  7. slideMargin: 10,
  8. auto: false,
  9. infiniteLoop: false
  10. });
  11. }
  12. };