pourmesomecode
pourmesomecode

Reputation: 4358

Navigate on keypress over array of divs javascript

  <div id="wrapper">
    <img class="seperator selected" src="imgs/character_1.png" tabindex="0" />
    <img class="seperator" src="imgs/character_2.png" tabindex="0" />
    <br />
    <img class="seperator" src="imgs/character_3.png" tabindex="0" />
    <img class="seperator" src="imgs/character_4.png" tabindex="0" />
    <br />
    <img class="seperator" src="imgs/character_5.png" tabindex="0" />
    <img class="seperator" src="imgs/character_6.png" tabindex="0" />
  </div>

So i'm listening to keypress and if it's keyCode === 32 which is the space bar, move the selected class one across. So I can do thisIndex++ and increment up by +1 everytime space is pressed but how do I target that element add a class and remove the previous one? I get addClass is not a function error.

$("body").on("keydown", function(e) {

  var thisIndex = $(".selected").index();
  var newIndex = null;

  if (e.keyCode === 32) {
    $(".seperator").removeClass("selected");

    thisIndex++;
    $('.seperator').get(thisIndex).addClass("selected");
  }

});

Upvotes: 1

Views: 82

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

The get() method returns DOM object so you can't use jQuery addClass() method on it, instead use eq() method to get jQuery object based on index.

$('.seperator').eq(thisIndex).addClass("selected");

You can combine all the lines inside the if into one by chaining the methods.

$(".seperator").removeClass("selected").eq(thisIndex + 1).addClass("selected");

UPDATE : You need to get index within the img tag collection(with class seperator) otherwise index calculated including the br tag.

$("body").on("keydown", function(e) {
  // specify the collection as the argument
  var thisIndex = $(".selected").index('.seperator');

  if (e.keyCode === 32)
    $(".seperator")
    .removeClass("selected")
    .eq(thisIndex + 1)
    .addClass("selected");

});
.selected {
  border: 1px solid red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <img class="seperator selected" src="imgs/character_1.png" tabindex="0" />
  <img class="seperator" src="imgs/character_2.png" tabindex="0" />
  <br />
  <img class="seperator" src="imgs/character_3.png" tabindex="0" />
  <img class="seperator" src="imgs/character_4.png" tabindex="0" />
  <br />
  <img class="seperator" src="imgs/character_5.png" tabindex="0" />
  <img class="seperator" src="imgs/character_6.png" tabindex="0" />
</div>

Upvotes: 3

Related Questions