background image

Content tagged with: jQuery

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

I recently signed up for Google AdSense and I thought it would be fun to show ads for Internet Explorer users. Of course, you could use this tutorial for more productive purposes. Here is how I integrated this functionality into my theme.

I added 2 regions to THEME.info file:

regions[ad_left] = Ad Left
regions[ad_right] = Ad Right

I then included the regions in my theme by adding some code to my theme's page.tpl.php file:

<?php if ($ad_left): ?>
  <div id='ad_left' class='google_ads'>
    <?php print $ad_left; ?>
  </div>
<?php endif; ?>

<?php if ($ad_right): ?>
  <div id='ad_right' class='google_ads'>
    <?php print $ad_right; ?>
  </div>
<?php endif; ?>

Next, I added some CSS in my style.css theme file to absolutely position the regions in a fixed position:

.google_ads {
  position: absolute;
  bottom: 10px;
  width: 120px;
  height: 600px;
  display: none;
}

.google_ads .block {
  padding: 0;
  margin: 0;
}

body > .google_ads {
  position: fixed;
}

#ad_left {
  left: 10px; 
}

#ad_right {
  right: 10px;
}

Now that my regions were setup, I added 2 blocks containing the Google AdSense code and assigned the blocks to my new regions. You'll need to make sure the input filter you choose allows for javascript to be included.

At this point, the ads are included for every browser, but they will not be shown due to the "display: none" property I added to the "google_ads" CSS class. I added a few lines of jQuery in my theme's script.js file to show the regions for IE users:

$(document).ready(function(){
  // per IE ads
  if ($.browser.msie) {
    $('.google_ads').show();  
  }
});

If you view this page in IE, you'll see my code in action ^_^

My additional thoughts... this code executes the Google AdSense javascript regardless of your browser, but it is only shown to IE users. A more efficient method would be to use AJAX to include the javascript ONLY if the browser is IE, or of course, by implementing a server side browser detection library.

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 implemented the Panels module to create a page layout with 3 columns. I added background images to the columns, repeating on the y axis to span the entire length of the column. The problem I encountered: you cannot predict how tall the content will be in your columns and they will be staggered. To provide a more uniform styling, I added some jQuery to find the tallest column and set the shorter ones to the max height.

$(document).ready(function(){

  // keep track of the tallest column
  var tallest = 0;

  // loop through columns and find the tallest
  $('#panel_other_programs .panel-panel').each(function(){
    if ( $(this).outerHeight(true) > tallest )
      tallest = $(this).outerHeight(true);
  });

  // loop through columns and adjust height as necessary
  $('#MY-PANEL-UNIQUE-IDENTIFIER .panel-panel').each(function(){
   
    // check if current column needs to be adjusted
    if ( $(this).outerHeight(true) < tallest ) {
      // set new height
      $(this).height( tallest );
    }
  });

});

Now, all the columns should have a uniform height and the backgrounds should all span the entire length of each column.

Eric's picture

This quick code snippet will show you how to update every external link on your site to open in a new window using jQuery. You can put this code in the script.js file in your theme.

$(document).ready(function(){

  // apply to all <a> tags that have an href that starts with "http"
  $("a[href^='http']").each(function(){

    // remove http:// and https://
    link = $(this).attr('href');
    if (link.substring(0,7)=='http://') {
      link = link.substring(7);
    } else if (link.substring(0,8)=='https://') {
      link = link.substring(8);
    } else {
      return;
    }

    // spilt on '/'
    split1 = link.split('/');

    // compare href hostname to site hostname
    if (split1[0]!=location.hostname) {
      // add target attribute to link
      $(this).attr('target','_blank');
    }

  });

});