Reputation: 1121
Good day.
I have code html:
<span class="empty-star level" style="cursor:pointer" id="1"></span>
<span class="empty-star level" style="cursor:pointer" id="2"></span>
<span class="empty-star level" style="cursor:pointer" id="3"></span>
<span class="empty-star level" style="cursor:pointer" id="4"></span>
<span class="empty-star level" style="cursor:pointer" id="5"></span>
I would like that when i click on element with class level
all elements before him, change class with empty-class
to good-class
and all elements after him change class with good-class
to empty-class
.
Tell me please how make this?
Upvotes: 1
Views: 555
Reputation: 3252
$('.level').on('click', function() {
$(this).prevAll('.empty-class').removeClass('empty-class').
addClass('good-class');
$(this).nextAll('.good-class').removeClass('good-class').
addClass('empty-class');
});
Upvotes: 2
Reputation: 412
$(".level").click(function()
{
$(this).prevAll().removeClass("empty-class").addClass("good-class");
$(this).nextAll().removeClass("good-class").addClass("empty-class");
});
Upvotes: 0
Reputation: 7078
You can use the .prev()
and .next()
jQuery functions!
And you can use .addClass()
and .removeClass()
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/
//Edit:
If you want to asign classes to more then one prev or next element you can use .prevAll()
/ .nextAll()
or .prevUntil()
/ .nextUntil()
http://api.jquery.com/prevAll/
http://api.jquery.com/nextAll/
http://api.jquery.com/prevUntil/
http://api.jquery.com/nextUntil/
Upvotes: 0
Reputation: 3281
You can try this:
$(".level").click(function() {
var thisId = $(this).attr("id");
$.each($(".level"), function(index) {
if(this.id < thisId) {
$(this).removeClass("empty-class");
$(this).addClass("good-class");
}
else if(this.id > thisId) {
$(this).removeClass("good-class");
$(this).addClass("empty-class");
}
});
});
Upvotes: 0
Reputation: 173562
You can use .prevAll()
and nextAll()
for this purpose:
$('.level').on('click', function() {
$(this)
.prevAll('.empty-class')
.toggleClass('empty-class good-class') // remove empty, add good
.end()
.nextAll('.good-class')
.toggleClass('good-class empty-class'); // remove good, add empty
});
Upvotes: 4