0

I want to change the css of an element by jQuery index.

 $(".switcher span").click(function() {
   var galleryIndex = $(this).index();
   $('.wrapper .gallery').eq(galleryIndex).css("background", "red");
 });
<div class="switcher">
  <span>Switch 0</span>
  <span>Switch 1</span>
</div>

<div class="wrapper">
  <div class="gallery">GALLERY 0</div>
  <div class="gallery">GALLERY 1</div>
</div>

jQuery gets the index of the .switcher span fine but it seems that the index pf the gallery is not loading. It does not work so far.

2
  • 1
    Working fine for me... Do share executable snippet.... Commented Nov 24, 2016 at 12:11
  • working fine jsfiddle.net/nu4ngh31 Commented Nov 24, 2016 at 12:12

1 Answer 1

1

It seems like everything works great in your code.

If you want to reset the background-color on every click you can set it to '':

$(".switcher span").click(function(){
      var galleryIndex = $(this).index();
      $('.wrapper .gallery').css('background', '').eq(galleryIndex).css("background", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="switcher">
    <span>Switch 0</span>
    <span>Switch 1</span>
</div>

<div class="wrapper">
    <div class="gallery">GALLERY 0</div>
    <div class="gallery">GALLERY 1</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.