Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Passing variables from PHP to JavaScript in Drupal 7

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 281
    Comment on it

    Drupal provide a mean to pass information easily to JavaScript. Many applications want to pass configuration information to JavaScript that runs on a page.

     "Hello World!"), 'setting');
    //Inline Js
    drupal_add_js('alert(Drupal.settings.helloworld);', array('type' => 'inline', 'scope'=> 'footer'));
    ?>
    

    Sometime it happens that you might have changed the class or id of the element after the page have fully loaded in this scenario javascript won't be able to detect the newly added classes (though there are other way to do it with jQuery). But in drupal, behaviors will help you out to handle this situation.

    Here are some examples where drupal behaviors come handy:

    1. CTools calls it after a modal has been loaded.

    2. Media calls it after the media browser has been loaded.

    3. Panels calls it after in-place editing has been completed.

    4. Views calls it after loading a new page that uses AJAX.

    5. Views Load More calls it after loading the next chunk of items and

    6. JavaScript from custom modules may call Drupal.attachBehaviors() when they add or change parts of the page.

    Drupals official JavaScript documentation suggests that modules should implement JavaScript by attaching logic to Drupal.behaviors

    example:

    Drupal.behaviors.exampleModule = {
      attach: function (context, settings) {
        $('.locatoinCL', context).click(function () {
          $(this).toggle('show');
        });
      }
    };
    
    // Attach all behaviors.
    $(function () {
      Drupal.attachBehaviors(document, Drupal.settings);
    });
    

    where $(function () is a shorthand for $(document).ready() and context is a dom and class locatoinCL is added after the page is loaded

    Drupal core will call attached behaviors when the HTML is fully loaded, and passing in two arguments

    • context : contains the DOM.
    • settings : contains all the settings injected from server side.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: