Use a combination of on()
(for binding minimum event handlers and to handle the dynamic updating that you mentioned) and the index()
method to determine the element's index relative to its parent.
$("ol").on("click", "li", function() {
yourFunction($(this).index());
});
jsFiddle.
If you didn't have jQuery...
var ol = document.querySelector("ol");
var olLi = ol.querySelectorAll("li");
var handleClick = function(e) {
var target = e.target;
var index = 0;
while (target = target.previousElementSibling) {
index++;
}
yourFunction(index);
};
ol.addEventListener("click", handleClick);
jsFiddle.
If you had to support old browsers without jQuery...
var ol = document.getElementsByTagName("ol")[0];
var olLi = ol.getElementsByTagName("li");
var handleClick = function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
var index = 0;
while (target = target.previousSibling) {
(target.nodeType == 1) && (index++);
}
yourFunction(index);
};
ol.addEventListener && ol.addEventListener("click", handleClick);
ol.attachEvent && ol.attachEvent("onclick", handleClick);
jsFiddle.