Javascript Next and Previous images - javascript

Code is supposed to show next image when clicking on next arrow and previous image when clicked on previous arrow. It does not work though. (error occurs while assigning img.src=imgs[this.i]; it says Cannot set property 'src' of null
at collection.next) .
Javascript code :
var arr = new collection(['cake.png', 'image2.png', 'image3.png', 'image1.png']);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById('element')
this.i++;
if (this.i == imgs.length) {
this.i = 0;
}
img.src = imgs[this.i].src;
}
this.prev = function(element) {
var img = document.getElementById('element');
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i].src;
}
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
Not using jquery. I do not have enough experience in js either. Thank you for your time

You had three mistakes:
You referenced the images as img.src = imgs[this.i].src; and you just had an array of strings, not an array of objects with a src property. img.src = imgs[this.i]; is the correct way to get the URL.
You used
var img = document.getElementById('element');
when you should have used
var img = document.getElementById(element);
element is an argument coming from your onclick event. It holds the id of your image that you should be using. "element" is just a string. You try to find an element with id equal to element which doesn't exist.
Edit: You should also use < and > to represent < and >. Otherwise your HTML might get screwed up. More on that here.
var arr = new collection(['http://images.math.cnrs.fr/IMG/png/section8-image.png', 'https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg', "http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"]);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById(element);
this.i++;
if (this.i >= imgs.length) {
this.i = 0;
}
img.src = imgs[this.i];
};
this.prev = function(element) {
var img = document.getElementById(element);
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i];
};
this.next("mainImg"); // to initialize with some image
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
This is how I'd personally do it:
var myCollection = new Collection([
"http://images.math.cnrs.fr/IMG/png/section8-image.png",
"https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg",
"http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"
], "mainImg");
document.getElementById("next_btn").onclick = function() {
myCollection.next();
};
document.getElementById("prev_btn").onclick = function() {
myCollection.prev();
}
function Collection(urls, imgID) {
var imgElem = document.getElementById(imgID);
var index = 0;
this.selectImage = function() {
imgElem.src = urls[index];
};
this.next = function() {
if (++index >= urls.length) {
index = 0;
}
this.selectImage();
};
this.prev = function(element) {
if (--index < 0) {
index = urls.length - 1;
}
this.selectImage();
};
// initialize
this.selectImage();
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input id="next_btn" type='button' value='<' />
<img id='mainImg'>
<input id="prev_btn" type='button' value='>' />
</body>
</html>

Why sending string into arr.next('mainImg') function ?
your img element always have the same id, only change src.
and document.getElementById(element) is also the same img element.
html: <img id='mainImg' src="cake.png">
js: document.getElementById('mainImg')
consider img element as a container, and id is it's identifiler.

var start_pos = 0;
var img_count = document.getElementsByClassName('icons').length - 1;
var changeImg = function(direction){
pos = start_pos = (direction == "next")? (start_pos == img_count)? 0 : start_pos+1 : (start_pos == 0)? img_count : start_pos-1;
console.log(pos)
}
document.getElementById('left').onclick = function(){ changeImg("previous"); }
document.getElementById('right').onclick = function(){ changeImg("next"); }

Related

How do I get the slideshow to disappear after one cycle through (javascript)

this intro slideshow works so far, it starts automatically when you load the webpage and cycles through the 4 photos. But I want the slideshow to disappear (to reveal the website homepage underneath) after it has cycled through the 4 photos only once, but need some help how to proceed forward.
<!DOCTYPE html>
<head>
</head>
<body>
<div id="slideshow">
<img id="pic" width="100%" height="auto" alt="Icon" src="one.jpg">
</div>
<script>
var i, imgs, pic;
function rotate() {
pic.src = imgs[i];
(i === (imgs.length - 1)) ? (i = 0) : (i++);
setTimeout(rotate, 1000);
}
function init() {
pic = document.getElementById("pic");
imgs = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"];
var preload = new Array();
for (i = 0; i < imgs.length; i++) {
preload[i] = new Image();
preload[i].src = imgs[i];
}
i = 0;
rotate();
}
document.addEventListener("DOMContentLoaded", init, false);
</script>
</body>
</html>
var count = 0
function rotate() {
pic.src = imgs[i];
(i === (imgs.length - 1)) ? (i = 0) : (i++);
if (count < imgs.length) {
count++;
setTimeout(rotate, 1000);
} else {
document.getElementById("slideshow").style.display = 'none';
}
}
Hi,
you have to count your number of slides. Afterwards just check if you already finished.
greetings
<!DOCTYPE html>
<head>
</head>
<body>
<div id="slideshow">
<img id="pic" width="100%" height="auto" alt="Icon" src="one.jpg">
</div>
<script>
var i, imgs, pic;
function rotate() {
pic.src = imgs[i];
if(i<(imgs.length - 1)){
i++;
setTimeout(rotate, 1000);
}
}
function init() {
pic = document.getElementById("pic");
imgs = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"];
var preload = new Array();
for (i = 0; i < imgs.length; i++) {
preload[i] = new Image();
preload[i].src = imgs[i];
}
i = 0;
rotate();
}
document.addEventListener("DOMContentLoaded", init, false);
</script>
</body>
</html>
if(i<(imgs.length - 1)){
i++;
setTimeout(rotate, 1000);
}
You need to check for how many time the rotate() method need to call.

How can i make a HTML button run three functions one after another

My code has three functions. I want one button to run function one when pressed the first time then function 2 when pressed the second time function 3 when pressed the third time and then for it to reset.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green]
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
</script>
</head>
<body>
<button id="sequence" onclick="changeyellow" onclick="changered" onclick="changegreen">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>
You can use only one function and a global variable that contains the current color like this :
<!DOCTYPE html>
<html>
<head>
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green];
var currentColor = 0;
function changeColor() {
var img = document.getElementById("light");
img.src= lights[currentColor];
if (currentColor === (lights.length - 1)) {
currentColor = 0;
} else {
currentColor++;
}
return false;
}
</script>
</head>
<body>
<button id="sequence" onclick="changeColor();">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>
There are several ways you could handle it, but here's an easy one:
above:
function changered()
add this:
var cur_button = 1
Then change your button to this:
<button id="sequence" onclick="handle_click()">sequence</button>
and add this function:
function handle_click()
{
if(cur_button == 1)
{
cur_button = 2
changered()
}
else if(cur_button == 2)
{
cur_button = 3
changeyellow()
}
else if(cur_button == 3)
{
cur_button = 1
changegreen()
}
}
There you go
<input type="button" name="btnn" onclick="runFunction()" />
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png";
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png";
var green = "https://s29.postimg.org/5ljr1ha3r/green.png";
var lights =[red,yellow,green];
var a =1;
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
function runFunction()
{
if(a==1)
{
changered();
a++;
}
if(a==2)
{
changeyellow();
a++;
}
if(a==3)
{
changegreen();
a=1;
}
}
I can use the switch statement, and simply reference the lights array to determine which to display next. Seems pretty painless.
var red = "https://snowmonkey.000webhostapp.com/images/red.png"
var yellow = "https://snowmonkey.000webhostapp.com/images/yellow.png"
var green = "https://snowmonkey.000webhostapp.com/images/green.png"
var lights =[red,yellow,green]
handleClick = function(){
var light = document.getElementById("light");
switch (light.src) {
case lights[0]:
light.src = lights[1];
break;
case lights[1]:
light.src = lights[2];
break;
case lights[2]:
light.src = lights[0];
break;
}
}
#light {
float: right;
width: 50px;
}
<button id="sequence" onclick="handleClick();">sequence</button>
<br><br><br>
<img id="light" src="https://snowmonkey.000webhostapp.com/images/green.png" />
https://jsfiddle.net/x1rqwzvy/1/
You shouldn't add more than one onclick in your html code. If you do the handlers will activate simultaneously. This means you have to handle the change with JavaScript.
To determine the light you would simply increment a value in the following example:
function lightChange() {
lightChange.incrementer = lightChange.incrementer || 1;
switch (lightChange.incrementer) {
case 1:
changered();
break;
case 2:
changeyellow();
break;
case 3:
changegreen();
lightChange.incrementer = 0;
break;
}
lightChange.incrementer++;
function changered() {
var img = document.getElementById("light");
img.src = lights[0];
return false;
}
function changeyellow() {
var img = document.getElementById("light");
img.src = lights[1];
return false;
}
function changegreen() {
var img = document.getElementById("light");
img.src = lights[2];
return false;
}
}
then just change the onclick handler to lightChange instead of trying to add three consecutive handlers.
<button id="sequence" onclick="lightChange()">sequence</button>
how about
var counter = 0;
function changeColor(){
counter++;
var img = document.getElementById("light");
img.src= lights[counter % 3];
return false;
}
and your html should be:
<button id="sequence" onclick="changeColor()">sequence</button>
You can create a function array and then remove entries from it once done.
var functionArray = [changered,changeyellow,changegreen]
function sequenceClick(){
functionArray[0]();
functionArray.shift();
}
Complete Code:
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green]
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
var functionArray = [changered,changeyellow,changegreen]
function sequenceClick(){
functionArray[0]();
functionArray.shift();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="sequence" onclick="sequenceClick()">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>

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>

function is undefined in firefox only

ok, the following code works ok in IE7+ and Chrome.
but for some reason, xfade is undefined in firefox
<html>
<body>
<div id="slider"></div>
<script type="text/javascript">
var Klimateka = {
Slider: function () {
// Check if we have a slider div on page
var slider = document.getElementById('slider');
if (slider != null) {
var images = ["slide-image-1.jpg", "slide-image-2.jpg", "slide-image-3.jpg", "slide-image-4.jpg"];
var i = images.length;
while (i) {
i -= 1;
var img = document.createElement("img");
img.src = "images/" + images[i];
slider.appendChild(img);
}
var d = document, imgs = new Array(), zInterval = null, current = 0, pause = false;
imgs = d.getElementById("slider").getElementsByTagName("img");
for (i = 1; i < imgs.length; i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;
setTimeout("xfade()", 3500);
function xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current + 1] ? current + 1 : 0;
nOpacity = imgs[nIndex].xOpacity;
cOpacity -= .05;
nOpacity += .05;
imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;
setOpacity(imgs[current]);
setOpacity(imgs[nIndex]);
if (cOpacity <= 0) {
imgs[current].style.display = "none";
current = nIndex;
setTimeout(xfade, 3500);
} else {
setTimeout(xfade, 50);
}
function setOpacity(obj) {
if (obj.xOpacity > .99) {
obj.xOpacity = .99;
return;
}
obj.style.opacity = obj.xOpacity;
obj.style.MozOpacity = obj.xOpacity;
obj.style.filter = "alpha(opacity=" + (obj.xOpacity * 100) + ")";
}
}
}
},
bar: function () {
}
};
Klimateka.Slider();
i have setup a jsfiddler for testing:
http://jsfiddle.net/rTtKh/10/
This might only apply to Firefox:
functions do not hoist when declared inside a child block.
You declare xfade inside the if block, but you are calling it prior to the declaration:
setTimeout(xfade, 3500);
Put the function declaration on top.
You have to do the same with setOpacity inside xfade. <- That is not necessary.
Fix your line that says this: setTimeout("xfade()", 3500); to match your others:
setTimeout(xfade, 3500);
Use setTimeout(xfade, 3500) instead.

Javascript Images Resize

I want to resize images depend on its size in CSS with JS function which get all images in the div but i am facing problems with getelement by tagname which i have to set the images styles into the img HTML tag or its never work , in this test project its easy to do but in my real one there is many images into this div and many pages so here the function and its HTML
<script type="text/javascript">
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].style.height == '1000px' && yourImgs[i].style.width == '1000px')
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
}
}
window.onload= x;
</script>
</head>
<body>
<div id="test">
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book1.jpg' />
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book2.jpg' />
</div>
Ignore style and just check for height and width like in this example:
http://jsfiddle.net/5yjfy/2/
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].height == 1000 && yourImgs[i].width == 1000)
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
} } window.onload= x;

Categories