- The code of adding jquery ready event in a js file which is added in a module using drupal_add_js or form['attached'] may not work. Below is a sample code not working.add js using Drupal Form API
//add js files used for the forms $form['#attached']['js'] = array( 'https://maps.googleapis.com/maps/api/js?libraries=places', drupal_get_path('module', 'urbansherpabooking') . '/js/booking.js', );the snippet of booking.js where jquery ready event are added//initialize the autocomplete address input in pickup form (function($){ if($('#edit-pickup-details-pickup-from').length == 1){ var auto_address = new initailize_autocomplete_address('edit-pickup-details-pickup-from'); auto_address.initialize(); $('#edit-pickup-details-pickup-from').focus(auto_address.geolocate()); } }(jQuery)); - The jquery ready event will never be added, because js file is loaded after the document's being loaded.
- To solve the issue, use drupal behaviour instead of jquery ready event and use drupal_add_js instead of Form API like the following code.
//use drupal behaviour instead of jquery ready event Drupal.behaviors.urbansherpabooking = { attach: function (context, settings) { //initialize the autocomplete address input in pickup form (function($){ if($('#edit-pickup-details-pickup-from').length == 1){ var auto_address = new initailize_autocomplete_address('edit-pickup-details-pickup-from'); auto_address.initialize(); $('#edit-pickup-details-pickup-from').focus(auto_address.geolocate()); } }(jQuery)); } };drupal_add_js('https://maps.googleapis.com/maps/api/js?libraries=places'); drupal_add_js(drupal_get_path('module', 'urbansherpabooking') . '/js/booking.js'); - Note: When using Drupal.behaviors to attach function as jQuery ready and using drupal ajax to reload some html elements, the function will be executed every time after ajax reload finished.
Monday, 9 March 2015
fix the issue that jquery ready event not work
Labels:
tips
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment