HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Toggling dropdowns using jQuery, with binding and unbinding

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
dropdownswithtogglingunbindingjqueryusingbindingand

Problem

This code is used to toggle some dropdowns. I've added the click event on the document to close the dropdown on click outside, but I'm not sure if I'm doing it the right way. I want it to be optimized for better performance.

Let me know if you have a better way to bind/unbind the events.

$('.header-top-bar .toggle').each(function (index) {
  var $this = $(this),
      $parent = $this.parent(),
      $dropdown = $this.siblings('.toggle-content');

  $this.on('click.toggle' + index, function (event) {
    event.preventDefault();

    $dropdown.toggleClass('isOpen');

    // Outside
    $document.on('click.toggle' + index, function (event) {
      if (!$(event.target).closest($parent).length) {
        $dropdown.removeClass('isOpen');
        $document.off('click.toggle' + index);
      }
    });
  });
});


jsFiddle

Solution

First, regarding readability, I suggest changing the following names:

  • $dropdown -> $content



  • .toggle (class) -> .togglable



  • .toggle (namespace) -> .toggling



  • .isOpen -> isToggleOpen



On the other hand this can be achieved with reduced code (and less internal working impact), with only one event binded:

var $togglables = $('.togglable-content');
$(document).on('click.toggling', function (event) {
  var $target = $(event.target),
  $content = $target.siblings('.togglable-content');
  if (!$target.hasClass('isTogglableOpen')) {
    $togglables.not($content).removeClass('isTogglableOpen');
    $content.toggleClass('isTogglableOpen');
    return false;
  }
});


Here is the modified fiddle.

Code Snippets

var $togglables = $('.togglable-content');
$(document).on('click.toggling', function (event) {
  var $target = $(event.target),
  $content = $target.siblings('.togglable-content');
  if (!$target.hasClass('isTogglableOpen')) {
    $togglables.not($content).removeClass('isTogglableOpen');
    $content.toggleClass('isTogglableOpen');
    return false;
  }
});

Context

StackExchange Code Review Q#117318, answer score: 4

Revisions (0)

No revisions yet.