Using Drupal 7.x w/ jQuery 1.4x, I'm trying to trap the click event when I click on a submit input of an AJAX form generated from this Commerce AJAX Cart module.

In my custom.js behaviors file, I have the following code.


The alert doesn't get displayed and I have no clue as to why. I load my custom.js file from template.php using the following code.

drupal_add_js(path_to_theme() . '/scripts/global.js', array('weight' => 200));

I tried lowering 200 down to insanely low levels just to test if weight had anything to do with any of this, but nothing I tried helped.

Any ideas as to why this click event isn't working would be helpful.

  • IIs this js in a drupal behavior? If not it should be. – 2pha Nov 11 '14 at 4:08
  • 2pha, yes, this is in a Drupal behaviors implementation via the following structure: (function ($) { Drupal.behaviors.global = { attach: function(context, settings){ } } })(jQuery); – Wolf_22 Nov 11 '14 at 4:41
  • why is your behavior called "global" ? – 2pha Nov 11 '14 at 16:32
  • 2pha, I named it this because it's the JS file I used for code that I want to apply to pages across the board, agnostic of content types, etc. (Reading the file name, you probably thought that it was a bunch of global-scoped code or something, which it isn't.) :) – Wolf_22 Nov 12 '14 at 2:05

Because the form is being loaded via ajax, your click handler is not binding at the right time. You need to use Drupal.behaviors, the context argument, and possibly the one() method to attach this.

Or a less drupally (but better jQuery) solution would be to use delegated events like

$(document).click(function(event)) {
  if ($(event.target).is(".form-submit") {

Note: delegated events are way more elegant in modern jQuery, the on() method is great for this. But the above is probably the best you can do in jQuery 1.4.

  • Coleman, the code I'm trying to get to work is in the Drupal behaviors configuration: (function ($) { Drupal.behaviors.global = { attach: function(context, settings){...} } })(jQuery); I tried what you posted however, and it just wouldn't show anything--I even tried to console.log(event) outside of the if condition and it still wouldn't show anything in Firebug. Any other ideas? – Wolf_22 Nov 11 '14 at 4:44
  • Coleman, I have to apologize to you. It was late last night when I commented on your response and after submitting my comment, I suddenly realized that I forgot to clear Drupal's damn cache. Ha. After doing this, I wound up seeing some changes, FINALLY. It's not exactly what I want but this is only because I didn't ask the correct question. I'll mark your answer as the correct, and seriously, thanks! Major help! – Wolf_22 Nov 12 '14 at 2:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.