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?
You can use the is()
[docs] method to test:
if( $(".thumb-selected").is( ':first-child' ) ) {
// whatever
} else if( $(".thumb-selected").is( ':last-child' ) ) {
// whatever
}
You can do this in native JavaScript like so:
var thumbSelected = document.querySelector('.thumb-selected');
var parent = thumbSelected.parentNode;
if (thumbSelected == parent.firstElementChild) {
// thumbSelected is the first child
} else if (thumbSelected == parent.lastElementChild) {
// thumbSelected is the last child
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With