Javascript image to div - javascript

So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<img src="images/Tulip_small.jpg" alt="Tulips">
<img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips">
<img src="images/Swan_small.jpg" alt="Swan on Lake">
<img src="images/Red_Tulip_small.jpg" alt="Red Tulips">
<img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees">
<img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video">
</div>

Change the class attribute to id or add the id attribute id="html5gallery"
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
EDIT:
Try this to append image
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}

I've never used the instagram API before, but I think this is what you want to achieve (code below). I've included both a Vanilla Javascript method as well as a jQuery method (so you can pick and use whichever one you prefer - vanilla is faster of course)
(function ($, window) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
// Define the gallery variable outside the for loop (performance)
// Vanilla JS
var galleryHTML = document.getElementById("html5gallery");
// jQuery
var $galleryHTML = $('#html5gallery');
// Moved the gallery outside of the for loop (performance, again)
var gallery = document.getElementById('gallery');
var insta = $('.insta');
// or var insta = document.getElementsByClassName('insta')[0] for vanilla JS
// create a function to do the fancy ajax
var fetchInstagram = function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
for (var i = 0; i < numDisplay; i++) {
// I don't think you need the onload function here
// img.onload = function() {
// document.getElementById('gallery').appendChild(img);
// };
// Not sure what this is, but I don't think you need it (for what you want to do)
// $(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
// Create the new image object
var newImage = document.createElement('img');
newImage.src = data.data[i].images.low_resolution.url;
// Insert the images into html5gallery
// Vanilla Javascript Way
// galleryHTML.appendChild(newImage);
// jQuery Way
// var $newImage = $(newImage);
// $galleryHTML.append($newImage);
}
}
});
};
// Making the function available in window for global use
window.fetchInstagram = fetchInstagram;
})(jQuery, window);
// Initiate the function
fetchInstagram();
// You can bind the function to other stuff like.. if you click a button
// $('#load-more').on('click', fetchInstagram);
I was able to get the 4 images to load in a div with the id of html5gallery on my end. Hope this helps!

If the human eye can only see 24fps or 30fps or more when playing a game or watching tv, I believe a programer can use less DIVs in HTML within the screen size, with a Javascript array of 3 million colors for a couple of DIVs and cheat it's position(because of our human eyes), based in a timer event with a bunch of frames per second than the ones I mentioned, example 1 millisecond. In my opinion this is something which I would like to test, if it's the question that drives us let the answer be our destination.
This is the fiddle so far: DEMO
<html>
<head>
<title></title>
<style>#placeDiv{position:absolute;left:0px;width:100px;height:100px;}
#placeDiv1{position:absolute;left:100px;width:100px;height:100px;}
#placeDiv2{position:absolute;left:200px;width:100px;height:100px;}
#b1{position:absolute;top:100px;left:0px}
#b2{position:absolute;top:100px;left:80px}
#b3{position:absolute;top:100px;left:170px}
#b4{position:absolute;top:100px;left:270px}
#b5{position:absolute;top:100px;left:320px}
</style>
</head>
<body>
<div id = "placeDiv">ok</div><div id = "placeDiv1">ok</div><div id = "placeDiv2">ok</div>
<button id="b1" onclick="forward()">Forward</button>
<button id="b2" onclick="backward()">Backward</button>
<button id="b3" onclick="skip2()">skip2</button>
<button id="b4" onclick="automatic()">auto</button>
<button id="b5" onclick="stop()">stop</button>
<script>
var myArray = ["black","yellow","green","red","blue","blue","black","gray"];
var myArray1 = ["yellow","blue","green","red","green","blue","black","gray"];
var myArray2 = ["yellow","blue","green","red","green","blue","black","gray"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
}; skip2=function(){
if(i == myArray.length-4)
{i+=2;alert("This is the iterator "+i)}else if(i==7){i=0}else{i=i+1;};
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;i=myArray1.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
//
}
var m=null;
automatic=function(){
clearInterval(m)
m = setInterval(function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
},1);
function b(x,y){
var a =setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if (x==100){d();clearInterval(a);}},10);
function d(){var z = setInterval(function(){document.getElementById("placeDiv").style.left=x--+"px";if (x==0){c();clearInterval(z);}},10);}
function c(){var g = setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if(x==100){d();clearInterval(g)}},10)};
//Aqui uma copia.
var v =setInterval(function(){document.getElementById("placeDiv").style.top=y+++"px";if (y==100){h();clearInterval(v);}},10);
function h(){var l = setInterval(function( {document.getElementById("placeDiv").style.top=y--+"px";if (y==0){ok();clearInterval(l);}},10);}
function ok(){var ja = setInterval(function( {document.getElementById("placeDiv").style.top=y+++"px";if(y==100 {h();clearInterval(ja)}},10)};
}
b(0,0);
stop=function(){clearInterval(m)};
};
</script>
</body>
</html>

Related

Need to solve problem with asynchronous code

I made a small game where there are 3 pictures of chests, and you have one attempt to choose a chest with a prize.
But the problem is with the asynchronous code, a notification of defeat or victory is displayed faster than the desired picture is put in the right place, After the message, a function that puts all the chests closed that also does not allow the picture to take its place.
var count=0;
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src ='https://i.pinimg.com/originals/ae/f7/15/aef715f93eadcdf77c4dfa3baf5859ad.jpg'
imgArray[1] = new Image();
imgArray[1].src = "https://previews.123rf.com/images/gl0ck33/gl0ck331106/gl0ck33110600002/9781614-wooden-chest-with-gold-coins.jpg";
imgArray[2] = new Image();
imgArray[2].src = "https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg";
var images = document.getElementsByTagName("img");
var k = Math.floor(Math.random() * 3) + 1;
console.log("Winning number " + k);
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function(e) {
count++;
console.log("Count " + count);
if(this.id == k){
count=0;
this.src = imgArray[1].src;//here picture with a gift
alert("You Win");// here problem,alert Faster than the picture above
TryAgain();//And this function is faster to put pictures with closed chests
return;
} else {
this.src = imgArray[0].src;//picture empty chest
}
if (count >= 1) {
count = 0;
alert("You lose!!!");//alert Faster than the picture above
TryAgain();
return;
}
}, false);
}
function TryAgain(e) {
for (var i = 0; i < images.length; i++){
images[i].src = imgArray[2].src;//picture with close chest
k = Math.floor(Math.random() * 3) + 1;
}
console.log(k);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img width="300px" height="300px" src="https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg" id="1">
<img width="300px" height="300px" src="https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg" id="2">
<img width="300px" height="300px" src="https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg" id="3">
<button id="btn" onclick="TryAgain()">Try Again</button>
</body>
</html>
Answer:
You need to wait for the images to get done loading before running alert.
alert completely halts the processing of code. Therefore if the image isn't loaded before it is executed you're not going to see the change occur.
A simple pattern to do this would be:
let self = this;
this.src = imgArray[1].src;
this.onload = function() {
alert("You Win");
self.onload = undefined;
TryAgain();
}
return;
Example:
var count=0;
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src ='https://i.pinimg.com/originals/ae/f7/15/aef715f93eadcdf77c4dfa3baf5859ad.jpg'
imgArray[1] = new Image();
imgArray[1].src = "https://previews.123rf.com/images/gl0ck33/gl0ck331106/gl0ck33110600002/9781614-wooden-chest-with-gold-coins.jpg";
imgArray[2] = new Image();
imgArray[2].src = "https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg";
var images = document.getElementsByTagName("img");
var k = Math.floor(Math.random() * 3) + 1;
console.log("Winning number " + k);
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function(e) {
let self = this;
count++;
console.log("Count " + count);
if(this.id == k){
count=0;
this.src = imgArray[1].src;//here picture with a gift
this.onload = function() {
alert("You Win");// here problem,alert Faster than the picture above
self.onload = undefined;
TryAgain();//And this function is faster to put pictures with closed chests
}
return;
} else {
this.src = imgArray[0].src;//picture empty chest
this.onload = function() {
alert("You Lose");// here problem,alert Faster than the picture above
self.onload = undefined;
TryAgain();//And this function is faster to put pictures with closed chests
}
return;
}
}, false);
}
function TryAgain(e) {
for (var i = 0; i < images.length; i++){
images[i].src = imgArray[2].src;//picture with close chest
k = Math.floor(Math.random() * 3) + 1;
}
console.log(k);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img width="300px" height="300px" src="https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg" id="1">
<img width="300px" height="300px" src="https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg" id="2">
<img width="300px" height="300px" src="https://i.pinimg.com/originals/94/09/6b/94096bf738837c16582902d281c520bc.jpg" id="3">
<button id="btn" onclick="TryAgain()">Try Again</button>
</body>
</html>
Images do not appear as soon as you set this.src
They appear when the browser is ready to show them, which may take some time.
Perhaps you can use the "load" event listener? This will fire once the image is visible. At that stage you can do the alert?
images[i].addEventListener("load", function(e) {
// This will run only once the image is loaded (i.e. visible)
} )

hyperlinking an image in an array from another array

I have 2 arrays,I with images and another with links.
Using set interval I am changing the image in 2000millisec.
How can I hyperlink the image with the links.
var img_array = <?php echo json_encode($images); ?>;
var link_array = <?php echo json_encode($links); ?>;
var image = document.getElementById("aaa");
var index=0;
function slide(){
document["aaa"].src = img_array[index];
index++;
if(index>=img_array.length)
{
index=0;
}
}
setInterval("slide()",2000);
</script>
Here's an example. It's not perfect, because if you see it in the first time, the image is not loaded. This is why most of the sites generates all the images with links, and then just hide and show them.
var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
var link = document.getElementById("link");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;
function slide(){
image.src = img_array[index];
link.href = link_array[index];
index++;
if(index >= img_array.length) {
index=0;
}
}
setInterval(slide, 2000);
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" width="200">
Or if you can't change the DOM or you want to hide somewhy the url you can do something like this:
var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;
function slide(){
image.src = img_array[index];
index++;
if(index >= img_array.length) {
index=0;
}
}
image.addEventListener("click", function() {
// This is because of the sandbox environment.
console.log(link_array[index]);
// This is what you need.
window.open(link_array[index]);
});
setInterval(slide, 2000);
.pointer {
cursor: pointer;
}
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" class="pointer" width="200">
However in this case maybe you will get blocked by the browser or if the click was registered after the new image was loaded, it may create a missclick.

how to load multiple image one by one on canvas? using loop

var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];
function sava(){
//push to array for loop
$('.Jicon').each(function(){
retval.push($(this).attr('id'));
retvalsrc.push($(this).attr('src'));
})
var className = $(".Jicon");
var classnameCount = className.length;
//loop classname
for(var d = 0; d < classnameCount; d++){
updateCanvas(retval[d], retvalsrc[d]);
}
}
//change main image
function updateCanvas(_id, _src)
{
ImgCanvas.clear();
// var oImg = new fabric.Image(_src, {
fabric.Image.fromURL(_src, function(oImg) {
oImg.setWidth(500);
oImg.setHeight(400);
oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
oImg.top = 50;
oImg.selectable = false;
ImgCanvas.add(oImg);
ImgCanvas.renderAll();
});
}
i have a mutiplete Image which i wanna to load them to canvas one by one using loop , how do i achieve that ? so when i press sava the image will show one by one on the canvas.i tried to use for but it load all those image together.
can anyone give me a help here~ thank apreciate.
Demo
Let the end of the imageFromURL call the next load, and refactor the code for use a settimeout, otherwise everything will be very fast.
The images before appeared all togheter because the load is async. So with the for loop you were
rapidly starting the loading in sequence of 4 images
immediately clear 4 times a canvas that is still empty
every image will then finish loading and appear on the canvas on random order.
var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];
function sava(){
$('.Jicon').each(function(){
retval.push($(this).attr('id'));
retvalsrc.push($(this).attr('src'));
})
updateCanvas();
}
//change main image
function updateCanvas() {
ImgCanvas.clear();
var _src = retvalsrc.pop();
fabric.Image.fromURL(_src, function(oImg) {
oImg.setWidth(500);
oImg.setHeight(400);
oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
oImg.top = 50;
oImg.selectable = false;
ImgCanvas.add(oImg);
ImgCanvas.renderAll();
if (retvalsrc.length > 0) {
setTimeout(updateCanvas, 1000);
}
});
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<img name="001.png" class="Jicon" id="displayImage1" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/077.png" onclick="updateCanvas(this.src);">
<img name="002.png" class="Jicon" id="displayImag2" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/076.png" onclick="updateCanvas(this.src);">
<img name="003.png" class="Jicon" id="displayImage3" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/071.png~c100" onclick="updateCanvas(this.src);">
<img name="004.png" class="Jicon" id="displayImag4" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/072.png~c100" onclick="updateCanvas(this.src);">
</div>
<button onclick="sava();">sava</button>
<div id="warpper">
<canvas id="mycanvas" width="380" height="500" style="border:1px solid #000;"></canvas>
</div><!-- end of div -->
</body>

How do I access and modify an image in an HTML page using javascript?

My HTML page has an image with id img. The idea is that by clicking first, previous, or next, the user can navigate through a set of images. How do I do this using JavaScript?
This should be a good start for you:
<script>
var imgs = ["img1.png","img2.png","img3.png"]; // copy images to the same dir
var index = 0;
</script>
<img src="img1.png" onclick="this.src=imgs[++index%imgs.length]"/>
click the image to slide.
If you need buttons, see this example:
<img id="clicker" src="img1.png"/>
Prev
Next
First
Last
<script>
var imgs = ["img1.png","img2.png","img3.png"];
var index = 0;
var clicker = document.getElementById("clicker");
function prev() { clicker.src = imgs[--index%imgs.length]; }
function next() { clicker.src = imgs[++index%imgs.length]; }
function first() { clicker.src = imgs[index=0]; }
function last() { clicker.src = imgs[index=imgs.length-1]; }
</script>
The return false means that default action on click (follow the link) is supressed. Javascript can access elements i.e. using id (see clicker here). Once you get comfortable with this and you start to solve browser compatibility problems, it is good idea to continue with jQuery (as the other suggests), MooTools or other framework.
Use jQuery!
var myImg = $("#myimg");
$("#next").click(function(){
var id = myImg.attr("data-id") + 1;
myImg.attr("src", "image"+id+".jpg");
});
$("#prev").click(function(){
var id = myImg.attr("data-id") -1;
myImg.attr("src", "image"+id+".jpg");
});
HTML:
<img id="myimg" src="image1.jpg" data-id="1">
Next<br>
Previous<br>
This is a very dummy example. There are numerous slideshow plugins out there!
No need jQuery:
<script type='text/javascript'>
window.onload = function() {
var imageSrcs= ['1.jpeg', '2.jpg', '3.jpg'];
var index = 0;
var image = document.getElementById('img');
var previous = document.getElementById('previous');
previous.onclick = function() {
index -= 1;
if(index < 0) index = imageSrcs.length - 1;
image.src = imageSrcs[index];
}
var next = document.getElementById('next');
next.onclick = function() {
index += 1;
if(index == imageSrcs.length) index = 0;
image.src = imageSrcs[index];
}
}
</script>
And html:
<img src='1.jpeg' id='img'>
<div>
<span id='previous'>Previous</span>
<span id='next'>Next</span>
</div>
You do not need a library for this. Something like this will change the image url, where "theImg" is the id of the image:
document.getElementById("theImg").src = "newUrl.png";
To do it without explicit ids, this will change the url where i is the index of the image:
document.getElementsByTagName("img")[i].src = "newUrl.png";
Try something like this (untested):
LOAD JQUERY:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
JAVASCRIPT:
<script type='text/javascript'>
var lst_src = ['img1.jpg', 'img2.png', 'img3.gif'];
$('a', '#nav').click(function(e) {
e.preventDefault();
var src_current = $('#img').attr('src');
var index = lst_src.indexOf(src_current);
var len = lst_src.length;
var action = $(this).attr('class');
switch ($action) {
case 'previous' : var i = index - 1;
if (i < 0) src_current = lst_src[len + i];
else src_current = lst_src[i];
break;
case 'next' : var i = index + 1;
if (i > len) src_current = lst_src[i - len];
else src_current = lst_src[i];
break;
case 'first' : src_current = lst_src[0];
break;
case 'last' : src_current = lst_src[len - 1];
break;
}
$('#img').attr('src', src_current);
});
</script>
HTML: Use the class of a link to denote the required action:
<img id='img' src='img1.jpg'>
<p id='nav'>
<a href='' class='first'>←←First</a>
<a href='' class='previous'>←Previous</a>
<a href='' class='next'>Next→</a>
<a href='' class='last'>Last→$rarr;</a>
</p>

I've hashed together this simple script to rotate pictures and link them to specified URL's, how do I make it pause when I mouseover the picture?

<a id="imageurl" name="imageurl"><img src="Rotating1" id="Rotating1" border="0" alt="Rotating1" name="Rotating1" /></a>
<script language="javascript" type="text/javascript">
function RotateImages(Start)
{
var a = new Array("1.jpg","2.jpg","3.jpg", "4.jpg");
var c = new Array("url1", "url2", "url3", "url4");
var b = document.getElementById('Rotating1');
var d = document.getElementById('imageurl');
if(Start>=a.length)
Start=0;
b.src = a[Start];
d.href = c[Start];
window.setTimeout("RotateImages(" + (Start+1) + ")",3000);
}
RotateImages(0);
</script>
Change your code as Follows:
<a id="imageurl" name="imageurl"><img src="Rotating1" id="Rotating1" border="0" alt="Rotating1" name="Rotating1" onmouseover="StopRotation();" onmouseout="RotateImages();"/></a>
<script language="javascript" type="text/javascript">
var currentImage = -1;
function RotateImages()
{
var a = new Array("1.jpg","2.jpg","3.jpg", "4.jpg");
var c = new Array("url1", "url2", "url3", "url4");
var b = document.getElementById('Rotating1');
var d = document.getElementById('imageurl');
currentImage++;
if(currentImage>= a.length)
currentImage=0;
b.src = a[currentImage];
d.href = c[currentImage];
rotator = window.setTimeout("RotateImages(" + (currentImage+1) + ")",3000);
}
function StopRotation()
{
window.clearTimeout(rotator);
}
RotateImages();
</script>
added Function "StopRotation"
added onmouseover and onmouseout-Events to the Image Tag
Rotation continues at the current Image.
The return value of setTimeout can be passed to cancelTimeout to stop the rotation. You might save it to a variable, then cancel the timeout on MouseIn and restart it on MouseOut.

Categories