Can't Toggle Through Images With JQuery Function - javascript

I'm trying to write a function that upon each button click, it changes the shape of the triangle.
I'm a novice, and I could probably do this quicker with toggle() but I want to get better at writing functions because it's holding me back. Any help would be appreciated. You don't have to give me the answer, but a point in the right direction would be so appreciated! Thank you.
I have the first two shapes but I don't know how to bring in the last two.
https://jsfiddle.net/gs0c30vd/2/
$(document).ready(function(){
$("#tri").click(function(){
$('#triangleup').hide();
$('#triangleright').show();
}) ;
});

A very simple and small jQuery script can do it like below - the only requirement for this is that you add the same class to the elements (see HTML beneath):
$(document).ready(function(){
// declare the first element in the range w. respect to the order of the HTML
var firstElement = $(".firstTriangle");
// declare the last element in the range here to reset the "loop" of elements
var lastElement = $(".lastTriangle");
$("#tri").click(function() {
if ($(lastElement).is(":hidden")){
$(".triangle").filter(":visible").hide().next().show();
} else {
$(lastElement).hide();
$(firstElement).show();
};
});
// ------------------------------------------------------------
// The original uni-directional method is above.
// Beneath I have added "support" for a bi-directional method;
// i.e. going either up or down in the HTML
// ------------------------------------------------------------
$("#counterclockwise").click(function() {
if ($(firstElement).is(":hidden")){
$(".triangle").filter(":visible").hide().prev().show();
} else {
$(firstElement).hide();
$(lastElement).show();
};
});
});
You can check it out in this fiddle. The real benefit of this little method is that you dont have to declare every element in the range which you would like to show. If you apply it for a slider with a lot of images it gets tiresome to type in every element (at least in my opinion); and especially if you change some of the elements. To make this method even easier to maintain you could just use some fixed classes which you always hold as the first and last element; such as "firstTriangle" and "lastTriangle" and then adjust the variables accordingly. I've also added this approach to the script and the HTML for future reference and ease-of-use.
However the drawbacks should also be noted:
You must have your elements which u wish to toggle inside a container with no other siblings (such as shown in the HTML). Otherwise it will move on to other elements and showing/hiding these, thereby breaking the function.
There can only be one direction in which you switch between the elements (downwards in the HTML document).
However, with regard to the unidirectional "drawback" you could easily reverse the function and add another button to make up for this. Such an example can be seen here: Change slides/elements in both directions.
This effectively grants you a pretty much fully functional slider.
HTML:
<div class="myContainer">
<div id="triangleup" class="triangle firstTriangle"></div>
<div id="triangleright" style="display: none;" class="triangle"></div>
<div id="triangledown" style="display: none;" class="triangle"></div>
<div id="triangleleft" style="display: none;" class="triangle lastTriangle"></div>
</div>
<button id="tri">Click me to change the direction of the triangle</button>
<!-- Button for changing direction beneath -->
<button id="counterclockwise">Change direction <b>counter-clockwise</b></button>
Interpretation of the function:
If the last element in the range is hidden (we're not through the range yet) then find the visible one (.filter(":visible")) and hide it, and afterwards find its next (next()) sibling and show (show()) this.
However, if the last Element is visible (then you are at the end of the range), manually hide this and show the first element - thereby starting the range over again.
Note: Pardon my lengthy answer (although that might not be a bad thing) but this was also a learning process for me as well - I wasn't even aware that a "slideshow" effectively could be made that easy with jQuery until I found the .filter() parameter in connection with this question.

You can use a Switch statement to track the current position of the triangle from 0..3 like so:
$(document).ready(function() {
var rot = 0
$("#tri").click(function() {
switch (rot) {
case 0:
$('#triangleup').hide();
$('#triangleright').show();
rot += 1;
break;
case 1:
$('#triangleright').hide();
$('#triangledown').show();
rot += 1;
break;
case 2:
$('#triangledown').hide();
$('#triangleleft').show();
rot += 1;
break;
case 3:
$('#triangleleft').hide();
$('#triangleup').show();
rot = 0;
break;
}
});
});

If your html looks like this
<div id="container">
<div class="shape visible"></div>
<div class="shape"></div>
<div class="shape"></div>
<div class="shape"></div>
</div>
And your css class for .shape is display:none and .visible is display:block
Than your js can be
$("#tri").click(function() {
var current = $(".visible");
var options = $("#container");
var index = options.index(current);
$(".visible").removeClass("visible");
If(index<options.length -1){
options[index + 1].addClass("visible");
}else{
options[0].addClass("visible");
}
});
Forgive me for the typeos I did this on my phone.

One way to do it is to store the names of the shapes in an array then have some sort of counter that increases each time you click the button. The modulus/remainder from that counter as compared to the array length will enable you to loop through them.
Code example:
var index = 0
var shapeArr = [
'#triangleup',
'#triangleright',
'#triangledown',
'#triangleleft'
]
var len = shapeArr.length
$(document).ready(function(){
$("#tri").click(function(){
$(shapeArr[index % len]).hide();
$(shapeArr[++index % len]).show();
}) ;
});

$(document).ready(function(){
var count = 0;
$("#tri").click(function(){
if( count == 0)
{
$('#triangleup').hide();
$('#triangleright').show();
count++;
}
else if(count == 1)
{
$('#triangleright').hide();
$('#triangledown').show();
count++;
}
else if(count == 2)
{
$('#triangledown').hide();
$('#triangleleft').show();
count++;
}
else
{
$('#triangleleft').hide();
$('#triangleup').show();
count = 0;
}
}) ;
});
this is not a good way you make upon this

You can use a flag isUp to know the current status and negate it on every click
$(document).ready(function(){
var isUp = true;
$("#tri").click(function(){
if (isUp) {
$('#triangleup').hide();
$('#triangleright').show();
} else {
$('#triangleup').show();
$('#triangleright').hide();
}
isUp = !isUp;
}) ;
});
EDIT:
I have seen you have four triangles. If you want a full rotation, then you might want to do this:
$(document).ready(function(){
var directions = ["up", "right", "down", "left"];
var directionIndex = 0;
$("#tri").click(function(){
$("#triangle" + directions[directionIndex]).hide();
$("#triangle" + directions[directionIndex = ((directionIndex + 1) % directions.length)]).show();
}) ;
});

You could have an alternative solution using just a few lines of CSS and a small addition in your jQuery code. The point is to simply rotate the triangle by using CSS transform attribute.
Example using jQuery
$(document).ready(function() {
var degrees = 0;
$("#tri").click(function() {
degrees = degrees + 90;
$('#triangle').css("transform", "rotate(" + degrees + "deg)");
});
});
#triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="triangle"></div>
<br>
<button id="tri">Click me to change the direction of the triangle</button>
You can also check this out in this updated Fiddle.
Example using only Javascript
var degrees = 0;
var triangle = document.getElementById("triangle");
document.getElementById("tri").addEventListener("click", function() {
degrees = degrees + 90;
var style = triangle.style;
style.transform = "rotate(" + degrees + "deg)";
});
#triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
<div id="triangle"></div>
<br>
<button id="tri">Click me to change the direction of the triangle</button>

Related

HTML full size div containing a draggable table

I'm not sure how to explain what I exactly want (which makes it really hard to google for as well), but I would like to create a table with each cell a specific width and height (let's say 40x40 pixels).
This table will be way larger than the viewport, so it would need some scrolling, but I don't want scrollbars (this part ain't a problem), but a way to drag the table around "behind the viewport".
To make it a bit more complex, I need to be able to center a specific cell and know which cell is centered too (although if I know for example that the table is on left: -520px; I can calculate what the situation is).
Long story short, I'm looking for something that looks and works like maps.google.com, but then with a table and cells instead of a canvas or divs.
What you're trying to achieve is relatively simple. You have a container div element with position: relative; overflow: hidden applied via CSS and the content set to position: absolute. For example:
<div class="wrapper">
<div class="content-grid">
... your grid HTML ...
</div>
</div>
You then need to set up some mouse/touch tracking javascript, you can find plenty of examples around Stack Overflow or Google, which monitors the position of the mouse at mousedown or touchstart events and then tests this repeatedly on an interval to see where the pointer is and update the content-grid top and left position, until mouseup or touchend.
You can make this animation smooth using CSS transition on left and top.
The tricky bit is calculating the position for the centre cell. For this I would recommend calculating a central zone, the size of your grid cells (i.e. 40x40) in the middle of your container element. Then checking if any grid cell is currently more than 1/4 inside that zone, and treating it as the "central" element.
Here is a basic example for position a cell within a grid within a wrapper: https://jsfiddle.net/tawt430e/1/
Hope that helps!
I was a bit disappointed to see the down votes of my question at first. I can imagine that stackoverflow has a lot of issues with new people just trying to get their code written here, but that's not what I asked.
Anyway, with the "you share the problem, you share the solution", mindset, I fixed the code with help of tw_hoff and it all works now. It even saves the coordinates in the local storage so this example HTML keeps you in the same position if you refresh the page. I added the two example images I used as well (store the left one as farm.png, the right one as tile.png, same directory as the html page).
The actual code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game map demo</title>
<style>
body { margin: 0; padding: 0; }
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="map" style="position: absolute; overflow: hidden; width: 100%; height: 100%; background-color: darkgreen;">
<div id="content" style="white-space: nowrap;">
</div>
</div>
<script>
for(i = 0; i < 20; i++) {
for(j = 0; j < 20; j++) {
var tile;
if((i == 4 || i == 5) && (j == 2 || j == 3)) {
tile = 'farm';
} else {
tile = 'tile';
}
$("#content").append('<div style="background: url(\'' + tile + '.png\'); width: 128px; height: 128px; position: absolute; margin-left: ' + (i * 128) + 'px; margin-top: ' + (j * 128) + 'px;"></div>');
}
}
$("body").css("-webkit-user-select","none");
$("body").css("-moz-user-select","none");
$("body").css("-ms-user-select","none");
$("body").css("-o-user-select","none");
$("body").css("user-select","none");
var down = false;
var current_left = 0;
var current_top = 0;
if(localStorage.getItem("current_left") && localStorage.getItem("current_top")) {
current_left = Number(localStorage.getItem("current_left"));
current_top = Number(localStorage.getItem("current_top"));
console.log(current_left);
$("#content").css('marginLeft', (current_left) + 'px');
$("#content").css('marginTop', (current_top) + 'px');
}
$(document).mousedown(function() {
down = true;
}).mouseup(function() {
down = false;
});
var cache_pageX;
var cache_pageY;
$( "#map" ).mousemove(function( event ) {
if(down == true) {
current_left += (-1 * (cache_pageX - event.pageX));
if(current_left > 0)
current_left = 0;
if(current_left < (-2560 + $("#map").width()))
current_left = (-2560 + $("#map").width());
current_top += (-1 * (cache_pageY - event.pageY));
if(current_top > 0)
current_top = 0;
if(current_top < (-2560 + $("#map").height()))
current_top = (-2560 + $("#map").height());
localStorage.setItem("current_left", current_left);
localStorage.setItem("current_top", current_top);
$("#content").css('marginLeft', (current_left) + 'px');
$("#content").css('marginTop', (current_top) + 'px');
}
cache_pageX = event.pageX;
cache_pageY = event.pageY;
});
</script>
</body>
</html>
It still needs some work, and of course a lot of work to be actually used in a game, but this part works and I hope if someone else ever might have the same issue and searches for it on stackoverflow my solutions gives them a push in the right direction :).
Thanks for those that helped!

How to fill progress bar based on number of letters typed?

I am trying to make an input box that has a div on the bottom which will act sort of a progress bar to tell you when you have enough characters typed.
I can't get this animation to work, even though I thought it would be a lot easier when I decided to try this project.
Please let me know what is wrong with my code. Thanks!
<div id='cntnr'>
<div id='inptDiv'>
<input id='inpt1'>
<div id='prgInd'></div>
</div>
</div>
var main = function() {
var inptAmnt = document.getElementById('inpt1').value;
if(inptAmnt.length === 1) {
$('#prgInd').css('width', 25);
}
}
$(document).ready(main);
I also tried this code first but it didn't work either:
var main = function() {
var inptAmnt = document.getElementById('inpt1').value;
if(inptAmnt.length === 1) {
$('#prgInd').animate({
width:25
},200 )
}
}
$(document).ready(main);
JSFiddle: https://jsfiddle.net/qcsb53ha/
You can use jQuery to listen to the change, keyup and paste events of your text input.
Then, work out a percentage, based on your desired input length; and use this percentage to set the width of the progress bar.
If the "percentage" is above 100 - just reset it to 100 again. jQuery code is below:
var desiredLength = 4; // no jokes please...
// Listen to the change, keyup & paste events.
$('#text-box').on('change keyup paste', function() {
// Figure out the length of the input value
var textLength = $('#text-box').val().length;
// Calculate the percentage
var percent = (textLength / desiredLength) * 100;
// Limit the percentage to 100.
if (percent > 100) {
percent = 100;
}
// Animate the width of the bar based on the percentage.
$('.progress-bar').animate({
width: percent + '%'
}, 200)
});
See the working JSFiddle here : https://jsfiddle.net/jqbka5j8/1/
I've included normal code for setting the width, and the code for animating the width. You can comment/uncomment the necessary ones and test appropriately.
Hope this helps!
There's no need the use of javascript, you can use only pure CSS and Content Editable:
HTML
<div>
<span contenteditable="true">sdfsd</span>
</div>
CSS
span
{
border: solid 1px black;
}
div
{
max-width: 200px;
}
JsFiddle example

Attempting to get dynamically generated classes to loop

I have a script which is dynamically adding a class every time the user moves their mouse in/out of the box (whenever they do, it makes the box larger). I am hoping to make this process loop, so that the large box goes back to a small box. I have attempted to use a if statement to check if the box has the class of "large" then it will revert the class back to "small" in the hopes that the document would repeat itself. Didnt work. Can you suggest any way of achieving this using similar code? I would hope to get this to work with 4 separate classes. Fiddle here: http://jsfiddle.net/cs31g61q/1/
var container=$("#container");
var box=$("#box");
box.mouseenter(function(){
$('#box').removeClass("small");
$('#box').addClass("medium");
});
box.mouseleave(function(){
container.on("mouseenter", "#box", function(){
$(this).removeClass("medium");
$(this).addClass("large");
});
});
<div id="container">
<div id="box" class="small">
</div>
</div>
Does the below snippet produce your desired result?
Snippet:
var box = $('#box');
var classes = ['small', 'medium', 'large'];
var iterator = 0;
box.mouseenter(function () {
$(this).removeClass();
$(this).addClass(classes[iterator]);
iterator += 1;
iterator = iterator > classes.length - 1 ? 0 : iterator;
});
.small {
width: 100px;
height:100px;
background: #000;
}
.medium {
width: 200px;
height: 200px;
background: green;
}
.large {
width:400px;
height: 400px;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="container">
<div id="box" class="small"></div>
</div>
This is basically iterating through a set of classes, applying them one by one on every single time mouse enters #box.
Hope this helps.
Fiddle here.
Check your logic: you only need one event listener - it should respond to either mouseenter or mouseleave and cycle through the classes (small, medium, large).
Below is a very simple approach, as demonstrated in the Fiddle above.
// Set up the event listener: every mouseenter or mouseleave
$(document).on('mouseenter mouseleave', "#box", function(){
var currentClass = $('#box').attr("class");
var newClass = ''; // TBD in switch statement.
switch(currentClass) {
case('small'):
newClass = 'medium';
break;
case('medium'):
newClass = 'large';
break;
case('large'):
default:
newClass = 'small';
break;
}
// Remove the current class, add new one.
$('#box').removeClass();
$('#box').addClass(newClass);
});

Counting continusly with scroll, speed varies

My boss asked me to mimic this site:
http://mailchimp.com/2013/#by-the-numbers
I've been able to figure out every piece except for the white numbers. The really cool (but tricky) effect is that the speed of the count accelerates/decelerates depending on the data-count attribute, even though the distance between sections is the same.
It looks like they used waypoints.js to differentiate between sections. I searched for a plug-in that would adjust speed depending on the data inputs, but I could only find ones like countTo.js which trigger then count, rather than continuously count up and down as the user scrolls.
Any help would be greatly appreciated!
This intrigued me, so I gave it a shot.
As far as I know, waypoints.js only fires when an element hits the edge of the viewport. I don't think you could use it for this kind of thing, because you need to continually update your counter. So I wrote this without any jQuery plugin.
Disclaimer: This code may or may not work for you, either way, please regard it as nothing more than a sketch of a solution, it still needs to be improved in several places to be used for a production site.
var current = $('.step').first();
$('.step').each(function() {
var start = $(this).data('count'),
end = $(this).next().data('count'),
height = $(this).height(),
offset = $(this).offset().top,
increment = end ? height / (end - start) : 0; //after how many pixels of scrolling do we need to incremwent our counter? Set to 0 for last element, just in case
// just adding the count as text, so it gets displayed
$(this).text(start);
//store increment and offset, we need those in our scrollListener
$(this).data({
increment: increment,
offset: offset
});
});
$(document).on('scroll', function() {
var scrollpos = $(window).scrollTop(),
elementscrollpos,
counter;
//check if scrolled to the next element
if (current.next().data('offset') < scrollpos) {
current = current.next();
} else if (current.data('offset') > scrollpos) {
current = current.prev();
}
//calculate the current counter value;
elementscrollpos = scrollpos - current.data('offset');
counter = Math.floor(current.data('count') + elementscrollpos / current.data('increment'));
$('.counter').text(counter);
});
body {
margin: 0;
}
.counter {
position: fixed;
top: 0;
left: 0;
}
.step {
height: 100vh;
text-align: center;
font-size: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="counter"></div>
<div class="step" data-count="0"></div>
<div class="step" data-count="1"></div>
<div class="step" data-count="2"></div>
<div class="step" data-count="8"></div>
<div class="step" data-count="100"></div>
<div class="step" data-count="110240"></div>
<div class="step" data-count="110250"></div>

Loop with trigger (which contains animation) not working

So I seem to have run into a bit of a dead end. I'm making a page which has an image slider. The slider has three images, one centered on the screen, the other two overflow on the left and right. When you click on the button to advance the slides it runs this code....
$('#slideRight').click(function() {
if ($('.container').is(':animated')) {return false;}
var next=parseInt($('.container img:last-of-type').attr('id')) + 1;
if (next == 12) {
next = 0;
}
var diff = galsize() - 700;
if ($('.thumbs').css("left") == "0px") {
var plus = 78;
} else {
var plus = 0;
}
var app='<img id="' + next + '" src="' + imgs[next].src + '">';
$('.container').width('2800px').append(app);
$('.container').animate({marginLeft: (diff + plus) + "px"}, 300, function() {
$('.container img:first-of-type').remove();
$('.container').width('2100px').css("margin-left", (galsize() + plus) + "px");
});
}); // end right click
This works just fine, not a problem..... I also have an interval set up to run this automatically every 5 seconds to form a slideshow...
var slideShow = setInterval(function() {
$('#slideRight').trigger("click");
}, 5000);
This also works perfectly, not a problem.... However my problem is this.... I have thumbnails, when you click on a thumbnail, it should run this code until the current picture is the same as the thumbnail.... here is the code....
$('img.thumbnail').click(function() {
clearInterval(slideShow);
var src = $(this).attr("src");
while ($('.container img:eq(1)').attr('src') != src) {
$('#slideRight').trigger("click");
}
});
When I click on the thumbnail nothing happens... I've used alert statements to try and debug, what ends up happening is this....
The while loop executes, however nothing happens the first time. The slide is not advanced at all. Starting with the second execution, the is('::animated') is triggered EVERY TIME and the remainder of the slideRight event is not executed...
So my first problem, can anyone shed some light on why it doesn't run the first time?
And my second question, is there any way to wait until the animation is complete before continuing with the loop?
Any help would be appreciated. Thank you!
I'm going to start with the second part of your question, regarding completing the animation before continuing with the loop.
I have done something similar in the past, and what I did was set two global variables to control the animation. One variable is for how long you want the period to be, the other is a counter for how much time since the last loop.
So, for example:
$timeToChange = 5; // in Seconds
$timeSinceReset = 0; // also in Seconds
Set your interval for one second and call a new function (autoAdvance()):
var slideShow = setInterval(function() {
autoAdvance();
}, 1000); // only one second
and then use the counter variable to count each time the interval is called (each second). Something like:
function autoAdvance(){
if($timeSinceReset == $timeToChange){
$timeSinceReset = 0;
$('#slideRight').trigger("click"); // execute click if satisfied
}
else{$timeSinceReset++;}
}
To stop from looping until the animation is done, reset $timeSinceReset back to 0 (zero) when you click on the thumbnail. Something like:
$('#thumbnail').click(function(){
$timeSinceReset = 0;
});
That'll give you a nice 5 second buffer (or whatever you set $timeToChange) before the loop continues.
As for the first part of your question, grab the number of the particular thumbnail, and use that to scroll to the appropriate image. Something like:
$('.thumb').click(function (each) {
$childNumber = $(this).index();
});
which you cansee in this fiddle. Click in one of the grey boxes and it'll tell you which one you clicked in. Use that info to scroll to the appropriate image (1, 2 or 3 if you only have three images).
Hope this helps.
Here is a full solution for one possible way of doing it at this fiddle.
HTML:
The top container holds the images. In this particular example I've included three, using divs instead of images. Whether you use images or divs doesn't change anything.
<div class="holder_container">
<div class="img_container">
<div class="photo type1">ONE</div>
<div class="photo type2">TWO</div>
<div class="photo type3">THREE</div>
</div>
</div>
.img_container holds all the images, and is the same width as the sum of the widths of the images. In this case, each image (.photo) is 150px wide and 50px tall, so .img_container is 450px wide and 50px tall. .holder_container is the same dimensions as a single image. When this runs, the .holder_container is set to hide any overflow while .img_container moves its position left or right.
Included also are two nav buttons (forward and back)
<div class="nav_buttons">
<div class="nav back"><<<</div>
<div class="nav forward">>>></div>
</div>
As well as three thumbnail images - one for each image in the top container
<div class="top">
<div class="thumb"></div>
<div class="thumb"></div>
<div class="thumb"></div>
</div>
CSS:
Refer to the JS Fiddle for all CSS rules.
The most important are:
.holder_container {
margin: 0px;
padding: 0px;
height: 50px;
width: 150px;
position: relative;
overflow: hidden;
}
.img_container {
margin: 0px;
padding: 0px;
height: 50px;
width: 450px;
position: relative;
left: 0px;
top: 0px;
}
In the example, .type1, .type2 and .type3 are only used to color the image divs so you can see the animation. They can be left out of your code.
JavaScript:
The javascript contains the following elements…
Variables:
var timeToChange = 3; // period of the image change, in seconds
var timeSinceReset = 0; // how many seconds have passed since last image change
var currentImage = 1; // Which image you are currently viewing
var totalImages = 3; // How many images there are in total
Functions:
autoAdvance - called once every second via setInterval. Counts the number of seconds since the last image change. If the number of seconds that has passed is equal to the period, a function is called that switches the images.
function autoAdvance() {
if (timeSinceReset == timeToChange) {
timeSinceReset = 0;
moveNext();
} else {
timeSinceReset++;
}
}
moveNext() - moves to the next image. If the current image is the last (currentImage == totalImages) then currentImages is set back to 1 and the first image is displayed.
function moveNext(){
if(currentImage == totalImages){
currentImage = 1;
var newPos = 0 + 'px';
$('.img_container').animate({left: newPos}, 300);
}else{
currentImage++;
var newPos = -((currentImage-1) * 150) + 'px'; // child numbers are zero-based
$('.img_container').animate({left: newPos}, 300);
}
}
Rest of code:
If one of the thumbs is clicked, move to the corresponding image.
$('.thumb').click(function (each) {
timeSinceReset = 0;
var childNumber = $(this).index();
currentImage = childNumber + 1; // child numbers are zero-based
var newPos = -(childNumber * 150) + 'px'; // child numbers are zero-based
$('.img_container').animate({left: newPos}, 300);
});
If one of the navigation buttons is clicked, move accordingly. If "back" is clicked, move one image backwards (or to last image if currently on first). If "first" is clicked, move one image forwards (or to first image if currently on last).
$('.nav').click(function(){
timeSinceReset = 0;
if($(this).hasClass('back')){ // Back button
if(currentImage == 1){
currentImage = totalImages;
}else{
currentImage--;
}
}else{ // Forward button
if(currentImage == totalImages){
currentImage = 1;
}else{
currentImage++;
}
}
var newPos = -((currentImage-1) * 150) + 'px';
$('.img_container').animate({left: newPos}, 300);
});
Here is the link to the fiddle example.

Categories

Resources