Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery.Next() with not selector not working as expected

Tags:

jquery

next

I am trying to setup a rotating panel, however I have three states: active, inactive, disabled.

I only want to rotate between active and inactive panels and skip over disabled panels. If there is no more inactive panels rotate back to the first panel.

However with the code below you click the button it will select panel1, then panel 2, and back to panel 1, not selecting panel5.. If I remove the not selector from bold part below it works as expected. I think it's my understanding (or lack thereof) of the next operator. Any thoughts?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>  
<script type="text/javascript">
    $(function () {
        $("#rotate").click(function () {
            var ActivePanel = $('.active');                 //Get the current active panel 
            var NextPanel = $('.active').next('.inactive:not(.disabled)'); //Get the next panel to be active. 
            if (NextPanel.length == 0) NextPanel = $("#panel1"); //check for null next. if so, rotate back to the first panel

            console.log("Active Panel: ", ActivePanel);
            console.log("Next Panel: ", NextPanel);

            $(ActivePanel).removeClass("active").addClass("inactive");
            $(NextPanel).removeClass("inactive").addClass("active"); 
        });
    });    
    </script>
</head>
<body>
    <button id="rotate">Rotate Active Panel</button>
    <div id="panel1" class="active"><p>Some Content</p></div>
<div id="panel2" class="inactive"></div>
<div id="panel3" class="inactive disabled"></div>
<div id="panel4" class="inactive disabled"></div>
<div id="panel5" class="inactive"></div>
</body>
</html>
like image 287
grausamer_1 Avatar asked Dec 02 '11 16:12

grausamer_1


1 Answers

The next method only returns the immediate sibling if it matches the selector. Use the nextAll method.

Try the following:

$("#rotate").click(function() {
  var activePanel = $('.active'); //Get the current active panel 
  var nextPanel = activePanel.nextAll('.inactive').not('.disabled').first(); //Get the next panel to be active. 
  if (!nextPanel.length) {
    nextPanel = $("#panel1"); //check for null next. if so, rotate back to the first panel
  }

  console.log("Active Panel: ", activePanel);
  console.log("Next Panel: ", nextPanel);

  $(activePanel).removeClass("active").addClass("inactive");
  $(nextPanel).removeClass("inactive").addClass("active");
});

See here for jsFiddle.

like image 96
Rich O'Kelly Avatar answered Sep 23 '22 02:09

Rich O'Kelly