I'm developing a Drupal module. I need to set the focus to the first form element when a page is loaded. I read this can be done by using the jquery code -$('#edit-name').focus();
.
How do I add this code to the Drupal.behaviors so that my code will be automatically called when the page is loaded?
Here is a example on how to use behaviors: Drupal.behaviors.
So all you need to do is put this in a .js file (or add it with inline): For Drupal6:
Drupal.behaviors.focus = function (context) {
$('#edit-name').focus();
};
For Drupal7:
(function($) {
Drupal.behaviors.focus = {
attach:function(context,settings) {
$('#edit-name').focus();
}
}
})(jQuery);
drupal_add_js("$('#edit-name').focus();", "inline");
in module. In theme it's depend where did you want this script, possible just adding in page-XXX.tpl.php direct code of script. In template.php in preprocessors you can use above code.