I'm working on a way to turn a image, X amount of directions, on a left & right button click. Directions are controlled by numbers and some images got more directions, then others.Those directions are in a array, like this: 0, 2, 4, 6, 8. Always jumping 2.
Those numbers are picked up by the API, so i just need to add them to the url like this, and udpdate the <img> tag.
api.domain.com/image.png?dir=0
Atm. I assume that all images starts at 0, find the last digit and just plus/substract 2 on left/right click. But the problem is that not all images starts at 0 and not all images follow the rule of jumping 2. Meaning it will go like this: 0, 6, 8.
I would love to just shuffle though the array on left/right buttons, but i don't know how. Anyone who maybe could help me?
Script
var prev = $('#left');
var next = $('#right');
var image = $('#img');
var directions = '0, 2, 4, 6';
var max = directions[directions.length - 1];
// Turn Left
prev.click(function(){
// Get current Direction
var curDir = image.attr('data-direction');
if(curDir >= 2){
// Make new direction
var newDir = parseInt(curDir) - parseInt(2);
// Set new data-direcion
image.attr('data-direction', newDir);
// Find current image direction
var url = image.attr('src');
var fix = url.substring(url.lastIndexOf('=') + 1);
// Set new image direction
image.attr('src', url.slice(0,-1) + newDir);
}
});
// Turn Right
next.click(function(){
// Get current Direction
var curDir = image.attr('data-direction');
if(curDir <= max - 2){
// Make new direction
var newDir = parseInt(curDir) + parseInt(2);
// Set new data-direcion
image.attr('data-direction', newDir);
// Find current image direction
var url = image.attr('src');
var fix = url.substring(url.lastIndexOf('=') + 1);
// Set new image direction
image.attr('src', url.slice(0,-1) + newDir);
}
});
HTML
<img id="img" data-direction="0" src="api.domain.com/image.png?dir=0">
<button id="left">Left</button>
<button id="right">Right</button>
minimal example