SlideShare a Scribd company logo
1 of 22
Download to read offline
jQuery in Drupal:
overview, tools, how-tos
 DrupalCamp Vancouver 2008
Introduction

• jQuery is a JavaScript Framework

• In core since Drupal 5 (version 1.0.1)

• Modular, like Drupal itself

• and, like Drupal, constantly evolving...
Overview / Timeline
jQuery Syntax Refresher
• Selectors
   – $(‘#myId’), $(‘div.myClass’),
     $(‘li:not(.active)’), $(‘a[href^=“mailto”]’)
• Commands
   – .hide(), .show(), .slideToggle(), .each(), etc
• Utility Functions
   – $.each(), $.get(), $.browser(), $.noConflict()

• Chaining Example
  $('div.myClass').not(':first-child').hide().end().filter(':first-child').wrap
  ('<div class=quot;my-wrapperquot;></div>');
Important Functions

• drupal_add_js
  – Add a JavaScript file, setting or inline code to the
    page
  – parameters: data, type, scope, defer, cache
  – Examples:
     • drupal_add_js(drupal_get_path(‘module’,
       ‘mymodule’) .'/myjs.js');
     • drupal_add_js(array(‘myjs’=>$mysettings), ‘setting’);
     • Drupal_add_js(‘var myVar = “foo”;’, ‘inline’);
• Use ‘setting’ type to make your module’s
  settings available to js
Important Functions

• drupal_get_js()
  – called from phptemplate.engine (assigned
    to scripts variable)
  – makes a call to drupal_add_js() to get the
    $javascript array
  – $output .= '<script type=quot;text/javascriptquot;>
    Drupal.extend({ settings: '. drupal_to_js
    (call_user_func_array('array_merge_recursive',
    $data)) .quot; });</script>nquot;;
Important Functions

• drupal_to_js()
  – Converts a PHP variable into its JavaScript
    equivalent
  – e.g. convert a PHP array into a JSON object
  – used in the callback function for an AJAX
    path
The Drupal JavaScript Object

 drupal.js in D5:
 var Drupal = Drupal || {};



 drupal.js in D6:

 var Drupal = Drupal || { 'settings': {},
 'behaviors': {}, 'themes': {}, 'locale': {} };
Ajaxifying Drupal with jQuery

• Asynchronous JavaScript and XML
  – retrieve data from the server and load into
    the DOM of the current page without
    refreshing the page
  – $(‘#someDiv’).load(‘/serverResource’);
  – the above corresponds to about 20 lines of
    normal js
• jQuery provides different AJAX
  functions, depending on your needs
Ajaxifying Drupal with jQuery

• jQuery AJAX functions:
  – $(‘#someDiv’).load(url, parameters,
    callback);
  – $.get(url, parameters, callback)
  – $.post(url, parameters, callback)
  – $.ajax(options)
Ajaxifying Drupal with jQuery




                         11
Ajaxifying Drupal with jQuery

• Basic essentials:
  – $.get (or another AJAX method)
  – drupal/path (menu callback)
  – callback function
• drupal_to_js($var)
  – to convert your php array into a JSON
    array
• Drupal.parseJSON(data)
Ajaxifying Drupal with jQuery
                Menu Callback

$items[] = array(
  'path' => 'photostories/get/photos',
  'type' => MENU_CALLBACK,
  'access' => user_access('access content'),
  'callback' => 'kflick_get_photos_ajax'
);
Ajaxifying Drupal with jQuery
                Callback Function

function kflick_get_photos_ajax($nid) {
    $photo = kflick_get_photo($nid);
    $imagefile = theme('image', $photo);
    print drupal_to_js(array(
    'image' => $imagefile,
    )
    );
}
Ajaxifying Drupal with jQuery
Drupal.kflick = function() {
  var imageDetails = function(data) {
    var result = Drupal.parseJson(data);
    $('div.field-type-image div.field-item').html(result['image']);
  }
  $('a.kflick_button').click(function(){
    $('a.kflick_button').removeClass('active');
    $(this).addClass('active');
    $.get('/photostories/get/photos/'+ parseInt(this.id, 10), null,
imageDetails);
    return false;
  });
}

if (Drupal.jsEnabled) {
	

     $(document).ready(Drupal.kflick);
}
Drupal 6: behaviors

• In D6, wrap all your module’s jQuery
  behaviours in a function assigned to
  Drupal.behaviors.mymodule
• no need to call it within
  $(document).ready() as Drupal
  automatically does it for you
• all behaviors can then be reattached to
  DOM elements that have come from an
  AJAX call
Drupal 6: behaviors
Drupal.behaviors.kflick = function(context) {
  $('div.field-type-image:not(.kflick-processed)', context).addClass
(‘kflick-processed’).each(function(){
    var imageDetails = function(data) {
      var result = Drupal.parseJson(data);
      $('div.field-type-image div.field-item').html(result['image']);
    }
    $('a.kflick_button').click(function(){
      $('a.kflick_button').removeClass('active');
      $(this).addClass('active');
      $.get('/drupal/sandbox/photostories/get/photos/'+ parseInt
(this.id, 10), null, imageDetails);
      return false;
    });
  });
}
Drupal 6: behaviors
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
       jQuery.each(Drupal.behaviors,
   function() {
      this(context);
    });
  }
};
What is AHAH?

• Asynchronous HTML and HTTP
• still uses the XMLHttpRequest object
• still uses JavaScript
• loads html content retrieved from the
  server directly into the DOM - no
  parsing necessary
• AHAH in Drupal = AHAH Forms
• AHAH Forms Framework module
• In core as of D6
AHAH in Drupal 6
  $form['qt_wrapper']['tabs_more'] = array(
     '#type' => 'submit',
     '#value' => t('More tabs'),
     '#description' => t(quot;Click here to add more tabs.quot;),
     '#weight' => 1,
     '#submit' => array('qt_more_tabs_submit'), // If no
javascript action.
     '#ahah' => array(
        'path' => 'quicktabs/ahah',
        'wrapper' => 'quicktabs-tabs',
        'method' => 'replace',
        'effect' => 'fade',
     ),
  );
Drag & Drop
drupal_add_tabledrag($table_id, $action, $relationship, $group);

theme('table', $header, $rows, array('id' => 'my-table'));

$form['my_elements'][$delta]['weight']['#attributes']
['class'] = quot;my-elements-weightquot;;

$row = array(...);
$rows[] = array(
'data' => $row,
'class' => 'draggable',
);

drupal_add_tabledrag('my-module-table', 'order',
'sibling', 'my-elements-weight');
Resources

• JavaScript Startup Guide
  on api.drupal.org
• drupaldojo.com/lesson/ahah
• http://jquery.com
• Firebug console
• Books
  – Learning jQuery
  – jQuery in Action

More Related Content

What's hot

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Krista Thomas
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7Michael Milz
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinADCI Solutions
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigWake Liu
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jeresig
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)jeresig
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.xJoão Ventura
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationMevin Mohan
 
JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)jeresig
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)JavaScript Libraries (@Media)
JavaScript Libraries (@Media)jeresig
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...DicodingEvent
 
AngularJS first steps
AngularJS first stepsAngularJS first steps
AngularJS first stepsseges
 

What's hot (20)

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton Shubkin
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
BackboneJs
BackboneJsBackboneJs
BackboneJs
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.x
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)JavaScript Libraries (@Media)
JavaScript Libraries (@Media)
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
AngularJS first steps
AngularJS first stepsAngularJS first steps
AngularJS first steps
 

Viewers also liked

Viewers also liked (8)

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 

Similar to JQuery In Drupal

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryRemy Sharp
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptDarren Mothersele
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowWork at Play
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfacesmaccman
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zLEDC 2016
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuerydeimos
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)jeresig
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Treeadamlogic
 

Similar to JQuery In Drupal (20)

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

JQuery In Drupal

  • 1. jQuery in Drupal: overview, tools, how-tos DrupalCamp Vancouver 2008
  • 2. Introduction • jQuery is a JavaScript Framework • In core since Drupal 5 (version 1.0.1) • Modular, like Drupal itself • and, like Drupal, constantly evolving...
  • 4. jQuery Syntax Refresher • Selectors – $(‘#myId’), $(‘div.myClass’), $(‘li:not(.active)’), $(‘a[href^=“mailto”]’) • Commands – .hide(), .show(), .slideToggle(), .each(), etc • Utility Functions – $.each(), $.get(), $.browser(), $.noConflict() • Chaining Example $('div.myClass').not(':first-child').hide().end().filter(':first-child').wrap ('<div class=quot;my-wrapperquot;></div>');
  • 5. Important Functions • drupal_add_js – Add a JavaScript file, setting or inline code to the page – parameters: data, type, scope, defer, cache – Examples: • drupal_add_js(drupal_get_path(‘module’, ‘mymodule’) .'/myjs.js'); • drupal_add_js(array(‘myjs’=>$mysettings), ‘setting’); • Drupal_add_js(‘var myVar = “foo”;’, ‘inline’); • Use ‘setting’ type to make your module’s settings available to js
  • 6. Important Functions • drupal_get_js() – called from phptemplate.engine (assigned to scripts variable) – makes a call to drupal_add_js() to get the $javascript array – $output .= '<script type=quot;text/javascriptquot;> Drupal.extend({ settings: '. drupal_to_js (call_user_func_array('array_merge_recursive', $data)) .quot; });</script>nquot;;
  • 7. Important Functions • drupal_to_js() – Converts a PHP variable into its JavaScript equivalent – e.g. convert a PHP array into a JSON object – used in the callback function for an AJAX path
  • 8. The Drupal JavaScript Object drupal.js in D5: var Drupal = Drupal || {}; drupal.js in D6: var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };
  • 9. Ajaxifying Drupal with jQuery • Asynchronous JavaScript and XML – retrieve data from the server and load into the DOM of the current page without refreshing the page – $(‘#someDiv’).load(‘/serverResource’); – the above corresponds to about 20 lines of normal js • jQuery provides different AJAX functions, depending on your needs
  • 10. Ajaxifying Drupal with jQuery • jQuery AJAX functions: – $(‘#someDiv’).load(url, parameters, callback); – $.get(url, parameters, callback) – $.post(url, parameters, callback) – $.ajax(options)
  • 12. Ajaxifying Drupal with jQuery • Basic essentials: – $.get (or another AJAX method) – drupal/path (menu callback) – callback function • drupal_to_js($var) – to convert your php array into a JSON array • Drupal.parseJSON(data)
  • 13. Ajaxifying Drupal with jQuery Menu Callback $items[] = array( 'path' => 'photostories/get/photos', 'type' => MENU_CALLBACK, 'access' => user_access('access content'), 'callback' => 'kflick_get_photos_ajax' );
  • 14. Ajaxifying Drupal with jQuery Callback Function function kflick_get_photos_ajax($nid) { $photo = kflick_get_photo($nid); $imagefile = theme('image', $photo); print drupal_to_js(array( 'image' => $imagefile, ) ); }
  • 15. Ajaxifying Drupal with jQuery Drupal.kflick = function() { var imageDetails = function(data) { var result = Drupal.parseJson(data); $('div.field-type-image div.field-item').html(result['image']); } $('a.kflick_button').click(function(){ $('a.kflick_button').removeClass('active'); $(this).addClass('active'); $.get('/photostories/get/photos/'+ parseInt(this.id, 10), null, imageDetails); return false; }); } if (Drupal.jsEnabled) { $(document).ready(Drupal.kflick); }
  • 16. Drupal 6: behaviors • In D6, wrap all your module’s jQuery behaviours in a function assigned to Drupal.behaviors.mymodule • no need to call it within $(document).ready() as Drupal automatically does it for you • all behaviors can then be reattached to DOM elements that have come from an AJAX call
  • 17. Drupal 6: behaviors Drupal.behaviors.kflick = function(context) { $('div.field-type-image:not(.kflick-processed)', context).addClass (‘kflick-processed’).each(function(){ var imageDetails = function(data) { var result = Drupal.parseJson(data); $('div.field-type-image div.field-item').html(result['image']); } $('a.kflick_button').click(function(){ $('a.kflick_button').removeClass('active'); $(this).addClass('active'); $.get('/drupal/sandbox/photostories/get/photos/'+ parseInt (this.id, 10), null, imageDetails); return false; }); }); }
  • 18. Drupal 6: behaviors Drupal.attachBehaviors = function(context) { context = context || document; if (Drupal.jsEnabled) { // Execute all of them. jQuery.each(Drupal.behaviors, function() { this(context); }); } };
  • 19. What is AHAH? • Asynchronous HTML and HTTP • still uses the XMLHttpRequest object • still uses JavaScript • loads html content retrieved from the server directly into the DOM - no parsing necessary • AHAH in Drupal = AHAH Forms • AHAH Forms Framework module • In core as of D6
  • 20. AHAH in Drupal 6 $form['qt_wrapper']['tabs_more'] = array( '#type' => 'submit', '#value' => t('More tabs'), '#description' => t(quot;Click here to add more tabs.quot;), '#weight' => 1, '#submit' => array('qt_more_tabs_submit'), // If no javascript action. '#ahah' => array( 'path' => 'quicktabs/ahah', 'wrapper' => 'quicktabs-tabs', 'method' => 'replace', 'effect' => 'fade', ), );
  • 21. Drag & Drop drupal_add_tabledrag($table_id, $action, $relationship, $group); theme('table', $header, $rows, array('id' => 'my-table')); $form['my_elements'][$delta]['weight']['#attributes'] ['class'] = quot;my-elements-weightquot;; $row = array(...); $rows[] = array( 'data' => $row, 'class' => 'draggable', ); drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  • 22. Resources • JavaScript Startup Guide on api.drupal.org • drupaldojo.com/lesson/ahah • http://jquery.com • Firebug console • Books – Learning jQuery – jQuery in Action