[support] Drupal behaviors misbehaving

Jamie Holly hovercrafter at earthlink.net
Fri Mar 15 15:07:19 UTC 2013


First off, you really should use one of the once methods, which is 
different depending on if you're in Drupal 6 or 7. 6 actually doesn't 
have that method, but rather you add a class indicating it's been processed:

$("#x:not(.my-class-processed)", context).each(function(){
   $(this).addClass('my-class-processed');
  {..LOGIC..}
})

For 7:

$("#x", context).once('x', function(){
  {..LOGIC..}

})

That prevents the settings div and handler from getting added multiple 
time during different ajax calls that might fall within the same context.

For your logic, it looks like you're confusing .click() with .toggle(). 
Click responds to every click and only takes a single callback. Toggle() 
takes 2 callbacks, one that is fired on odd clicks and one that is fired 
on even.

var div = $('<div />').addClass('settings');
$(this).prepend(div);
div.toggle(
  // Odd clicks
   function(){
     $('#p').show();
   },
   // Even clicks
  function() {
       $('#p').hide();
})

Even better:

var div = $('<div />').addClass('settings');
$(this).prepend(div);
div.click(function(){
   if ($('#p').is(':visible')) {
         $('#p').hide();
    } else {
         $('#p').show();
    }
})

Jamie Holly
http://www.intoxination.net
http://www.hollyit.net

On 3/15/2013 10:48 AM, Jeff Greenberg wrote:
> I have the following in Drupal.behaviors:
>
> $(context).find('#x').prepend('<div class="settings"></div>');
>       $(context).find('div.settings').click(
>         function () {
>           $('#p').show();
>         },
>         function () {
>           $('#p').hide();
>         }
>       );
> The div gets prepended, but the click does nothing. If I just enter 
> the jQuery('#p').show() in the console, it works fine.
>
> -- 
> ---
> drupal.org/user/367108 <http://drupal.org/user/367108>
> linkedin.com/in/jeffrgreenberg <http://linkedin.com/in/jeffrgreenberg>
> accidentalcoder.com <http://accidentalcoder.com> / ayendesigns.com 
> <http://ayendesigns.com>
> @accidentalcoder
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.drupal.org/pipermail/support/attachments/20130315/a38d5e1b/attachment.html 


More information about the support mailing list