0

Problem

I'm using jQuery toggle to make one block appear when another is clicked. The code works in jsfiddle but doesn't in Drupal.

Set-Up

I have a node with two blocks on it, applytoggle and tellafriend. Apply toggle:

<div class="applytoggle">
    //*Other stuff*
</div>

Tellafriend:

<div id="block-tellafriend-tellafriend-form" class="block block-tellafriend"></div>

In my template file I add the following script :

function mytheme_preprocess_page (&$vars) {
  drupal_add_js('sites/all/themes/tefltheme/toggle.js', 'file');

Which looks like this:

(function ($) {
    $('div.applytoggle').click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
    });
})(jQuery);

This works great in jsfiddle - http://jsfiddle.net/dr9vG/, but doesn't in my actual page. The script is loaded successfully and I've got other jQuery scripts loaded and running the same way which work (not related, different objects). Why doesn't this work?

1 Answer 1

5

Most likely because the JS code you write in JSFiddle is automatically run when the document is ready; the same isn't true in a normal environment, you need to be explicit:

(function ($) {
  $(function() {
    $('div.applytoggle').click(function() {
      $('.applytoggle_title, .block-tellafriend').toggle();
    });
  });
})(jQuery);

But to be properly Drupal you should use behaviors:

(function ($) {
  Drupal.behaviors.myToggle = {
    attach: function(context, settings) {
      $('div.applytoggle', context).click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
      });
    }
  };
})(jQuery);
2
  • Yep, I just tried wrapping it in jQuery(document).ready(function(){ on a hunch and that also works. I'd got myself all confused and thought the Drupal wrapper initialized the code and then the click function would call it. Thank you! Sep 1, 2013 at 21:36
  • $(function() {...}) is a handy little shortcut for $(document).ready(function() {...}) so yeah both will work; using behaviors is still preferable for Drupal though; it means if any part of your page is replaced by the AJAX API at any point, your code will be run again, in the correct context, and the events will be re-attached
    – Clive
    Sep 1, 2013 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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