Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

span onclick does not work jquery

I have a treeview structure created with css and jquery. To expand a node I want the user to click on a <span> within the <li> (it's an image) and not on the node itself.

So here is my HTML part :

<div class="tree">      
<ul>
<li class="parent active"><span class="expand"></span><a>Level 1</a>
    <ul>
        <li><span class="expand"></span><a>Level 2</a></li>
        <li><span class="expand"></span><a>Level 2</a></li>
        <li><span class="expand"></span><a>Level 2</a></li>
        <li><span class="expand"></span><a>Level 2</a></li>
    </ul>
</li>
<li class="parent active"><span class="expand"></span><a>Level 1</a>
    <ul>
        <li class="parent active"><span class="expand"></span><a>Level 2</a>
          <ul>
             <li class="parent active"><span class="expand"></span><a>Level 3</a>
                <ul>
                   <li><a>Level 4</a></li>
                </ul>
          </ul>
        </li>
        <li><span class="expand"></span><a>Level 2</a></li>
    </ul>
</li>
</ul>
</div>

Here's the JS part for the clikc event on span (but it doesn't work) :

$( '.tree li.parent > span.expand' ).click( function( ) {
    $( this ).parent().toggleClass( 'active' );
    $( this ).parent().children( 'ul' ).slideToggle( 'fast' );
});

However, the following code works but by clicking on the <a> within the <li> :

 $( '.tree li.parent > a' ).click( function( ) {
    $( this ).parent().toggleClass( 'active' );
    $( this ).parent().children( 'ul' ).slideToggle( 'fast' );
 });

I need to expand the nodes by clicking on the span because when clicking on the node I need to redirect to another page to display its details.

Please see this jsfiddle that a created for this question.

So why the click event on span does not work ?

like image 645
blackbishop Avatar asked Mar 31 '26 04:03

blackbishop


1 Answers

The issue is with css. Tag a is overlapping your span. Replace padding with margin and everything will start working.

Upd.: Actually - remove display:block from your rules for a tag fiddle: http://jsfiddle.net/8ucy1gjb/2/

like image 133
Sergey Kochetov Avatar answered Apr 02 '26 19:04

Sergey Kochetov