Adam Griffiths
Adam Griffiths

Reputation: 792

jQuery get index of clicked element using the $.on event handler

I've seen ways of getting the index of an element clicked on by using the following code:

$('.element').mouseup(function() {
  var index = $(this).index();
});

However due to the way in which my elements are dynamically generated I have to attach my event handler as so:

$(document).on("mouseup", ".element", function(){
    //Do things 
});

Since $(this) will simply return the document, how can I find the index of the element that the event was triggered on?

Upvotes: 0

Views: 2966

Answers (3)

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

<body>
    <ul class="element">
        <li >one</li>
        <li >two</li>
        <li >three</li>
        <li >four</li>
        <li >five</li>
        <li >six</li>
    </ul>
    <script>
        $(document).on("mouseup", ".element", function (e) {
            //Do things 
            //var index = $(this).index();
            console.log($(e.target).index());
        });
    </script>
</body>

For such html, all you need to do is to include event object in the call back. As shown above, it prints the indices on the console window.

Upvotes: 0

Adam Griffiths
Adam Griffiths

Reputation: 792

I'm actually mistaken $(this) called within the scope of ```$(document).on("mouseup", ".element", function(){...}); does actually return the element that triggers this event.

This means my question is pointless, but I'll leave it up for historical purposes if anyone else has the same mistaken question.

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22395

One way is to grab the parent, select the children via:

let index = $(this).parent().children();

Then, use this to grab the index:

index.index(this);

So to wrap it all together, though I don't know why the index is relevant here..

$(document).on("mouseup", ".element", function(){
    let index = $(this).parent().children();
    index = index.index(this);
});

Here's a runnable version for you

One way is to grab the parent, select the children via:

let index = $(this).parent().children();

Then, use this to grab the index:

index.index(this);

So to wrap it all together, though I don't know why the index is relevant here..

$(document).on("mouseup", ".element", function(){
    let index = $(this).parent().children();
    index = index.index(this);
    console.log(index)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="element">test 0</div>
<div class="element">test 1</div>
<div class="element">test 2</div>
<div class="element">test 3</div>
<div class="element">test 4</div>
<div class="element">test 5</div>

Upvotes: 1

Related Questions