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.
Related
I'm currently working on an image rotator. The rotation part is complete, however I'm expanding the functionality based on a need that I've found.
Goal: Rotate through a preset list of slides that contain hardcoded images, however on each subsequent rotation, use js to swap to a new image for specific slides that require a variation.
The script below works fine, but I feel like it's not the most efficient way to go about this. Currently I'm tackling it by running a new loop and function for each of the specific slides that I've chosen to be the "different" ones. My guess is there is a way to do it using one function and loop, but I'm not quite sure how to go about it.
Anology: Let's say I have an image rotator that displays a list of cars and every 5 seconds it rotates to the next slide. Each slide is designated for a different model of car, however for some models, I want to display a different variation of that model on each iteration of the entire rotator.
Example:
Here is a list of how each pass of the rotator would print.
- Ford Focus
- Toyota Celica
- Hyundai Elantra
- Dodge Ram
- Motorcycle
- Ford Focus
- Toyota Celica GTS
- Hyundai Elantra
- Dodge Ram w/ additional accessories
- Motorcycle
- Ford Focus
- Toyota Celica w/ Spoiler
- Hyundai Elantra
- Dodge Ram different color
- Motorcycle
Here is my current script:
<script>
window.onload=function() {
imgCont = document.getElementById('example1');
c_imgCont = document.getElementById('example2');
}
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("slide");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1;
if (typeof(imgCont) != 'undefined' && imgCont != null)
{
swapImage();
}
if (typeof(c_imgCont) != 'undefined' && c_imgCont != null)
{
swapImageExample2();
}
}
x[myIndex-1].style.display = "block";
setTimeout(carousel, x[myIndex-1].dataset.timing);
}
var picPaths = ['image1.png','img2.png','img3.png','img4.png'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
}
var c_picPaths = ['otherimg1.png','otherimg2.png'];
var c_curPic = -1;
//preload the images for smooth animation
var c_imgO = new Array();
for(l=0; l < c_picPaths.length; l++) {
c_imgO[l] = new Image();
c_imgO[l].src = c_picPaths[l];
}
function swapImageExample2() {
c_curPic = (++c_curPic > c_picPaths.length-1)? 0 : c_curPic;
c_imgCont.src = c_imgO[c_curPic].src;
}
</script>
Why not just adjust your data structure so that any "image" in the picPaths array can be an array of image paths. Then use a function to get the image path to show. See simple example below.
Notice the structure of picPaths. Also notice that the 2nd and 4th images in the rotation (transport, nature) rotate through different images each iteration of the picPaths array.
<img id="example1" src="http://lorempixel.com/400/200/cats/1/"/>
<script>
window.onload = function() {
imgCont = document.getElementById('example1');
swapImage();
}
var picPaths = [
"http://lorempixel.com/400/200/cats/1/",
[
"http://lorempixel.com/400/200/transport/1/",
"http://lorempixel.com/400/200/transport/2/",
"http://lorempixel.com/400/200/transport/3/",
"http://lorempixel.com/400/200/transport/4/"
],
"http://lorempixel.com/400/200/animals/1/",
[
"http://lorempixel.com/400/200/nature/1/",
"http://lorempixel.com/400/200/nature/2/",
"http://lorempixel.com/400/200/nature/3/",
"http://lorempixel.com/400/200/nature/4/",
"http://lorempixel.com/400/200/nature/5/"
],
"http://lorempixel.com/400/200/sports/1/"
],
curImg = 0;
function getImagePath(path) {
if(Array.isArray(path)) {
var temp = path.shift();
path.push(temp);
return temp;
}
else {
return path;
}
}
function swapImage() {
curImg = curImg < (picPaths.length - 1) ? curImg : 0;
var imgPath = getImagePath(picPaths[curImg]);
console.clear();
console.log('current index in picPaths:', curImg, 'current image path to display:', imgPath);
imgCont.src = imgPath;
curImg++;
setTimeout(function() {
swapImage();
}, 4000);
}
</script>
Based on your comment I made a 2nd example. I think this is what you mean.
window.onload = function() {
carousel(picPaths, 'slide');
};
var picPaths = [
"https://placeimg.com/640/480/any/sepia/1",
[
"https://placeimg.com/640/480/tech/1",
"https://placeimg.com/640/480/tech/2",
"https://placeimg.com/640/480/tech/3",
"https://placeimg.com/640/480/tech/4"
],
"https://placeimg.com/640/480/animals/1",
[
"https://placeimg.com/640/480/nature/1",
"https://placeimg.com/640/480/nature/2",
"https://placeimg.com/640/480/nature/3",
"https://placeimg.com/640/480/nature/4",
"https://placeimg.com/640/480/nature/5"
],
"https://placeimg.com/640/480/arch/1"
];
function carousel(imgPaths, imgClass) {
var imgs = document.getElementsByClassName(imgClass);
Array.prototype.forEach.call(imgs, function(imgElem, idx) {
var timing = imgElem.dataset.timing,
path = imgPaths[idx];
swapImage(imgElem, path, timing);
});
function getImagePath(path) {
if(Array.isArray(path)) {
var temp = path.shift();
path.push(temp);
return temp;
}
else {
return path;
}
};
function swapImage(imgElem, path, timing) {
var imgPath = getImagePath(path);
imgElem.src = imgPath;
setTimeout(function() {
swapImage(imgElem, path, timing);
}, timing);
};
}
.slide {
width: 100px;
}
<div id="container">
<img id="slide_1" class="slide" src="" data-timing="8000">
<img id="slide_2" class="slide" src="" data-timing="4000">
<img id="slide_3" class="slide" src="" data-timing="10000">
<img id="slide_3" class="slide" src="" data-timing="6000">
</div>
I have to make a program which is able to present an animation once opened.
Here the code that I have so far, but I am not sure how to fix it to automatically show the pictures and I am not allowed to use a button or hover over the image to change it , and I'm not allowed to use a premade gif or a gif at all
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
var image1 = document.getElementById("myImage");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if (timerValue >= 30) {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
} else if (timer <= 60) {
img.src("http://www.iconsplace.com/icons/preview/orange/sad-256.png");
} else {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
}
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">
You can use an interval:
window.onload = function(){
var index = 0;
var ImageList = ["Images/happy.png", "Images/sad.png"];
var image1 = document.getElementById("myImage");
var a = 0;
setInterval(function(){
a++;
image1.src = ImageList[a % ImageList.length];
}, 30000);
}
It changes the image per 30 seconds.
You have the two images in an array. USE it!
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
window.onload=function() { // page has finished loading, image is available
var image1 = document.getElementById("myImage");
var tId=setInterval(function() {
index=index==0?1:0; // if 0 then 1 else 0
// for more images instead use:
// index++; if (index>=ImageList.length)index=0;
image1.src=ImageList[index]; // how to set the image src
},5000); // every 5 seconds
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">
I have a unique situation where I am trying to take an image and swap it out after a specific time. I have that part working however I also need the pictures to fade in and out of each other and I can not figure that part out. Please help if you can.
JavaScript:
<script type="text/javascript">
var picPaths = ['images/Front1.jpg','images/Front2.jpg','images/Front3.jpg'];
var curPic = -1;
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,5000);
}
window.onload=function() {
imgCont = document.getElementById('imgBanner');
swapImage();
}
</script>
HTML:
div img id="imgBanner" src="" alt="" / /div
I have the correct <> in places on the HTML however it would not let me post the HTML into the screen.
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>
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>