[Solved] Javascript: Issue when using .click method


  1. You don’t need inline event handlers
  2. You can use event delegation
  3. Use index to get the clicked element index in ul

HTML

<div class="grid_12">
    <ul id="categories">
        <li class="filter">Categories:</li>
        <li id="ny"><a href="#newYork"> New York</a>
        </li>
        <li id="sc"><a href="#spanishCities">Spanish Cities</a>
        </li>
        <li id="gv"><a href="#aGlasgowViewpoint">A Glasgow Viewpoint</a>
        </li>
        <li id="sch"><a href="#someChurches">Some Churches</a>
        </li>
        <li id="bh"><a href="#barcelonaHighlights">Barcelona Highlights</a>
        </li>
        <li id="mp"><a href="#martin's Pictures">Martin’s Pictures</a>
        </li>
    </ul>
</div>

Javascript

var id;
$('#categories').on('click', 'li>a', function () {
    id = $(this).closest('li').index();
});

Demo: http://jsfiddle.net/tusharj/q9xbqck0/3/

2

solved Javascript: Issue when using .click method