Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try this (also read : <a href="https://stackoverflow.com/q/1687296/1636522">What is DOM Event delegation?</a>) :</p> <pre><code>carouselThumbsContainer.onclick = function (e) { var tgt = e.target, i = 0, items; if (tgt === this) return; items = children(this); while (tgt.parentNode !== this) tgt = tgt.parentNode; while (items[i] !== tgt) i++; alert(i); }; function children(el) { var i = 0, children = [], child; while (child = el.childNodes[i++]) { if (child.nodeType === 1) children.push(child); } return children; } </code></pre> <p>Here is a demo : <a href="http://jsfiddle.net/wared/U7Xpc/" rel="nofollow noreferrer">http://jsfiddle.net/wared/U7Xpc/</a>.</p> <hr> <h2>The click handler line by line</h2> <h3>The actors</h3> <pre><code>var tgt = e.target, i = 0, items; // and `this` </code></pre> <p><code>this</code> is the UL itself. <code>e.target</code> is the DOM element that initiated the event. It can be any descendant of the UL or the UL itself (in this case <code>e.target</code> = <code>this</code>). <code>i</code> holds the index of the clicked item. <code>items</code> stands for LIs that are direct children of the UL.</p> <h3>The story</h3> <p>Exit the function if the target is the UL itself:</p> <pre><code>if (tgt === this) return; </code></pre> <p>Get LIs that are direct children of the UL:</p> <pre><code>items = children(this); </code></pre> <p>Bubble up through target's ancestors until reaching the uppermost LI:</p> <pre><code>while (tgt.parentNode !== this) tgt = tgt.parentNode; </code></pre> <p>Increment the index until the target matches one of the LIs:</p> <pre><code>while (items[i] !== tgt) i++; </code></pre> <p>Alert the index:</p> <pre><code>alert(i); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload