3
I’m trying to create/adapt a tree list
, however I am not being able to expand my list by clicking on a label.
List:
<div id="listContainer">
<ul id="expList">
<li style="">
<label style="margin-top: 50px;border-style: solid; border-width: 1px; border-color: #7C7C7C; background-color:#E0E0E0">
Item A
</label>
<ul>
<li>
itens lista A
</li>
</ul>
</li>
</ul>
The error starts from my js function to expand the list:
function prepareList() {
$('#expList').find('li:has(ul)')
.click(function (event) {
if (this == event.target) {
$(this).toggleClass('expanded');
$(this).children('ul').toggle('medium');
}
return false;
})
.addClass('collapsed')
.children('ul').hide();
...
...
}
I’ve tried to find the label on expList
just to test and I couldn’t resolve the issue:
$('#expList').find('label')
.click(function (event) {
...
...
}
Follow the full code: jsfiddle
PS. - If you click outside the list, it expands
What’s the idea of this line?
if (this == event.target) {
What do you want with her? (Just to understand better what you’re looking for)– Sergio
@Sergio, the problem is of this line (if you take it works as I want). I will delete the question, because the match will not help anyone in the future. Thanks for the help ;)
– CesarMiguel
Do not delete. The problem on this line is that the
this
and theevent.target
are not always the same element. And this causes confusion to many people, hence the question is useful...– Sergio
Oh I’m already understanding my mistake. My departure
event.target
had the value something like "clicked on li", and minethis
refers to the element. That’s what you’re trying to say?– CesarMiguel
In what scenario do you want that
if
give false? IE, how is it, this is the<li>
and theevent.target
is the descending element ofthis
that was clicked, for example the<label>
. Unless the<li>
have for example a padding will be difficult to have that if to give true.– Sergio
The match by clicking outside the
li
was going to be false. But as thelabel
is inside theli
I didn’t understand the mistake– CesarMiguel
To prevent the click on the children from triggering the parent’s click event, use Event.stopPropagation();
– Jader A. Wagner
In this case this line is not necessary because the
$('#expList').find('li:has(ul)')
selects onlyli
's. And while you’re at it$('#expList li:has(ul)')
only.– Sergio
Yeah, I figured out why it didn’t. I thought I was gonna select the kids from
li
– CesarMiguel