Recently I needed to find out the element index of a List element when clicked.
I managed to come up with the code that enabled me to do that using jQuery.
First you need to set up your HTML code with an id of ‘bourne’. You don’t have to use bourne, use whatever you like.
<ul id="bourne"> <li>Option 1</li> <li>Option 2</li> <li>Option 3</li> <li>Option 4</li> <li>Option 5</li> </ul>
You can see above that I have created an unordered list with an id of ‘bourne’, with 5 list elements inside it.
Now we need to move over to the javascript. I will assume that you have managed to set up a script element in your page header, or link to an external jscript file.
Whatever you use, insert the following code to trigger the onDomReady, so that this is run once the page is ready.
$(function(){ // our code will go here inside the domready });
Now that we have set up our entry point, we now need to the trigger for the onclick event. We want this to be triggered every time a list element is triggered.
We set up the click event, telling it that we want it to attach it to the list elements id bourne.
$(function(){ // onclick event $('#bourne li').click(function() { // clicked }); });
Now that we have built the click event, you can reference the element by using ‘this’.
// onclick event $('#bourne li').click(function() { // clicked alert('Element ' + $(this).html() + ' was clicked'); });
The above would display an alert box displaying the text of the clicked element.
But what if we want to find out the index of this element, so that we could work out it’s position if it was part of a menu or tab option?
To do this, we need to get every list element an place it in a variable.
$('#bourne li').click(function() { elementlist = $(this).parent; alert('Element ' + elementlist.index(this) + ' was clicked'); });
The new code now puts the clicked elements parent into a variable. The second line displays an alert detailing which element of the array was clicked. It does this by find the clicked elements index of the parent.
I know this is a script I will be using again soon, so hopefully somebody else might find this useful as well.
1 Comment
Thnk you !this works for me