views:

189

answers:

3

Hi All,

I am stuck with a problem here, please help. What my requirement is to get the index value of the div clicked. Have 2 lists, and i need to call a function doSomething(); only when the user clicks the first div set. Is there anyway that i can achieve it.

The scripts and HTML is as follows

$(document).ready(function() {
 $(".list-wrapper li").click(function() {
    var index = $(".list-wrapper div").index(this);
    alert(index);
    });
});

<div class="list-wrapper">
<ul>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ul>
</div>

<div class="list-wrapper">
<ul>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ul>
</div>

Please help...

+2  A: 

jQuery has powerful selectors, so usually you don't need to check the index after the event. For example:

For the first div on your page:

$(".list-wrapper:first").click(doSomething);

For the first <li>s in every list:

$(".list-wrapper li:first-child").click(doSomething);

If you still want to find the index, you need to search for the parent div of the clicked li. Also, the selector .list-wrapper div is empty - you don't have any divs in list-wrapper. This will work:

var parent = $(this).closest('div')
var index = $(".list-wrapper").index(parent);
Kobi
+1  A: 

if it only needs to be on the first one use the :first selector

http://api.jquery.com/first-selector/

$("div.list-wrapper:first").find("li").click(function() {...
Josh
A: 

There are many ways to do this:

$('div.list-wrapper').first().click(function() { doSomething(); });

and

$("div.list-wrapper:first").click(function() { doSomething(); });

and

$('div.list-wrapper').eq(0).click(function() { doSomething(); });

are the first ones that come to mind. Pro-tip, include the element type before the class for speed (div.blah faster than .blah)

Or to just get the index:

var index = $('div.list-wrapper').index(this);

replace 'this' with the parent for specificity

davidosomething