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>
try using the next siblings ~
selector followed by a nested .class
, :not(.class)
and :first
selector
$("#rotate").click(function() {
var ActivePanel = $('.active');
var NextPanel = $(".active ~ .inactive:not(.disabled):first");
if (NextPanel.length == 0) NextPanel = $("#panel1");
$(ActivePanel).removeClass("active").addClass("inactive");
$(NextPanel).removeClass("inactive").addClass("active");
});
Working Example: http://jsfiddle.net/hunter/vfVBB/
Next Siblings Selector (“prev ~ siblings”)
Description: Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.