Search code examples
jqueryindexinghoverhtml-listsvisible

get index of current hovered li respect to visible li only - jquery hover


There are 5 li element and one of them say third li is hidden.Is there a way to apply filter before getting index so that fourth element's index should show 2 instead of 3.

<html>
    <head>
        <title>test</title>
        <script type='text/javascript' src='js/jquery-1.4.2.js'></script>
        <script>
            $(window).load(function() {
                    jQuery('.addchar').live('hover', function(event) {
                        $("#result").html("Index is:" +$(this).index() );
                    });
                });
            });
        </script>
    </head>
    <body>
        <div id="content">
            <div>
                <ul>
                    <li class="addchar">one </li>
                    <li class="addchar">two </li>
                    <li class="addchar" style="display:none"> three</li>
                    <li class="addchar">four </li>
                    <li class="addchar">five </li>
                </ul>
            </div>
            <div id="result"></div>
        </div>
    </body>
</html>

Solution

  • How about using the visible selector:

    $('.addchar:visible').live( ...
    

    EDIT:

    Too bad, you could try an alternative approach if that is an option for you:

    $(function() {
        $('.addchar:visible').each(function(index) {
            $(this).hover(function() {
                $("#result").html("Index is: " + index);
            });
        });
    });