Reputation: 163
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.
Upvotes: 0
Views: 737
Reputation: 62566
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>
Upvotes: 1