Search code examples
javascriptjqueryhtml

How to determine if element is last or first child of parent in javascript/jquery?


I have the following code, emulating a click on the left or right key down events. This is used as part of a gallery slideshow:

$(document).keydown(function (e) {
                    if(e.keyCode == 37) { // left
                        $(".thumb-selected").prev().trigger('click');
                    }
                    else if(e.keyCode == 39) { // right
                        $("thumb-selected").next().trigger('click');
                    }
                });

Essentially it picks the next or previous sibling (depending on the key pressed) and call the click event that will in turn display the appropriate image in the gallery. These images are all stored in a unordered list.

Where I am stumped is that when the first or last image is selected and the left or right button is clicked (respectively), I want it to get the next picture at the opposite end of the list of images. For example, if the first image is selected and the left arrow is pressed; given that there is no previous image (or li element), it will get the last image in the list. This way the keys never lose functionality.

Is there a function in jquery that will either check if the present element is the first or last child of its parent, or return its index relative to its parent so I can compare its index to the size() (child count) of his parent element?


Solution

  •     var length = $('#images_container li').length;
        if(e.keyCode == 37) { // left
             if($('.thumb-selected').index() > 0)
                  $(".thumb-selected").prev().trigger('click');
             else
                  $('.thumb-container').eq(length-1).trigger('click');
         }
    
         else if(e.keyCode == 39) { // right
             if($('.thumb-selected').index() < length-1)
                 $("thumb-selected").next().trigger('click');
              else
                  $('.thumb-container').eq(0).trigger('click');
         }
    

    .thumb-container is the parent element of the all the thumbs. At least what I got from your code.

    HTML

        <ul class="thumb-container">
            <li>thumb</li>
            <li>thumb</li>
                .
                .
                .
        </ul>