0

I'm having trouble doing simple stuff in jQuery. What I wanted was to call a function when something was typed in an input field.

Now I'm just trying this: when you click anywhere on the page to call an alert box like this:

(function ($) {
    $('body').click(function() {
        alert('test');
    });
})(jQuery);

This doesn't work ... . But when I do this:

(function ($) {
    alert('test');
})(jQuery);

I get an alert box when I load the page. My js file is loaded like this:

function xmed_preprocess_page(&$vars) {
    $path = current_path();
    if ($path == 'node/add/product') {
        drupal_add_js(drupal_get_path('theme', 'subtheme') . "/js/add.js", array('weight' => 1000));
    }
}

The file is loaded correctly. I'm working with jQuery v1.10.2. What could be the problem?

1
  • It doesn't work because the DOM is not yet loaded; that code would not work even without Drupal.
    – apaderno
    Apr 29 '14 at 7:48
2

Try this as per drupal standard

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('body', context).click(function () {
        alert("test");
      });
    }
  };
})(jQuery);

Go through with Managing JavaScript in Drupal 7 for more information

2
  • And how can you know the module? It's on my page 'node/add/product' that I need JS.
    – nielsv
    Apr 30 '14 at 11:57
  • Check body tag consist class 'page-node-add-product' on add product page & 'node-type-product' on edit product page. Use this and handle it.
    – Rupesh
    Apr 30 '14 at 12:14
0

maybe the problem is by your css, open the firebug and see what is the dimension of the body. change the target of body to some thing else like a button. you can also set

body,html{
width:100%;
height:100%;
}

you can also test

(function($) {
$(document).ready(function() {
    $("body").click(function(){
         alert("test");
    });
});
})(jQuery);

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