JQuery for CCK field best practices and help

Events happening in the community are now at Drupal community events on www.drupal.org.
webdrips's picture

Hi all.

I'm still relatively new to the development side of Drupal, so please excuse these dumb questions.

Essentially, I am attempting to add a jQuery plugin (http://plugins.jquery.com/project/spin-button) that works on a text box to increment/decrement an integer value in the box. That text box was created using the CCK for a custom content type. Upon inspecting the DOM when adding/editing that content type, I see the ID = "edit-field-player-strength-0-value".

So, I am attempting to use the Spin plugin with my CCK field in the following way:

  1. Copy the file jquery.spin.js to my sites/all/plugins directory.
  2. In template.php, I added the following line: drupal_add_js('sites/all/plugins/jquery.spin.js');. Using Firebug, I see the file and code listing now showing up in the "head" section.
  3. In my theme's root folder, I created the script.js file with the listing below (and placed the images in the appropriate place).

script.js:

$(document).ready(function(){
  $("#edit-field-player-strength-0-value").spin({imageBasePath:"/files/",max:100,min:0});
});

But alas, no joy on the script running. Note that a very basic script like $("p").hide().fadeIn(1000); from script.js works like a charm on all paragraphs, so I feel I am very close.

My first question: (with the exception of not degrading gracefully), what am I doing wrong?
My second question: is the approach described above in-line with a "best practices" approach or should I be going about this a different way? (The old get hit by a bus and someone has to take over the code conundrum.)

Comments

first of all, I should place

skilip's picture

first of all, I should place the images in the theme directory instead in the files folder. Any file which isn't placed in the files folder without the use of Drupals uploadsystem is deleted after cron.

Secondly you best double check all paths. If you're absolutely sure that's correct, you should try applying the plugins behavior to more elements (just to be sure re selector you use is correct).

If you've got it all working you could consider moving the drupal_add_js stuff into a theme overwrite function inside template.php. This way the script is only loaded when the form field is present.

It was the path!

webdrips's picture

Skilip,

Thanks and yes it was the path! What I am failing to understand is why I had to look at the JQuery file being loaded closely before recognizing the error. You see, a file was being loaded by the drupal_add_js alright, but it was some HTML garbage. Strange thing was, there were no actual files in the folder I pointed to, so I can't imaging what could have been loading.

Your comment on the images does not appear to be true though. I just ran cron.php and did not encounter any issues with the files being deleted.

I will look into the theme overwrite function as you suggested and the next suggestion.

Dan

Need Drupal module or theme design? Please visit Webdrips to learn how we can help.

Drupal.behaviors

markus_petrux's picture

Also, consider using Drupal.behaviors rather than $(document).ready().

Drupal.behaviors.addSpinToPlayerStrength = function(context) {
  $('#edit-field-player-strength-0-value:not(.spin-processed)', context).addClass('spin-processed').each(function() {
    $("#edit-field-player-strength-0-value").spin({imageBasePath:"/files/",max:100,min:0});
  });
});

This way, Drupal will invoke your code when the document is ready, but also when some one else modifies the DOM and invokes Drupal.attachBehaviors(). See misc/drupal.js

You may also try alert($("#edit-field-player-strength-0-value").size()); from the javascript console or firebug to see if the selector for your field really works.

Thanks for the tip!

webdrips's picture

Markus,

Thank you for the tip! What is the best place to insert the code you described above?

These are the types of tips I need, but the Pro Drupal Development book is lacking. Are there any tutorials you know of on the overall best practices for using Javascript in Drupal 6?

Thanks again,

Dan

Need Drupal module or theme design? Please visit Webdrips to learn how we can help.

Placement of the code

markus_petrux's picture

Usually, you put your javascript code in a separate file (for example mymodule.js) in your module directory. In the PHP script of your module you use drupal_add_js() to tell Drupal to append this .js file whenever it's needed. This API function can be used to add a JavaScript file, setting or inline code to the page. So in the PHP file of your module you could do something like this:

<?php
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (
$form_id == 'xxx' /* && whatever else condition to match the form you're interested in */) {
   
// Send javascript library with custom Drupal behaviors.
   
drupal_add_js(drupal_get_path('module', 'mymodule') .'/mymodule.js');
   
// Send settings for the custom javascript code.
   
$js_settings = array(
     
'imageBasePath' => base_path() . url('path/to/myfiles'),
    );
   
drupal_add_js(array('mymodule' => $js_settings), 'setting');
  }
}
?>

Your javascript file could look like this:

Drupal.behaviors.addSpinToPlayerStrength = function(context) {
  if (Drupal.settings && Drupal.settings.mymodule) {
    $('#edit-field-player-strength-0-value:not(.spin-processed)', context).addClass('spin-processed').each(function() {
      $("#edit-field-player-strength-0-value").spin({
        imageBasePath: Drupal.settings.mymodule.imageBasePath, // <-- Comes from PHP ($js_settings).
        max: 100,
        min: 0
      });
    });
  }
});

Read the comments in misc/drupal.js or misc/textarea.js to learn how this works.

As per best practices... not sure how to advice. I'm using Drupal since 4.6 and keep learning by looking at the code itself, core or contrib. Before doing anything I always ask myself: How core do this? How other contrib authors do this? It often happens that you don't need to reinvent the wheel. :) Also, another valuable resource is the issues queue (here you can often find why something was made in a particular way), the handbooks, the online API, example modules, ...

Javascript

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: