I am developing a cross-platform mobile application using Cordova. I have an HTML page with a table. I have a button add row when clicked adds a new row to my table. I need an iOS-like swipe action to have a delete action. I used touchstart event to swipe a static row in my table. That works fine but not with dynamically created table rows. How to do this swipe action?
This is the code I have so far:
HTML
<div class="fortable">
<table id="cashreg">
<tr>
<td class="tablecellbackground"><div class="del" id="d1" ><p>Delete</p></div><div id="cells" class="cells"><div class="denom"><p>Start Time</p></div><div class="cnt"><p>Select Item</p></div><div class="tots"><p>Employee</p></div><div class="tots1"><p>Price</p></div></div></td>
</tr>
</table>
<input type="button" class="addmore">
</div>
JavaScript
For adding a row to the table:
$(".addmore").click(function(){
var rows = $("#cashreg tr").length+1;
$("#cashreg").append('<tr><td class="tablecellbackground"><div class="cells"><div class="denom"><p>Start Time</p></div><div class="cnt"><p>Select Item</p></div><div class="tots"><p>Employee</p></div><div class="tots1"><p>Price</p></div><div class="del"><p>Delete</p></div></div></td></tr>');
});
For iOS-like swipe:
window.addEventListener('load', function(){
var el = document.getElementsByClassName('cells')[0];
ontouch(el, function(evt, dir, phase, swipetype, distance){
var touchreport = ''
touchreport += '<b>Dir:</b> ' + dir + '<br />'
touchreport += '<b>Phase:</b> ' + phase + '<br />'
touchreport += '<b>Swipe Type:</b> ' + swipetype + '<br />'
touchreport += '<b>Distance:</b> ' + distance + '<br />'
if(dir=="left"){
left=parseInt(($(".cells").css("top")).replace ( /[^\d.]/g, '' ))-distance;
$(".cells").css("left","-"+left+"px")
}
if(dir=="right"){
if($(".cells").css("left")== "-166px"){
//left=parseInt(($(".cells").css("top")).replace ( /[^\d.]/g, '' ))-distance;
$(".cells").css("left","0px")
}
}
if(dir=="none"){
// document.getElementById("hi").value=el.pageX;
}
})
}, false)
function ontouch(el, callback){
var touchsurface = el,
dir,
swipeType,
startX,
startY,
distX,
distY,
threshold = 50, //required min distance traveled to be considered swipe
restraint = 100, // maximum distance allowed at the same time in perpendicular direction
allowedTime = 500, // maximum time allowed to travel that distance
elapsedTime,
startTime,
handletouch = callback || function(evt, dir, phase, swipetype, distance){}
touchsurface.addEventListener('touchstart', function(e){
var touchobj = e.changedTouches[0]
dir = 'none'
swipeType = 'none'
dist = 0
startX = touchobj.pageX
startY = touchobj.pageY
startTime = new Date().getTime() // record time when finger first makes contact with surface
handletouch(e, 'none', 'start', swipeType, 0) // fire callback function with params dir="none", phase="start", swipetype="none" etc
e.preventDefault()
}, false)
touchsurface.addEventListener('touchmove', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
if (Math.abs(distX) > Math.abs(distY)){ // if distance traveled horizontally is greater than vertically, consider this a horizontal movement
dir = (distX < 0)? 'left' : 'right'
handletouch(e, dir, 'move', swipeType, distX) // fire callback function with params dir="left|right", phase="move", swipetype="none" etc
}
else{ // else consider this a vertical movement
dir = (distY < 0)? 'up' : 'down'
handletouch(e, dir, 'move', swipeType, distY) // fire callback function with params dir="up|down", phase="move", swipetype="none" etc
}
e.preventDefault()
// prevent scrolling when inside DIV
}, false)
touchsurface.addEventListener('touchend', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX
elapsedTime = new Date().getTime() - startTime // get time elapsed
if (elapsedTime <= allowedTime){ // first condition for awipe met
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
swipeType = dir // set swipeType to either "left" or "right"
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
swipeType = dir // set swipeType to either "top" or "down"
}
}
// Fire callback function with params dir="left|right|up|down", phase="end", swipetype=dir etc:
handletouch(e, dir, 'end', swipeType, (dir =='left' || dir =='right')? distX : distY)
e.preventDefault()
if(dir=="left"){
if(distX>-100){
$(".cells").css("left","0px")
}
else if(distX<-50 && distX>-100){
$(".cells").css("left","-166px")
}
else{
$(".cells").css("left","-166px")
}
}
}, false)
}
How to make this swipe apply to a newly added table row?
You should use event delegation on() to deal with new elements added dynamically by js :
$("body").on('touchstart click','#cashreg tr', function(e){
})
Hope this helps.
The problem is that you bind your cells elements with the event ontouch in the load function. It means that only the elements present on load will be bound. You need to register the ontouch event on your newly created row element as well.
With your example, you could try to use the ontouch html attribute directly, i.e.:
<div class="cells" ontouchstart="...">
or simply bind the touch event to your body and check for the cells class in the handler:
var el = document.getElementsByTagName('body')[0];
ontouch(el, function(evt, dir, phase, swipetype, distance){
if($(evt.target).hasClass("cells")){
// your code
}
});
Related
I have a webgame I made in pure javascript using processing.js
It works fine on desktop but I want it to work on mobile.
It's on this website: https://www.ricarddokifuri.tk/mlg/
I found a function to detect swipes
function swipedetect(el, callback){
var touchsurface = el,
swipedir,
startX,
startY,
distX,
distY,
threshold = 150, //required min distance traveled to be considered swipe
restraint = 100, // maximum distance allowed at the same time in perpendicular direction
allowedTime = 300, // maximum time allowed to travel that distance
elapsedTime,
startTime,
handleswipe = callback || function(swipedir){}
touchsurface.addEventListener('touchstart', function(e){
var touchobj = e.changedTouches[0]
swipedir = 'none'
dist = 0
startX = touchobj.pageX
startY = touchobj.pageY
startTime = new Date().getTime() // record time when finger first makes contact with surface
e.preventDefault()
}, false)
touchsurface.addEventListener('touchmove', function(e){
e.preventDefault() // prevent scrolling when inside DIV
}, false)
touchsurface.addEventListener('touchend', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
elapsedTime = new Date().getTime() - startTime // get time elapsed
if (elapsedTime <= allowedTime){ // first condition for awipe met
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
swipedir = (distX < 0)? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
swipedir = (distY < 0)? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
}
}
handleswipe(swipedir)
e.preventDefault()
}, false)
}
I can activate and detect which direction was swiped like this
swipedetect(el, function(swipedir){
if (swipedir == 'left')
alert('You just swiped left!')
});
My function to move the player is like this
var movePlayer = function(){
if(keyCode === LEFT){
x -= 3.5*scaless;
}
if(keyCode === RIGHT){
x += 3.5*scaless;
}
if(keyCode === UP){
y -= 3.5*scaless;
}
if(keyCode === DOWN){
y += 3.5*scaless;
}
};
if(keyPressed){
movePlayer();
}
How could I make the function that detects a swipe, simulate a keypress?
If you want to reuse your movePlayer function both for the keyboard and for swipes, then I would probably make it accept an argument and then call it either from a keypress event handler with the event keycode either from the swipe handler with an appropriate argument.
So basically, according to this: https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
The keycodes for up,right,down,left are:
UP: 38
RIGHT: 39
DOWN: 40
LEFT: 37
so you could modify your move player like so:
var movePlayer = function(keyCode){
if(keyCode === LEFT){
x -= 3.5*scaless;
}
if(keyCode === RIGHT){
x += 3.5*scaless;
}
if(keyCode === UP){
y -= 3.5*scaless;
}
if(keyCode === DOWN){
y += 3.5*scaless;
}
};
From your code snippet, I am assuming that LEFT, RIGHT, UP and DOWN are constant values, somewhere else in your program, so then I would modify my swipe detect function like:
swipedetect(el, function(swipedir){
if (swipedir == 'left'){
movePlayer(LEFT);
}else if(swipedir == 'right'){
movePlayer(RIGHT);
}else if(swipedir == 'up'){
movePlayer(UP);
}else if(swipedir == 'down'){
movePlayer(DOWN);
}
//you can have the default case in an else here
});
Then, you would need to modify the keypress code that calls movePlayer when the user uses the keyboard to pass the code of the key that was pressed i.e. by doing movePlayer(event.keyCode) in your keypress event handler.
Hi Friends i am very very new to javascript and and J Query . now i want to create virtual mouse pad . i am created two div's one for mouse pad and second one is container in container i am taken another div for act as a cursor(class name is follower) .
in mouse pad div when ever mouse move follower div moving relative to the mouse position. now i want to generate click event using virtual cursor means click the buttons using follower.
Button1
Button2
MousePad
this is my js code
var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$('.container1').mousemove(function(e){
var offset = $('.container1').offset();
mouseX = Math.min(e.pageX - offset.left, limitX);
mouseY = Math.min(e.pageY - offset.top, limitY);
mouseX=mouseX*3;
mouseY=mouseY*3;
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 0;
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp);
yp += (mouseY - yp) ;
follower.css({left:xp, top:yp});
}, 30);
$('.buttons span').bind('click',function(){
alert($(this).attr('title'));
});
JSbin Link
http://jsbin.com/AGAquhej/2/edit for code
http://jsbin.com/AGAquhej/1 Demo
i want generate click event using follower(moving in mouse pad)
can any one solve the problem how to generate fake click events
Thanks in advance
Using the some collision detection code from this SO answer https://stackoverflow.com/a/12180865/1481489 the following may work (untested, description is in the comments):
var overlaps = (function () { // this is the collision detection code
function getPositions( elem ) {
var pos, width, height;
pos = $( elem ).position();
width = $( elem ).width();
height = $( elem ).height();
return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
}
function comparePositions( p1, p2 ) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function ( a, b ) {
var pos1 = getPositions( a ),
pos2 = getPositions( b );
return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
};
})();
$('.container1').mousemove(function(e){
var offset = $('.container1').offset();
mouseX = Math.min(e.pageX - offset.left, limitX);
mouseY = Math.min(e.pageY - offset.top, limitY);
mouseX=mouseX*3;
mouseY=mouseY*3;
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 0;
});
$('.container1').click(function(){
proxyTriggerEvent('click');
});
function proxyTriggerEvent(eventName) {
$('.container').find('a,input,.buttons span')
.each(function() { // and loop through them all for testing
if ( overlaps(follower,this) ) { // collision detection for each item
$(this).trigger(eventName); // click the specific element
return false; // break out of the loop
}
});
}
Update:
Fixed a bug where the selector was not targeting the buttons. I misread the tag as <span class="button1"> but it is really <span title="button1">. The selector is now .buttons span instead of .button1,.button2.
Removed the unnecessary filtering of follower with .not('#follower')
Moved the hit detection to the click handler of .container - this way it isn't being run on every single interval frame, only when it really counts.
Moved the event trigger proxy out of the click call, now any event can be triggered, and it can be called as a regular function, e.g.: proxyTriggerEvent('mouseup'); or proxyTriggerEvent('click');
I am implementing a swipe effect but move position of upper div by calculating the x, y coordinates and then move the wrapper(upper most div) with screen width, so it looks like swipe effect.
Now my problem is I dont know which in the next div showing on the screen, I need to manipulate on that, is there any method I can get the current div id which is showing on the DIV.
Below is my JS Code
(function() {
var swipey = {
slideContainer: null, //<ul> element object that holds the image slides
wrapper: null, //meant for masking/clipping
slides: null, //array of all slides i.e <li> elements
distanceX: 0, //distance moved in X direction i.e left or right
startX: 0, //registers the initial touch co-ordinate
preferredWidth: 0, //dynamic variable to set width
preferredHeight: 0, //dynamic variable to set height
direction: "", //direction of movement
timer: null, //timer that set starts when touch starts
timerCounter: 0, //counter variable for timer
hasSwipeStarted: false, //boolen to chk whether touch has started
maxDistance: 0, //maximum distance in X direction that slide container can move
currentDistance: 0, //current distance moved by slide container through translate
//detect touch and then automatically assign events
isTouchSupported: 'ontouchstart' in window.document,
initSwipey: function() {
// alert('in initSwipey');
//scroll the window up to hide the address bar of the browser.
window.setTimeout(function() {
window.scrollTo(0, 1);
}, 100);
/*mapping touch events to mouse events. Automatic registration of event
based on the device. If touch enabled then touch event is registered.
and if desktop browser then mouse event is registered.*/
swipey.startEvent = swipey.isTouchSupported ? 'touchstart' : 'mousedown',
swipey.moveEvent = swipey.isTouchSupported ? 'touchmove' : 'mousemove',
swipey.endEvent = swipey.isTouchSupported ? 'touchend' : 'mouseup',
//get all the instances of the HTML elements
swipey.wrapper = document.getElementById("wrapper");
swipey.slideContainer = document.getElementById("sitePageContainer");
//swipey.slides = slideContainer.getElementsByTagName("li");
swipey.slides = document.getElementsByClassName("sitePage");
//for iPhone, the width and height
swipey.preferredWidth = window.innerWidth;
// alert("swipey.preferredWidth: " + swipey.preferredWidth);
swipey.preferredHeight = window.innerHeight; //510 for android
// alert("swipey.preferredHeight: " + swipey.preferredHeight);
//setting the width and height to our wrapper with overflow = hidden
swipey.wrapper.style.width = swipey.preferredWidth + "px";
// alert("swipey.wrapper.style.width: " + swipey.wrapper.style.width);
swipey.wrapper.style.height = swipey.preferredHeight + "px";
// alert("swipey.wrapper.style.height: " + swipey.wrapper.style.height);
//setting the width to our <ul> element which holds all the <li> elements
swipey.slideContainer.style.height = swipey.preferredHeight + "px";
// alert("swipey.slideContainer.style.height: " + swipey.slideContainer.style.height);
swipey.slideContainer.style.width = swipey.slides.length * swipey.preferredWidth + "px";
// alert("swipey.slideContainer.style.width: " + swipey.slideContainer.style.width);
//display the <ul> container now
swipey.slideContainer.style.display = "inline-block";
//setting width and height for <li> elements - the slides
for(var i=0;i<swipey.slides.length;i++)
{
swipey.slides[i].style.width = swipey.preferredWidth + "px";
swipey.slides[i].style.height = swipey.preferredHeight + "px";
}
//calculating the max distance of travel for Slide Container i.e <ul> element
swipey.maxDistance = swipey.slides.length * swipey.preferredHeight;
//initialize and assign the touch events
swipey.initEvents();
},
initEvents: function() {
//registering touch events to the wrapper
//$('#wrapper').bind(swipey.startEvent, swipey.startHandler );
$('#wrapper').bind(swipey.startEvent, function(e){
$('#wrapper').bind(swipey.moveEvent, swipey.moveHandler );
} );
$('#wrapper').bind(swipey.endEvent, swipey.endHandler );
//swipey.wrapper.addEventListener(swipey.startEvent, swipey.startHandler, false);
//swipey.wrapper.addEventListener(swipey.moveEvent, swipey.moveHandler, false);
//swipey.wrapper.addEventListener(swipey.endEvent, swipey.endHandler, false);
},
//funciton called when touch start event is fired i.e finger is pressed on the screen
startHandler: function(event) {
//create appropriate event object to read the touch/mouse co-ordinates
var eventObj = swipey.isTouchSupported ? event.touches[0] : event;
//stores the starting X co-ordinate when finger touches the device screen
swipey.startX = eventObj.pageX;
//timer is set on
swipey.timer = setInterval(function() {
swipey.timerCounter++;
}, 10);
swipey.hasSwipeStarted = true;
event.preventDefault(); //prevents the window from scrolling.
},
//funciton called when touch move event is fired i.e finger is dragged over the screen
moveHandler: function(event) {
if (swipey.hasSwipeStarted) {
//create appropriate event object to read the touch/mouse co-ordinates
var eventObj = swipey.isTouchSupported ? event.touches[0] : event;
swipey.distanceX = eventObj.pageX - swipey.startX;
//move the slide container along with the movement of the finger
swipey.slideContainer.style.webkitTransform = "translate3d(" + (swipey.distanceX + swipey.currentDistance) + "px, 0,0)";
}else{
swipey.startHandler(event);
}
},
//funciton called when touch end event is fired i.e finger is released from screen
endHandler: function(event) {
$('#wrapper').unbind(swipey.moveEvent, swipey.moveHandler );
clearInterval(swipey.timer); //timer is stopped
if(swipey.distanceX == 0) //if the intention is to tap on the image then open a link
{
var link_url = event.target.getAttribute("link"); //read the link from <img /> element
// window.open(link_url,"_blank");
}
else
{
if (swipey.distanceX > 0) {
swipey.direction = "right";
}
if (swipey.distanceX < 0) {
swipey.direction = "left";
}
//the following conditions have been discussed in details
if ((swipey.direction == "right" && swipey.currentDistance == 0) || (swipey.direction == "left" && swipey.currentDistance == -(swipey.maxDistance - swipey.preferredWidth))) {
swipey.comeBack();
}
else if (swipey.timerCounter < 30 && swipey.distanceX > 10) {
swipey.moveRight();
}
else if (swipey.timerCounter < 30 && swipey.distanceX < -10) {
swipey.moveLeft();
}
else if (swipey.distanceX <= -(swipey.preferredWidth / 2)) { //-160
swipey.moveLeft();
}
else if (swipey.distanceX >= (swipey.preferredWidth / 2)) { //160
swipey.moveRight();
}
else {
swipey.comeBack();
}
}
swipey.timerCounter = 0; //reset timerCounter
swipey.hasSwipeStarted = false; //reset the boolean var
swipey.distanceX = 0; //reset the distance moved for next iteration
//alert(event.screenX+"::"+event.screenY);
var element = document.elementFromPoint(event.screenX, event.screenY);
var $element = $(element);
alert($element.attr('id'));
$("div.fixHeader").hide();
$("#"+$element.attr('id')+" div.fixHeader").show();
},
moveLeft: function() {
swipey.currentDistance += -swipey.preferredWidth;
swipey.slideContainer.style.webkitTransitionDuration = 300 + "ms";
//using CSS3 transformations - translate3d function for movement
swipey.slideContainer.style.webkitTransform = "translate3d(" + swipey.currentDistance + "px, 0,0)";
},
moveRight: function() {
swipey.currentDistance += swipey.preferredWidth;
swipey.slideContainer.style.webkitTransitionDuration = 300 + "ms";
swipey.slideContainer.style.webkitTransform = "translate3d(" + swipey.currentDistance + "px, 0,0)";
},
comeBack: function() {
swipey.slideContainer.style.webkitTransitionDuration = 250 + "ms";
swipey.slideContainer.style.webkitTransitionTimingFunction = "ease-out";
swipey.slideContainer.style.webkitTransform = "translate3d(" + swipey.currentDistance + "px, 0,0)";
}
}; //end of swipey object
window.swipeyObj = swipey; //expose to global window object
})();
window.onload = function() {
swipeyObj.initSwipey();
} //invoke the init method to get started
Updates:
Below are structure, Now I am sliding sitePageContainer and sitePage appears on screen, now I want to know which div is showing on screen (partypicturespage1 or partypicturespage2)
<div id="wrapper">
<div id="sitePageContainer">
<div class="sitePage" id="partypicturespage1"></div>
<div class="sitePage" id="partypicturespage2"></div>
You can select your visible div the following way:
$("div.fixHeader:visible")
Update:
If all of your divs are visible then use a custom data-* attribute to keep track of the div that is currently in view. You can do it the following way:
$("div.fixHeader").attr('data-visible', true);
and select it the following way:
$("div.fixHeader[data-visible=true]");
and you remove the attribute so you don't select divs that are no longer in view:
$("div.fixHeader[data-visible=true]").attr('data-visible', false);
Update #2:
If you scroll the page by setting the container's left property, then determining which div is in view is done by the following calculation in pseudo code:
ceil(scrollContainer.left / divWidth) // if index starts from 1
floor(scrollContainer.left / divWidth) // if index starts from 0
I have this horizontal carousel component that I want to make it work for both Mouse and Swipe events.
Everything is working fine, except for one bit: in touch devices, I don't want the carousel to scroll horizontally if the user is trying to swipe vertically to scroll through the whole page.
What I am doing is,
on mousedown/touchstart - I stop the event from propagating to avoid page scroll, item selects, etc...
on the first move event, on the carousel, I set a 50ms timeout to determine if the user is moving vertically or horizontally.
If deltaX < deltaY, I stop my horizontal scrolling, manually fire the touchstart event, with a flag indicating that i fired it manually
on my mousedown/touchstart handler, I read that "manually" flag and, if it's true, I return true from my function so all the default browser events, like the page vertical scrolling, continue to work.
This is not working, everything I'm doing responds correctly but the browser doesn't pick up and scroll the page. I hope I am explaining myself correctly enough so you guys can help me... I don't have an online example because this is a "secret" project for my company...
I was trying to do the same thing as you (were?). The key is to check on touchmove if the current touch and the last touch is more vertical than horizontal. If the touch was more left to right or right to left, prevent the event's default, otherwise ignore it. Here's what I ended up writing. Hopefully it works for you!
var gestures = function() {
var self = this,
coords = {
startX: null,
startY: null,
endX: null,
endY: null
};
self.$el.on('touchstart', function(e) {
coords.startX = e.originalEvent.targetTouches[0].clientX;
coords.startY = e.originalEvent.targetTouches[0].clientY;
coords.endX = coords.startX;
coords.endY = coords.startY;
});
self.$el.on('touchmove', function(e) {
var newX = e.originalEvent.targetTouches[0].clientX,
newY = e.originalEvent.targetTouches[0].clientY,
absX = Math.abs(coords.endX - newX),
absY = Math.abs(coords.endY - newY);
// If we've moved more Y than X, we're scrolling vertically
if (absX < absY) {
return;
}
// Prevents the page from scrolling left/right
e.preventDefault();
coords.endX = newX;
coords.endY = newY;
});
self.$el.on('touchend', function(e) {
var swipe = {},
deltaX = coords.startX - coords.endX,
deltaY = coords.startY - coords.endY,
absX = Math.abs(deltaX),
absY = Math.abs(deltaY);
swipe.distance = (absX > absY) ? absX : absY;
swipe.direction = (absX < absY) ?
(deltaY < 0 ? 'down' : 'up') :
(deltaX < 0 ? 'right' : 'left');
// console.log(swipe.direction + ' ' + swipe.distance + 'px');
// If we have a swipe of > 50px, let's use it!
if (swipe.distance > 50) {
if (swipe.direction === 'left') {
self.advance();
} else if (swipe.direction === 'right') {
self.retreat();
}
}
});
};
this is my slider object and $el is the container element.
I have one scrolling image which is in jQuery, it scrolls and logos of the clients appears in scrolling box and it keeps scrolling without a pause.
I can increase and decrease the speed. But for pause and then resuming the animation in 2 seconds, I am not able to which I want.
Here is the link where I have downloaded the source code http://net.tutsplus.com/tutorials/javascript-ajax/building-a-jquery-image-scroller/
**The code in html file**
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function() {
//remove js-disabled class
$("#viewer").removeClass("js-disabled");
//create new container for images
$("<div>").attr("id", "container").css({ position:"absolute"}).width($(".wrapper").length * 170).height(170).appendTo("div#viewer");
//add images to container
$(".wrapper").each(function() {
$(this).appendTo("div#container");
});
//work out duration of anim based on number of images (1 second for each image)
var duration = $(".wrapper").length * 1000;
//store speed for later (distance / time)
var speed = (parseInt($("div#container").width()) + parseInt($("div#viewer").width())) / duration;
//set direction
var direction = "rtl";
//set initial position and class based on direction
(direction == "rtl") ? $("div#container").css("left", $("div#viewer").width()).addClass("rtl") : $("div#container").css("left", 0 - $("div#container").width()).addClass("ltr") ;
//animator function
var animator = function(el, time, dir) {
//which direction to scroll
if(dir == "rtl") {
//add direction class
el.removeClass("ltr").addClass("rtl");
//animate the el
el.animate({ left:"-" + el.width() + "px" }, time, "linear", function() {
//reset container position
$(this).css({ left:$("div#imageScroller").width(), right:"" });
//restart animation
animator($(this), duration, "rtl");
//hide controls if visible
($("div#controls").length > 0) ? $("div#controls").slideUp("slow").remove() : null ;
});
} else {
//add direction class
el.removeClass("rtl").addClass("ltr");
//animate the el
el.animate({ left:$("div#viewer").width() + "px" }, time, "linear", function() {
//reset container position
$(this).css({ left:0 - $("div#container").width() });
//restart animation
animator($(this), duration, "ltr");
//hide controls if visible
($("div#controls").length > 0) ? $("div#controls").slideUp("slow").remove() : null ;
});
}
}
//start anim
animator($("div#container"), duration, direction);
//pause on mouseover
$("a.wrapper").live("mouseover", function() {
//stop anim
$("div#container").stop(true);
//show controls
($("div#controls").length == 0) ? $("<div>").attr("id", "controls").appendTo("div#outerContainer").css({ opacity:0.7 }).slideDown("slow") : null ;
($("a#rtl").length == 0) ? $("<a>").attr({ id:"rtl", href:"#", title:"rtl" }).appendTo("#controls") : null ;
($("a#ltr").length == 0) ? $("<a>").attr({ id:"ltr", href:"#", title:"ltr" }).appendTo("#controls") : null ;
//variable to hold trigger element
var title = $(this).attr("title");
//add p if doesn't exist, update it if it does
($("p#title").length == 0) ? $("<p>").attr("id", "title").text(title).appendTo("div#controls") : $("p#title").text(title) ;
});
//restart on mouseout
$("a.wrapper").live("mouseout", function(e) {
//hide controls if not hovering on them
(e.relatedTarget == null) ? null : (e.relatedTarget.id != "controls") ? $("div#controls").slideUp("slow").remove() : null ;
//work out total travel distance
var totalDistance = parseInt($("div#container").width()) + parseInt($("div#viewer").width());
//work out distance left to travel
var distanceLeft = ($("div#container").hasClass("ltr")) ? totalDistance - (parseInt($("div#container").css("left")) + parseInt($("div#container").width())) : totalDistance - (parseInt($("div#viewer").width()) - (parseInt($("div#container").css("left")))) ;
//new duration is distance left / speed)
var newDuration = distanceLeft / speed;
//restart anim
animator($("div#container"), newDuration, $("div#container").attr("class"));
});
//handler for ltr button
$("#ltr").live("click", function() {
//stop anim
$("div#container").stop(true);
//swap class names
$("div#container").removeClass("rtl").addClass("ltr");
//work out total travel distance
var totalDistance = parseInt($("div#container").width()) + parseInt($("div#viewer").width());
//work out remaining distance
var distanceLeft = totalDistance - (parseInt($("div#container").css("left")) + parseInt($("div#container").width()));
//new duration is distance left / speed)
var newDuration = distanceLeft / speed;
//restart anim
animator($("div#container"), newDuration, "ltr");
});
//handler for rtl button
$("#rtl").live("click", function() {
//stop anim
$("div#container").stop(true);
//swap class names
$("div#container").removeClass("ltr").addClass("rtl");
//work out total travel distance
var totalDistance = parseInt($("div#container").width()) + parseInt($("div#viewer").width());
//work out remaining distance
var distanceLeft = totalDistance - (parseInt($("div#viewer").width()) - (parseInt($("div#container").css("left"))));
//new duration is distance left / speed)
var newDuration = distanceLeft / speed;
//restart anim
animator($("div#container"), newDuration, "rtl");
});
});
</script>
There is already code in the example you posted that will stop and resume the animation (the live mouseover and mouseout event handlers on a.wrapper).
You should be able to take the required code out of those functions, and use it in combination with the jQuery delay function, or JavaScript's native setTimeout function to pause the animation for a specified amount of time.