JQuery test if div is first child?

How to run a test if the image is the first or last of a group of images?

I am trying to make the previous and next buttons animated or exiting depending on whether I am at the end of a series of images with the following code:

var $current = jQuery("img .active");
var $next = $current.next();

if ($next != jQuery("img:first-child")
{
 // show next item and the previous button
 // seems to work?

} else if ($next == jQuery("img:last-child")
{
 // hide the next button since we're at the end
 // doesn't seem to work??
}
+3
source share
2 answers

Do you want to check img index:

var $current = jQuery("#img .active"),
    index = $current.index();

if (index === 0) {
    // This is the first
} else if (index === jQuery("#img").children().length - 1) {
    // This is the last
}
+8
source

Assuming .each()there won't be much performance when using , I would do something like this:

jQuery('#img').children().each(function(i,obj){
  // some code to show buttons
  if (i <= 0) { // hide prev }
  if (i >= $('#img').children().length - 1) { // hide next }
});

Then hide everything $('#img').children()except the active, or else you want it to function.

0
source

Source: https://habr.com/ru/post/1780596/


All Articles