Skip to content

Instantly share code, notes, and snippets.

@stubbornella
Created October 14, 2013 00:21
Show Gist options
  • Select an option

  • Save stubbornella/6968898 to your computer and use it in GitHub Desktop.

Select an option

Save stubbornella/6968898 to your computer and use it in GitHub Desktop.

Revisions

  1. stubbornella created this gist Oct 14, 2013.
    18 changes: 18 additions & 0 deletions jsbin.EGusina.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="description" content="[add your bin description]" />
    <meta charset=utf-8 />
    <title>JS Bin</title>

    </head>
    <body>
    <h1>Using onclick</h1>
    <div class="text">text to be replaced</div>
    <ul>
    <li>foo - clicks here should not alert</li>
    <li>bar</li>
    <li>baz</li>
    </ul>
    </body>
    </html>
    22 changes: 22 additions & 0 deletions jsbin.EGusina.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    /* tests:
    *
    * 1. click on children of .text should alert their index - PASS
    * 2. click on other elements should not - PASS
    * 3. if two nodes have the same content, a click on the latter should not return the index of the former - PASS
    */

    // how to make it execute after document is loaded?
    var content = "<div>a</div><div>e</div><div>t</div><div>7</div><div>1</div><div>a</div>",
    textNode = document.getElementsByClassName("text")[0]; // what if the server returned json, or content was an array.

    textNode.innerHTML = content;

    textNode.onclick = findIndex;
    if (textNodes.captureEvents) textNodes.captureEvents(Event.CLICK);



    function findIndex(e) { // does js have an api for the index?
    if (!e) var e = window.event;
    alert(Array.prototype.indexOf.call( e.target.parentNode.children, e.target ));
    }