Make images clickable to next image in javascript - javascript

I have a Previous/Next link on my site that lets me go thru the images with this code:
Previous | Next
<span id='num'></span>
I have placed the images in the codes below. The Previous / Next links are working great but I would like to be able to click on the images itself to navigate to the next images: so click on 1.jpg then goes to 2.jpg so forth and once clicked on 5.jpg goes back to 1.jpg. Please advise, thanks in advance for your help. I am a beginner building my site blindly and any help is much appreciated.
<script type="text/javascript">
var image = new Array("jpegs/1.jpg",
"jpegs/2.jpg",
"jpegs/3.jpg",
"jpegs/4.jpg",
"jpegs/5.jpg"
)
var imgNumber=1
var numberOfImg = image.length
function previousImage(){
if(imgNumber > 1){
imgNumber--
}
else{
imgNumber = numberOfImg
}
document.slideImage.src = image[imgNumber-1]
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.slideImage.src = image[imgNumber-1]
}
</script>

How about:
document.slideImage.onclick = nextImage;
I would also suggest using event registration (also for the anchors):
document.slideImage.addEventListener('click', nextImage);

I wouldn't recommend using href="Javascript:function()", so to give you an idea of how to approach it...
<script type="text/javascript">
window.onload = function() {
var n = 0;
var src = ["jpegs/1.jpg", "jpegs/2.jpg", "jpegs/3.jpg", "jpegs/4.jpg", "jpegs/5.jpg"];
var e = document.getElementById('slideImage');
var prev = function() {
n -= 1;
if(n < 0) n = src.length - 1;
e.setAttribute('src', src[n]);
};
var next = function() {
n += 1;
if(n >= src.length) n = 0;
e.setAttribute('src', src[n]);
};
e.onclick = next;
document.getElementById('nextlink').onclick = next;
document.getElementById('prevlink').onclick = prev;
};
</script>
This method does not write variables to window (excluding onload) and only requires an id attribute.

Related

Having real trouble combining 2 JS

I am struggling combining two JS into one… I try and try in the JSFiddle but can not really understand the console erros…
I am trying to have a background-color that changes combined with a changing background .svg in a div…
$(document).ready(function() {
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)";
images[1] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)";
images[2] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)";
images[3] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)";
//function
function changeImage() {
var el = document.getElementById('header');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
$(function setbackground() {
window.setTimeout( "setbackground()", 2000);
var index = Math.round(Math.random() * 4);
var ColorValue = "FA89CB";
if(index == 1)
ColorValue = "FAED96";
if(index == 2)
ColorValue = "D27DFA";
if(index == 3)
ColorValue = "6CFA64";
if(index == 4)
ColorValue = "8370FA";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
});
});
Here's my fiddle:
http://jsfiddle.net/gmck02ru/1/
does somebody have a clue – i guess I am not really understanding what I am doing here so far...
Help please!
The issue is because the syntax you've used to define the setbackground() function is incorrect. You've placed it inside a jQuery object. That function is also never called. You should define it as a standalone function and invoke it when the page loads.
In addition there's a few improvements you can make to the logic.
Use addEventListener() over setting the onclick or other onX event properties.
Declare the elements of the array at the same time as you define the array itself.
Use an array to hold the background colours instead of hard-coding an if statement.
Use the modulo operator when incrementing the counter to save having to write logic to reset to 0
If you want to repeatedly update the background colour, as you do for the images, place the setTimeout() call within the setbackground() function.
Use document.body directly instead of getting it by tag name
$(document).ready(function() {
let i = 0;
let images = [
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)"
];
let backgroundColours = ['#FAED96', '#D27DFA', '#6CFA64', '#8370FA']
function changeImage() {
let el = document.getElementById('header');
el.style.backgroundImage = images[i];
i = ++i % (images.length - 1)
setTimeout(changeImage, 3000);
}
changeImage();
function setbackground() {
let index = Math.round(Math.random() * 4);
document.body.style.backgroundColor = backgroundColours[index];
setTimeout(setbackground, 2000);
}
setbackground();
});
Working jsFiddle - see the demo in the fiddle as the images are on an insecure domain so cannot be called from SO.

Play Boostrap Popover on loop

DEMO: http://jsfiddle.net/0s730kxx/
I'm trying to open Bootstrap Popover to auto-open on loop but so far I've have manage only to auto-play once.
HTML:
<div class="container">
Hover Left |
Hover Right |
Click Me
</div>
JS:
$(document).ready(function(){
var time = 1000;
var len = $('.myclass').length;
var count = 0;
var fun = setInterval(function(){
count++;
if(count>len){
clearInterval(fun);
}
$('.p'+count).popover('show');
if(count>1){
var pre = count-1;
$('.p'+pre).popover('hide');
}
}, time);
});
Could anyone help? I want it on loop so it plays forever or atleast 10 or 20 times.
Modify javascript part of your fiddle like this:
$(document).ready(function(){
var time = 1000;
var len = $('.myclass').length;
var count = 0;
var fun = setInterval(function(){
count++;
if(count>len){
$('.p'+(count-1)).popover('hide');
count = 1;
//clearInterval(fun);
}
$('.p'+count).popover('show');
if(count>1){
var pre = count-1;
$('.p'+pre).popover('hide');
}
}, time);
});
Since you are not clearing the interval in this modified snippet, it will run forever as you expected.
Thats because you have added line
if(count>len){
clearInterval(fun);
}
After showing them 1 time count is 3 and clearInterval(fun) is called
which terminates further call to function fun().
Original comment: You can't clear the interval and expect the loop to continue! Instead of clearing set the count back to 0. But you'll also need to remember to hide the last popover.
var fun = setInterval(function(){
count++;
$('.p' + count).popover('show');
if(count > 1){
$('.p' + (count - 1)).popover('hide');
}
if(count > len){
count = 0;
}
}, time);
Here is a fiddle: http://jsfiddle.net/89gcqnfm/
Simplicity and modular arithmetic are your friends:
$(document).ready(function(){
var time = 1000;
var eles = $('.myclass');
var count = 0;
var fun = setInterval(function(){
if(eles.length < 1)
return (console.log("No elements found!")&&!1) || clearInterval(fun);
eles.eq(count%eles.length).popover('hide');
eles.eq(++count%eles.length).popover('show');
}, time);
});
https://jsfiddle.net/L2487dfy/

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

javascript slideshow overlay

i would like to make image slideshow.
First, i would have just thumbnails and when clicked on the one, it would pop up overlay(some sort of div, or something) and there would be option to move through the images. I don't want to use anykind of libraries
i have this, so far:
NewImg = new Array (
"img/1gif",
"img/2gif",
"img/3gif"
);
var ImgNum = 0;
var ImgLength = NewImg.length - 1;
var delay = 3000;
var lock = false;
var run;
function chgImg(direction) {
if (document.images) {
ImgNum = ImgNum + direction;
if (ImgNum > ImgLength) {
ImgNum = 0;
}
if (ImgNum < 0) {
ImgNum = ImgLength;
}
document.slideshow.src = NewImg[ImgNum];
}
}
function auto() {
if (lock == true) {
lock = false;
window.clearInterval(run);
}
else if (lock == false) {
lock = true;
run = setInterval("chgImg(1)", delay);
}
html part
Previous
Auto/Stop
Next
this is the regular image gallery. With regular sized images.
I don't know how to implement those thumbnails
thank for helping me around here
i forgot, i have
used following code for overlays(but don't know how to implement it here)
function toggleLayer( whichLayer )
{
var elem, vis;
if( document.getElementById )
{
elem = document.getElementById( whichLayer );
}
vis = elem.style;
if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
http://jsfiddle.net/sevdah/z7Ggx/1/ on jsfiddle, but it is not working, don't know why

Rotating URLs within an Iframe

I have 10 different urls that I want to feed into an iframe src attribute that I would also like to rotate say every 5 seconds between all the 10 urls within the iframe.
Unsure how to do this using javascript/best approach?
Sorry, should've mentioned that I am using IE6.
Thanks.
<iframe id="rotator" src="http://...first"></iframe>
<script>
// start when the page is loaded
window.onload = function() {
var urls = [
"http://...first",
"http://...second",
// ....
"http://...tenth" // no ,!!
];
var index = 1;
var el = document.getElementById("rotator");
setTimeout(function rotate() {
if ( index === urls.length ) {
index = 0;
}
el.src = urls[index];
index = index + 1;
// continue rotating iframes
setTimeout(rotate, 5000);
}, 5000); // 5000ms = 5s
};
</script>
Javascript (place in window.onload)
var urls = ['http://www.stackoverflow.com', 'http://www.google.com'];
var pos = 0;
next();
setInterval(next, 5000); // every 5 seconds
function next()
{
if(pos == urls.length) pos = 0; // reset the counter
document.getElementById('rotate').src = urls[pos];
pos++;
}
HTML
<iframe id="rotate"></iframe>
There are many ways, so best is up for debate. Take a look at setInterval() since you mentioned JavaScript. I'd write a method that got the iframe on the page by it's id attribute, getElementById() and changed the src attribute to the next URL in the array of URLs.
<!doctype html>
<html>
<body>
<iframe id="foo"></iframe>
<script>
(function() {
var e = document.getElementById('foo'),
f = function( el, url ) {
el.src = url;
},
urls = [
'http://www.msn.com/',
'http://www.mtv.com/'
],
i = 0,
l = urls.length;
(function rotation() {
if ( i != l-1 ) {
i++
} else {
i = 0;
}
f( e, urls[i] );
setTimeout( arguments.callee, 5000 );
})();
})();
</script>
</body>
</html>
Is there a reason to reload the iframes every time they rotate in? I might load all the iframes upfront and simply rotate through their display if this particular project was concerned with quality of experience.
Hi I assume you would want to load the page completely before starting the timer to load the next URL, otherwise you would end up showing the next URL before the existing page even shows up (depending on your internet speed).
Secondly you said you want to rotate the URLS.
Below is the tested code for this:
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var urls = [
"http://www.google.com"
,"http://www.yahoo.com"
,"http://www.ajaxian.com"
,"http://www.ebay.com"
];
function showUrl(idx) {
alert(idx + " Showing " + urls[idx]);
var f = document.getElementById("f");
// call the next load after 5 seconds only after
// this iframe loads
f.onload = function() {
var next = ++idx % urls.length;
setTimeout(function(){
showUrl(next);
}, 5000);
}
// set the src
f.src = urls[idx];
}
</script>
</head>
<body onload="showUrl(0)" class="app-chrome">
<iframe id="f" src="about:blank"></iframe>
</body>
</html>
Adding a more compact version: (Works in IE6, FF, Opera, Chromium)
<script type="text/javascript">
window.onload = (function(urls, interval) {
var idx = 0;
var bAttached = false;
return function showUrl() {
var f = document.getElementById("f");
var onLoad = function() { // loading only after previous page loads
idx = ++idx % urls.length; // rotation
setTimeout(showUrl, interval);
}
if(! bAttached) {
if(navigator.userAgent.indexOf("MSIE") !== -1) {
f.attachEvent("onload", onLoad);
bAttached = true;
}else {
f.onload = onLoad;
}
bAttached = true;
}
f.src = urls[idx];
};
})([
"http://www.google.com" ,"http://www.yahoo.com" ,
"http://www.sun.com" ,"http://www.ebay.com"
], 5000
);
</script>
I am not going to do it all for you but an example as requested:
Using Jquery for ease.
Code:
<script type="text/javascript">
//sets a var to 0//
var MyInt = 0
//sets some URLS//
var url1 = 'http://UR1L.com';
var url2 = 'http://URL2.com';
var url3 = 'http://URL3.com';
function RunEveryTenSecs {
// Increases var by 1//
MyInt + 1;
//Checks var value if 1 runs if not goes to next//
if (MyInt == 1) {
$('#MyElementID').html('<iframe src="' + url1+ '"></iframe>');
}
if (MyInt == 2) {
$('#MyElementID').html('<iframe src="' + url2+ '"></iframe>');
}
if (MyInt == 3) {
$('#MyElementID').html('<iframe src="' + url3+ '"></iframe>');
MyInt = 0;
}
}
window.setTimeout(RunEveryTenSecs, 10000);
</script>
HTML:
<div id="MyElementID">
IFRAME WILL GO HERE.
</div>
It may not be the neatest there are other ways to do it but it is something simple and easy to understand. The URL's dont have to be seperate but it will make changing them in the future easier.

Categories

Resources