I am using below java script code to create slide show with images
img1.jpg, img1.jpg and img3.jpg.
But it is displaying just img1.jpg in the output. Please tell the problem.
<html>
<style>
#slideshow{width:310;height:210;border-style:solid;}
#slideshow>img{position:absolute;left:15;top:15}
</style>
<body>
<div id="slideshow">
<img id="imge" src="img1.jpg" height="200" width="300">
</div>
<script>
var count=2;
function mf()
{
document.getElementById("imge").src="img"+count+".jpg";
document.getElementById("imge").height="200";
document.getElementById("imge").width="300";
if(count<3)
count++;
else
count=1;
setTimeout("mf()",3000);
}
</script>
</body>
</html>
You need to start off your script afterwards, with mf();
<script>
var count=2;
// if your script is at the bottom of the page, you can move
// these three lines out here
var elem = document.getElementById("imge");
elem.height="200";
elem.width="300";
function mf() {
elem.src="img"+ (count + 1) +".jpg"; // add 1 to grab images 1 through 3
count = ((count + 1) % 3); // will loop from 0 to 2 and back again
setTimeout(mf,3000);
}
mf(); // kick off the first iteration of the slideshow
</script>
Related
I am trying to have an image, once clicked move on to image 2, then once image 2 is clicked it moves on to image 3, then image 4 and so on, but I am struggling to find a way to have more than 2 images? So far I have tried various different ways such as repeating the code I already have, using multiple if statements and switch statement but I just cannot seem to be able to use more than 2 images. I am only a beginner coder so it is difficult to see where I am going wrong. the expected outcome would be just to have a number of images appearing after each one is clicked.
So far the code that I have that's working is:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Social Media</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<script type="text/javascript">
var mysrc = "image1.jpg";
function changeImage() {
if (mysrc == "image1.jpg") {
document.images["pic"].src = "image1.jpg";
document.images["pic"].alt = "image1";
mysrc = "image.jpg";
}
else {
document.images["pic"].src = "image.jpg";
document.images["pic"].alt = "image";
mysrc = "image1.jpg";
}
}
</script>
</head>
<body>
<img src="image.jpg"
alt="image" id="pic" class="portrait"
onclick="changeImage()"
width="1000px" height="500px"
style="cursor:pointer">
</body>
</html>
and i have been able to get the same results by doing:
function change() {
var image = document.getElementById('image');
image.src = "image1.jpg"
}
</script>
</head>
<body>
<img src="image.jpg" alt="text" id="image" onclick="change();">
but i just cant seem to get more than 2 images? as mentioned I am just a beginner so I'm really not sure if it's just me making stupid mistakes, any advice would be really helpful
You should be to do this using an array and a simple variable counter.
var imgCount = 0;
var images = ["img1.png", "img2.png", "img3.png", "img4.png"...];
imgCount will get added to every time <img> is clicked.
<script>
var imgCount = -1;
var images = ["img1.png", "img2.png", "img3.png", "img4.png"...];
function change() {
imgCount++;
var image = document.getElementById('image');
image.src = images[imgCount];
}
</script>
<img src="image.jpg" alt="text" id="image" onclick="change()">
The src is now called from the array. imgCount serves as the counter of the amount of times the image has been clicked and is used to find the correct src with the array since it also serves as an index.
If you don't know much about arrays read MDN.
I'm sure that you don't have an endless amount of pictures, so you can also use this:
<script>
var imgCount = -1;
var images = ["img1.png", "img2.png", "img3.png", "img4.png"];
function change() {
if (imgCount !== images.length - 1)
imgCount++;
else
imgCount = 0;
var image = document.getElementById('image');
image.src = images[imgCount];
}
</script>
<img src="image.jpg" alt="text" id="image" onclick="change()">
Now, if <img> is clicked and it is on the last image, it will go back to the beginning. The if statement sees whether or not the counter equals the amount of images in the array. If it hasn't it keeps adding. If it hasn't, it sets the counter back to 0.
I'm sorry, I'm very new to JS but I need it for work...
Can you just quickley tell me what is wrong with this script? I just want the div box to be visible every second time when someone loads the page...
<body onload="script();">
<script type="text/javascript">
var random = Math.floor(Math.random() * 2) + 1 ;
if (random<1) {
document.getElementById('ele').style.display = 'block';
};
</script>
<div style="display: none;" id="ele">Div-Box<br />
</div>
</body>
Cheers,
Till
Using random won't guarantee that the div will be shown every second time the page is loaded. To do that you need to keep track of how many times a user has opened the page. You can do this in localStorage.
<body>
<script>
var viewCount = localStorage.getItem('viewCount') || 1; // default to 1 the first time
if (viewCount % 2 === 0) { // if it's an even number
document.getElementById('ele').setAttribute('style', 'display: block');
}
</script>
</body>
Apart from your logic you are calling script() function on onload but it is not defined.
<body onload="script();">
<script type="text/javascript">
function script(){
var random = Math.floor(Math.random() * 2) + 1 ;
console.log(random);
if (random>1) {
document.getElementById('ele').style.display = 'block';
};
}
</script>
<div style="display: none;" id="ele">Div-Box<br />
</div>
</body>
I was looking in other posts for the answer, but the answers never seem to work in my favor. I'm trying to make an image fade when the page finishes loading. I've figured out I can loop until the counter reaches 0 (when image is invisible) and fade the image slowly.
The problem is, the setTimeout() function doesn't seem to be working.
Here's the code:
function timeout() {
setTimeout(function () {
//A comment said something about looping,
//but it was confusing to understand...
}, 50);
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 0 //Start at being visible
for (var i = 10; i > 0; i = i - 0.1) { //For loop
load.style.opacity = i; //Use the index variable and use that to set the opacity
setTimeout(); //Set the timeout, but this function does not pause the program for some reason...
//I need to pause for 0.05 seconds.
}
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
I put the javascript in a seperate file, I just can't access it from Stack Overflow...
Can someone help? And also, sometimes the image can be finicky at times as well, like sometimes it won't hide like it's supposed to do. Thanks!
You declared a setTimeout without arguments, hence the error:
'Window': 1 argument required, but only 0 present."
Give it the appropriate amount of arguments:
for (var i = 10; i > 0; i = i - 0.1) { //For the loop
load.style.opacity = i;
setTimeout(functionName, milliseconds);
}
If you intended to use your timeout() function instead, call it. You're just instantiating a new setTimeout from the one you already created in the timeout() function.
You can use a recursive function instead of a loop
var load = document.getElementById('img');
function setup() {
load.style.opacity = "1"; //Start at being visible
timeout(1);
}
function timeout(i) {
setTimeout(function() {
i -= 0.1;
if(i<=0)
return;
load.style.opacity = i.toString();
timeout(i);
}, 200);
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div>
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150" id="img">
</div>
</body>
</html>
Basically you want to countdown the opacity with a recursive call. Here we are going from 1 down to 0 in 0.01 increments. The setTimeout will trigger the next recursive call after pausing for 50 msecs. These values, can of course, be adjusted as needed but the opacity needs to be a number from 1 (visible) to 0 (invisible).
function setOpacity(el, lvl) {
el.style.opacity = lvl;
}
function countDown(el, lvl) {
function action(el, lvl) {
return function () {
countDown(el, lvl);
}
}
setOpacity(el, lvl);
if (lvl > 0) {
lvl -= 0.01
setTimeout(action(el, lvl), 50);
}
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 1; //Start at being visible
countDown(load, 1);
}
window.addEventListener('load', setup, true);
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
function setup() {
var load = document.getElementById('img');
(function(){
var i = 1;
setTimeout(function () {
i -= 0.1;
load.style.opacity = i;
if (i > 0) {
setTimeout(arguments.callee, 100);
}
}, 100);
})();
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
I'm relatively new into html, css and javascript. So far, I have a landing page with a thumbnail gallery. For different reasons, every thumbnail is located in a different div. I used javascript to make the thumbnail change when I click inside the div, and the thumbnail changes. The problem is: when I change to another div I need to click two times to make the script start working.
My html and js code is:
<div id="thumb1" class="fluid"><img src="img/image2.jpg" img id="img1" alt=""/></div>
<script type="text/javascript">
var images = ["img/image1.jpg",
"img/image2.jpg",
"img/image3.jpg"
],
i = 1;
for (var j=images.length; j--;) {
var img = new Image();
img.src = images[j];
}
document.getElementById('img1').addEventListener('click', function() {
this.src = images[i >= images.length - 1 ? i = 0 : ++i];
}, false);
</script>
<div id="thumb2" class="fluid"><img src="img/imageC.jpg" img id="img2" alt=""/></div>
<script type="text/javascript">
var images2 = [
"img/imageA.jpg",
"img/imageB.jpg",
"img/imageC.jpg",
"img/imageD.jpg"
],
i = 1;
for (var j=images2.length; j--;) {
var img2 = new Image();
img2.src = images2[j];
}
document.getElementById('img2').addEventListener('click', function() {
this.src = images2[i >= images2.length - 1 ? i = 0 : ++i];
}, false);
</script>
Is there a way to convert this two scripts (or more) into only one in a simple an easy way? Right now, the script is the same but I don't feel like duplicating the script each time for every div is the most reasonable way to proceed. Moreover, since I will need more than two div, like nine or ten... I don't want a bunch of useless code...Any help would be appreciated. Thank you very much.
You could use this solution, where you put all your images inside every div, but every time, all the images are hidden except one, and the onClick listener changes the display property.
<html>
<body>
<script type="text/javascript">
function getOnlyImagesFromArray(nodeList) {
var onlyImagesArray = [];
var nodeListAsArray = Array.prototype.slice.call(nodeList, 0);
nodeListAsArray.forEach( function(element) {
if(element.localName == 'img') {
onlyImagesArray.push(element);
}
});
return onlyImagesArray;
}
function handleClick() {
// using JQuery here would be much cleaner, but out of shear lazyness, I've created the helper function "getOnlyImagesFromArray"
var onlyImages = getOnlyImagesFromArray(this.childNodes);
var visibleIndex = -1;
for(var i = 0; i < onlyImages.length; i++) {
if(onlyImages[i].style.display == 'inline') {
visibleIndex = i;
break;
}
};
onlyImages[visibleIndex].style.display = "none";
onlyImages[visibleIndex >= onlyImages.length - 1 ? visibleIndex = 0 : ++visibleIndex].style.display = "inline";
}
</script>
<div id="thumb1" class="fluid">
<img src="img/image1.jpg" img id="img1" alt="" style="display:none"/>
<img src="img/image2.jpg" img id="img1" alt="" style="display:inline"/>
<img src="img/image3.jpg" img id="img1" alt="" style="display:none"/>
</div>
<script type="text/javascript">
document.getElementById('thumb1').addEventListener('click', handleClick, false);
</script>
<div id="thumb2" class="fluid">
<img src="img/imageA.jpg" img id="img2" alt="" style="display:none"/>
<img src="img/imageB.jpg" img id="img2" alt="" style="display:none"/>
<img src="img/imageC.jpg" img id="img2" alt="" style="display:inline"/>
<img src="img/imageD.jpg" img id="img2" alt="" style="display:none"/>
</div>
<script type="text/javascript">
document.getElementById('thumb2').addEventListener('click', handleClick, false);
</script>
</body>
</html>
Your problem is that when you use var inside an inline script, it always create it in main scope (i.e. window).
e.g.:
<script type="text/javascript">
var i = 1;
//...your code
</script>
<script type="text/javascript">
var i = 2;
//...your code
</script>
Both scripts assign value into window.i which will be equal to 2 in both scripts.
To make it separate, wrap each script into a function like this:
<script type="text/javascript">
(function() {
var i = 1;
//...your code
})();
</script>
<script type="text/javascript">
(function() {
var i = 2;
//...your code
})();
</script>
Or simple instead of i use something more specific, e.g. imageIndex1 and imageIndex2.
More experienced developers may write it like this, which is a bit shorter but less readable for beginners:
<script type="text/javascript">
(function(i) {
//...your code
})(1);
</script>
<script type="text/javascript">
(function(i) {
//...your code
})(2);
</script>
I have many div tags.
I am trying to display only one tag at a time for 10 seconds.
That is, when div1 is being displayed, div2,div3..divn must be hidden, after 10 seconds div2 has to be displayed for 10 seconds and other div tags has to be hidden and so on.
Its a kind of cyclic manner.
Kindly help.
Check out the sample html here:
<html>
<head>
......
.......
</head>
<body>
<div id="div1">
........
......
</div>
<div id="div2">
........
......
</div>
..
..
<div id="divn">
........
......
</div>
</body>
</html>
Regards,
abk
This should work: http://jsfiddle.net/Z5uMV/
var current = 1;
function cycle() {
$('#div' + current).fadeOut(function() {
current++;
if(current > 10) current = 1;
$('#div' + current).fadeIn(function() {
setTimeout(cycle, 10000);
}
});
}
cycle(); // start it
You can use setInterval
Live Demo
var myVar=setInterval(function(){myTimer()},1000);
var index=1;
totalDivs = $('[id^=div]').length;
$('[id^=div]').hide();
function myTimer()
{
$('[id^=div]').hide();
$('#div'+ index++).show();
if(index > totalDivs)
index = 0;
}