user4367388
user4367388

Reputation:

Difference between jquery chain and no jquery chain

I don't know if the title of the question is correct, because i don't know exactly what is this.

I have this piece of code:

  $actual.find('h2').addClass('event__change')
    .append('<span class="event__arrow" aria-hidden="true">&#9660;</span>')
    .append(function () {
      var self = $(this);
      var list = '<ul class="dropdown hidden">';

      $('.event').each(function (index) {
        if ($(this).find('h2')[0] != self[0]) {
          list += "<li data-index='" + index + "'>" + $(this).find('h2').text() + '</li>';
        }
      });
      return list;
    })
    .click(function () {
      if ($(this).attr("data-expanded") == true) {
        $(this).find("ul").toggleClass('hidden');
        $(this).attr("data-expanded", false);
      } else {
        $(this).find("ul").toggleClass('hidden');
        $(this).attr("data-expanded", true);
      }
    });

And i was trying to use like this:

  $actual.find('h2').addClass('event__change');
  $actual.append('<span class="event__arrow" aria-hidden="true">&#9660;</span>');

  $actual.append(function () {
      var self = $(this);
      var list = '<ul class="dropdown hidden">';

      $('.event').each(function (index) {
        if ($(this).find('h2')[0] != self[0]) {
          list += "<li data-index='" + index + "'>" + $(this).find('h2').text() + '</li>';
        }
      });
      return list;
    });

    $actual.click(function () {
      if ($(this).attr("data-expanded") == true) {
        $(this).find("ul").toggleClass('hidden');
        $(this).attr("data-expanded", false);
      } else {
        $(this).find("ul").toggleClass('hidden');
        $(this).attr("data-expanded", true);
      }
   });

But if i try change to the second code, the effect will broke totally, and i want understand why..

Upvotes: 0

Views: 32

Answers (2)

Ruben Kazumov
Ruben Kazumov

Reputation: 3892

You can easily fix the code:

var $actual_ = $actual.find('h2');// redefine the target of next actions
$actual_.addClass('event__change');
$actual_.append('<span class="event__arrow" aria-hidden="true">&#9660;</span>');

$actual_.append(function () {
  var self = $(this);
  var list = '<ul class="dropdown hidden">';

  $('.event').each(function (index) {
    if ($(this).find('h2')[0] != self[0]) {
      list += "<li data-index='" + index + "'>" + $(this).find('h2').text() + '</li>';
    }
  });
  return list;
});

$actual_.click(function () {
  if ($(this).attr("data-expanded") == true) {
    $(this).find("ul").toggleClass('hidden');
    $(this).attr("data-expanded", false);
  } else {
    $(this).find("ul").toggleClass('hidden');
    $(this).attr("data-expanded", true);
  }
});

Upvotes: 0

Quentin
Quentin

Reputation: 944544

In the first example you are chaining off the results of find("h2").

In the second you are working directly on $actual.

These are different collections of elements.

Upvotes: 1

Related Questions