Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass $(this) to selector

I have a jquery click handler which toggles one of list elements:

$(document).on('click', 'ul li', function() {
    $(this).toggleClass('expanded');
});

With it I can change element I clicked expanding and collapsing it.

But what if I want only one element to be expanded and previously expanded element to close when I click to another one?

I want to do this passing both $(this) (clicked li) and li.expanded to jQuery selector for toggleClass('expanded').

Something like (but this does not work):

$(document).on('click', 'ul li', function() {
    $(this, 'ul li.expanded').toggleClass('expanded');
});

Thanks in advance!

UPD: I need this function to work even if no elements was expanded before (on page start) and to be able to collapse previously expanded element when i click on it.

it does not work correctly if use (does not expand first item):

$('li.expanded', this).toggleClass('expanded');

but works fine with:

$('li.expanded').toggleClass('expanded');
$(this).toggleClass('expanded');
like image 832
s.webbandit Avatar asked Jun 26 '15 08:06

s.webbandit


3 Answers

Just changed the position of arguments passed to selector. The jquery selector accepts second parameter context. where you can pass the current context this:

$('ul li.expanded',this).toggleClass('expanded');

which would be equivalent to:

$(this).find('ul li.expanded').toggleClass('expanded');

Full Snippet:

$(document).on('click', 'ul li', function() {
  $('ul li.expanded').not($(this).find('ul li.expanded')).removeClass('expanded'); 
  $('ul li.expanded',this).toggleClass('expanded');
});
like image 191
Milind Anantwar Avatar answered Nov 12 '22 09:11

Milind Anantwar


ToggleClass not working in your context. its collapse all li's Use addClass and removeClass instead of

$(document).on('click', 'ul li', function() {
    $('ul li.expanded').removeClass('expanded'); // remove class expanded
    $(this).addClass('expanded'); // add class current li
});
like image 21
Sudharsan S Avatar answered Nov 12 '22 09:11

Sudharsan S


You can remove class 'expanded' from all li elements and add it to the clicked one:

This code

$('ul li.expanded',this).toggleClass('expanded');

does not work in this case

WORKING DEMO

$(document).on('click', 'ul li', function() {
  $('ul li').removeClass('expanded');
  $(this).addClass('expanded');
});
li.expanded { color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li class="expanded">test</li>
  <li>test2</li>
  <li>test3</li>
  <li>test4</li>
</ul>
like image 1
kapantzak Avatar answered Nov 12 '22 09:11

kapantzak