In Jquery I’m attempting to increment the attribute value of 5 list items such that their position in the list changes on the click of a forward and backward button, but does not exceed the 5 possible positions, or become a negative integer.
What I was trying to write was a function that checks for values < 5, and increments them by 1, and then decrements 5 by 4 to make it a position of 1, when #forward is clicked. Similarly, for clicking #backward, a function would check for values > 1 and decrement them by 1, and then increment 1 by 4 to make it a position of 5, essentially allowing for a control to loop the 5 list items through the 5 positions.
I’m using the following script:
//forward
$("#forward").click(function() {
if ( $('li').attr('position') < 5 ) {
$('li').attr('position', function(_, v) {
return Number(v) + 1;
});
} else if ( $('li').attr('position') == 5 ) {
$('li').attr('position', function(_, v) {
return Number(v) - 4;
});
}
});
//backward
$("#backward").click(function() {
if ( $('li').attr('position') > 1 ) {
$('li').attr('position', function(_, v) {
return Number(v) - 1;
});
} else if ( $('li').attr('position') == 1 ) {
$('li').attr('position', function(_, v) {
return Number(v) + 4;
});
}
});
2
Answers
You need to swap the position of the
if
statement and theattr
function around, like this:After swappering the if and attr, then we will change
$('li').attr('position') < 5
to$(this).attr('position') < 5
Demo
If you only want to change the position attribute please try this.
https://jsfiddle.net/b62uzqkf/