Search code examples
jqueryarraysloopsclickcomparison-operators

jQuery click inside loop


Trying to achieve with extractAsset(); the following:

  • When clicking div.clickable, if lists[i].id is >= than it's previous lists[i].id (tried .prev() but nothing) then toggleClass("highlight");

Ideally if this worked, only list2(id:8) would toggle yellow background.

What I've been trying is commented on the fiddle.

see JSFiddle

A working fiddle example is appreciated, thank you.


Solution

  • You need to compare the values of the .data element html. To get the previous one, use the jquery prev function on the target div.

    function extractAsset() {
      for (var i = 0; i < lists.length; i++) {
        $(".clickable" + [i]).click(function(){         
          if($(this).find('.data').html() >= $(this).prev().find('.data').html())
            $(this).toggleClass("highlight");
        })
      }
    }
    

    jsfiddle