shefali
shefali

Reputation: 85

Getting extra 'li' in ul

Every time user click on li, new ul should be added to that li, basically want to create binary tree using ul

$('#tree').on('click','li', function(){

		$(this).append('<ul style="display:block;"><li>list1</li><li>list2</li></ul>');	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="tree">
		  	<li>
				sdfsdf	
			</li>
		</ul>

list is getting added twice when list1 is clicked

Upvotes: 1

Views: 101

Answers (2)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You need to use event.stopPropagation(); so that the parent event is not propagated. Since, click on li inside a li will trigger click event twice, you need to stop the click event of the parent and only trigger the one which you have clicked.

$('#tree').on('click','li', function(event){
 event.stopPropagation();
  var ulExist = $(this).find('ul');
  if(ulExist.length === 0){
    $(this).append('<ul style="display:block;"><li>list1</li><li>list2</li></ul>'); 
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tree">
  <li>
      sdfsdf  
  </li>
</ul>

Upvotes: 2

Ahmad Ibrahim
Ahmad Ibrahim

Reputation: 1925

You have to stop the propagation of the click event, i.e.

$('#tree').on('click', 'li', function(e) {
    e.stopPropagation();
    $(this).append('<ul style="display:block;"><li>list1</li><li>list2</li></ul>');     
});

Working fiddle

Upvotes: 0

Related Questions