background image

Content tagged with: drupal_add_js

Eric's picture

In this tutorial, I'll show a way to pass PHP/Drupal variables to javascript using drupal_add_js(), and a way you can debug javascript variables using the FireBug console.

I'll start by creating a hook_menu() implementation to establish a page callback:

<?php
function helper_menu() {

 
$items = array();
 
 
$items['js-vars'] = array(
   
'title' => t('Javascript Variables'),
   
'description' => t('Javascript Variables'),
   
'page callback' => 'helper_page_callback_js_vars',
   
'access arguments' => array('access content'),
   
'type' => MENU_CALLBACK,   
  );
 
  return
$items;

}
?>

Next, I'll define the page callback:

<?php
function helper_page_callback_js_vars() {

 
// include module javascript file
 
drupal_add_js(drupal_get_path('module','helper') . '/js/helper.js');

 
// define variables you'd like to pass to the DOM
 
$js_vars = array(
   
'js_vars' => array(
     
'message' => t('Hello @username', array('@username' => $GLOBALS['user']->name)),
     
'an_array' => array(
       
'color' => t('red'),
       
'name' => t('Eric'),
      ),
    ),
  );
 
 
// pass variables to javascript
 
drupal_add_js($js_vars, 'setting');
 
 
// generate some page output
 
return "TEST";

}
?>

And here is the contents of the javascript include file I stuck in my module directory:

$(document).ready(function(){

  // debug variables directly in FireBug
  console.debug(Drupal.settings.js_vars);
 
  // popup mesage passed from Drupal
  alert(Drupal.settings.js_vars.message);
 
});

When viewing this page in a browser, you'll see the following. The javascript popup window is using variables passed directly from a Drupal/PHP array:
javascript popup

The console.debug() javascript method was used to send data directly to the FireBug console. If you open FireBug, you'll see the following:
FireBug Console

If you click on the Object shown, you can drill into the variables further:
FireBug Console

Eric's picture

In this tutorial I'll show you how you can add jQuery image carousel functionality to your CCK node. This tutorial requires you to install the following modules:

cck
filefield
imageapi
imagecache
imagefield

NOTE: The next few steps assume you have not already setup a content type and ImageCache preset. You can ignore them if you already have.

Once you installed the above modules and set permission accordingly, you'll need to define an ImageCache preset (/admin/build/imagecache/add). I called mine "thumbnail" for this example. I added a "Add Scale" action to set the width to 100 (pixels). This will ensure when you create an image, a thumbnail will be created automatically.

Create a new content type (/admin/content/types/add). I called mine "Carousel" for this example. I then clicked on "Manage Fields" (/admin/content/node-type/carousel/fields) to setup a new Image field. I called my new field "field_images", selected "File" for field type, and selected "Image" for the form element.

On the next screen, scroll down to the Global fieldset region and enable the "Required" checkbox, and set the "Number of Values" to "Unlimited". This will allow the user to upload numerous image files to the same CCK field.

Next, you'll want to set which image preset it shown when viewing the node, by clicking on "Display fields" (/admin/content/node-type/carousel/display). I chose the "thumbnail image" preset for both the teaser and full node displays.

I then created a new carousel node (/node/add/carousel). I used the "Add another item" button to upload three images to this node.

If you view the node, the images will be stacked vertically.

This is where the fun starts. You'll need to download the jQuery Carousel library (http://sorgalla.com/projects/jcarousel/). I downloaded the jcarousel.zip file and unpacked it. Copy the entire unpacked jcarousel folder into your theme directory.

Now, you'll need to add a preprocess_node function to your template.php file:

<?php
function YOURTHEME_preprocess_node(&$variables) {
 
 
// test for carousel node type
 
if ($variables['type'] == 'carousel') {

   
// include jCarousel javascript
   
drupal_add_js(path_to_theme() . '/jcarousel/lib/jquery.jcarousel.js');
   
   
// add jquery in enable jQuery carousel on <ul>
   
$js = "
      $(document).ready(function(){
        $('#mycarousel').jcarousel();
      });
    "
;
   
drupal_add_js($js, 'inline');
   
   
// include jCarousel css
   
drupal_add_css(path_to_theme() . '/jcarousel/lib/jquery.jcarousel.css');
   
drupal_add_css(path_to_theme() . '/jcarousel/skins/tango/skin.css');
   
   
// loop through images and create an item list
   
$items = array();
    foreach (
$variables['field_images'] as $key => $value) {
     
$items[] = $value['view'];
    }
   
   
// ensure images exist
   
if (count($items)) {
     
// add jQuery carousel html to $content variable
     
$variables['content'] .= theme('item_list', $items, NULL, 'ul', array('id' => 'mycarousel', 'class' => 'jcarousel-skin-tango'));
    }
   
  }
 
}
?>

The previous code snippet should result in the following:

If you'd like you can hide the old image html by adding a single line of CSS (or by adding more elaborate code in your template preprocess function).

Example:

div.field-field-images {
  display: none;
}

Adding the previous CSS will result in this example:

Eric's picture

I recently added an admin settings page to allow the user to select colors for node title labels. I quick Google search and I discovered this promising jQuery color picker library. Here's how I embedded it in a form.

First I unpacked the colorpicker.zip file and moved it into my theme folder. Next, I added a form callback function in my module.

<?php
// defining my form callback function
function _MYFORM() {
 
 
$form = array();

 
// include css & javascript for color picker
 
drupal_add_css(path_to_theme() . '/colorpicker/css/colorpicker.css');
 
drupal_add_js(path_to_theme() . '/colorpicker/js/colorpicker.js');

 
// define field ID
 
$formElementID = 'MYFORMELEMENT';

 
// create a javascript-friendly ID
 
$jsID = 'edit-' . str_replace('_','-',$formElementID);

 
// adding textfield input for color picker widget
 
$form[$formElementID] = array(
   
'#type' => 'textfield',
   
'#title' => t('MY FIELD TITLE'),
   
'#size' => 6,
   
'#maxlength' => 6,
   
'#suffix' => "
      <script type='text/javascript'>
        $(document).ready(function(){
          colorPickerAttach('#$jsID');
        });
      </script>"
 
);

 
// add a javascript function to attach the color picker to a form element
 
$js = "
    function colorPickerAttach(which) {
      $(which).ColorPicker({
        onSubmit: function(hsb, hex, rgb) {
          $(which).val(hex);
        },
        onBeforeShow: function () {
          $(this).ColorPickerSetColor(this.value);
        }
      })
      .bind('keyup', function(){
        $(this).ColorPickerSetColor(this.value);
      });
    }
  "
;
 
drupal_add_js($js, 'inline');

  return
$form;

}
?>

Now, my form has a text input that uses a fancy color picker to choose the hex value. More documentation on the color picker can he found here.

Here's a screenshot of the color picker in action:

Eric's picture

You've probably seen the accordion effect in use at Apple's website. I recently implemented this plugin in a Drupal module to get a similar effect.

First, download the plugin from Bassistance. I stuck the jquery.accordion.js in my module directory and then included it using the following code:

<?php
drupal_add_js
(drupal_get_path('module','MYMODULENAME') . '/jquery.accordion.js');
?>

I created a dataset to use with the theme_item_list function. For this example, I'll query the node table.

<?php
$sql
= "select title from {node} where status='1' order by title asc";
$resource = db_query($sql);
$results = array();
while (
$row = db_fetch_array($resource)) $results[] = $row;
?>

I looped through the dataset and created an item list array consisting of an A tag and a DIV.

<?php
$items
= array();
foreach (
$results as $k => $v) {
 
// NOTE: you should use the l() function here, excuse my example
 
$items[] = "<a>{$v['title']}</a><div>MYTEXTHERE</div>";
}
?>

I used the theme function to generate the html for a UL with a unique identifier.

<?php
$title
= MYTITLE;
$type = 'ul';
$attributes = array(
 
'id' => 'MYITEMLISTID',
);
$page_contents .= theme('item_list', $items, $title, $type, $attributes);
?>

Last, I added the jQuery to apply the accordion effect to my UL.

<?php
$(document).ready(function(){
  $(
'#MYITEMLISTID').accordion();
});
?>

Eric's picture

In a module I was developing recently, I needed to add a javascript confirm popup before allowing the user to submit the form. Here is an excerpt from my code to show you how to add the jQuery

<?php
function MYMODULE_main() {
 
$page_contents  = "";
 
// ...code...
 
$page_contents .= drupal_get_form('MYMODULE_form');
 
// ...code...
 
return $page_contents;
}

function
MYMODULE_form() {
 
$form = array();
 
// ...code...
 
$js = "
    $(document).ready(function(){
      $('#"
. str_replace('_','-',__FUNCTION__) . "').submit(function(){
        if (confirm('Are you sure?')) {
          return true;
        } else {
          return false;
        }
      );
    });
  "
;
 
drupal_add_js($js, 'inline');
 
// ...code...
 
return $form;
}
?>