I'm making a slideshow in javascript for a class assignment and I have the slideshow working but it's not displaying the images. I can see that the image icon changes but the actual image is not showing.
<script type="text/javascript">
//put images in array
var pics = new Array();
pics[0] = new Image();
pics[0].src = "images/forest.jpg";
pics[1] = new Image();
pics[1].src = "images/mountains.jpg";
pics[2] = new Image();
pics[2].src = "images/nature.jpg";
pics[3] = new Image();
pics[3].src = "images/snowtops.jpg";
var index = 0; //start point
var piclength = pics.length - 1;
function slideshow() {
document.slide.src = pics[index];
if (index < piclength) {
index++;
}
else {
index = 0;
}
}
function slide() {
setInterval(slideshow, 3000);
}
</script>
<body onload="slide()">
<h1>Nature Photography</h1>
<main>
<section>
<p>I am an enthusiastic about nature photography. Here is a slideshow of my
works.</p>
<aside> <img id="myImage" src="images/forest.jpg" name="slide" width="95%">
</aside>
First, I would put the script tag after your HTML. This will allow you to cache DOM elements without waiting for the "DOMContentLoaded" event or the "load" (window) event to be fired.
Second, you should cache the "myImage" element. Something like const slider = document.getElementById('myImage').
Third, check your console. Maybe your image URLs are wrong? And make sure your HTML is valid. From what you posted, you are missing a lot of things (doctype, html/head tags, you didn't close body tag and similar)
Related
I'm using this code to build a gallery:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
[].forEach.call(image,function(x){
x.onmouseover = function(){
mainImage.src = x.src;
};
});
}
The code loads different thumbnails on the big image when "onmouseover". Now I would like to "preload" the first image from that gallery of thumbnails. I tried using onload with
rr_lrg_img.src=document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img')[0].src
but then it conflicts with the onmouseover. Any ideas? I can only use javascript, no jquery.
Since your var image is actually a collection of images, you need to use the [0] index pointer to target the first one:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
mainImage.src = image[0].src; // Add this line (preload first image into main one)
function toMainImage() {
mainImage.src = this.src;
}
[].forEach.call(image,function(x){
x.addEventListener("mouseenter", toMainImage, false);
});
}
.thumbnails img{height:50px;}
<img src="//placehold.it/200x200&text=default" id="rr_lrg_img">
<div class="thumbnails">
<img src="//placehold.it/200x200/cf5&text=1">
<img src="//placehold.it/200x200/f0f&text=2">
<img src="//placehold.it/200x200/444&text=3">
</div>
I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>
I'm working on making a JS script that will go in the header div and display a few pictures. I looked into JQuery Cycle, but it was out of my league. The code I wrote below freezes the browser, should I be using the for loop with the timer var?
<script type="text/JavaScript" language="JavaScript">
var timer;
for (timer = 0; timer < 11; timer++) {
if (timer = 0) {
document.write('<img src="images/one.png">');
}
if (timer = 5) {
document.write('<img src="images/two.png">');
}
if (timer = 10) {
document.write('<img src="images/three.png">');
}
}
</script>
Thanks!
Assuming you want a script to rotate images and not just write them to the page as your code will do, you can use something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="target"></div>
<script>
var ary = ["images/one.png","images/two.png","images/three.png"];
var target = document.getElementById("target");
setInterval(function(){
target.innerHTML = "<img src=\""+ary[0]+"\" />";
ary.push(ary.shift());
},2000);
</script>
</body>
</html>
Of course the above code has no effects (like fading) which jQuery will give yous, but it also doesn't require loading the entire jQuery library for something so basic.
How about just running the script after the page loads?
<script>
// in <head> //
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
}
</script>
Then use <body onload="load();"> to run the script.
Edit
To add in a delay loading images, I rewrote the code:
<script>
// in <head> //
var displayOnLoad = true; // Set to true to load the first image when the script runs, otherwise set to false to delay before loading the first image
var delay = 2.5; // seconds to delay between loading images
function loadImage(url) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
setTimeout(loadImage(images[i]), (i+displayOnLoad)*(delay*1000));
}
}
</script>
Set displayOnLoad = false; if you want to wait the specified delay before loading the first image. The delay is set in seconds. I recommend waiting over a single second between images, as they may take some time to download (depending on the user's internet speed).
As with the first snippet, I haven't tested the code, so please tell me if an error occurs, and I will take a look.
Since you used the jquery tag on your question, I assume you are OK with using jQuery. In which case, you can do something like this:
In your static HTML, include the img tag and set its id to something (in my example, it's set to myImg) and set its src attribute to the first image, e.g.:
<img id="myImg" src="images/one.png">
Next, use jQuery to delay execution of your script until the page has finished loading, then use setTimeout to create a further delay so that the user can actually spend a few seconds looking at the image before it changes:
<script>
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
$(function() {
// Document is ready
setTimeout(function() {
// We will get here after the first timer expires.
// Change the image src property of the existing img element.
$("#myImg").prop("src", "images/two.png");
setTimeout(function() {
// We will get here after the second, nested, timer expires.
// Again, change the image src property of the existing img element.
$("#myImg").prop("src", "images/three.png");
}, imgTimeoutMsecs);
}, imgTimeoutMsecs);
});
</script>
Of course, that approach doesn't scale very well, so if you are using more than three images total, you want to modify the approach to something like this:
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
// Array of img src attributes.
var images = [
"images/one.png",
"images/two.png",
"images/three.png",
"images/four.png",
"images/five.png",
];
// Index into images array.
var iCurrentImage = 0;
function cycleImage() {
// Increment to the next image, or wrap around.
if (iCurrentImage >= images.length) {
iCurrentImage = 0;
}
else {
iCurrentImage += 1;
}
$("#myImg").prop("src", images[iCurrentImage]);
// Reset the timer.
setTimeout(cycleImages, imgTimeoutMsecs);
}
$(function() {
// Document is ready.
// Cycle images for as long as the page is loaded.
setTimeout(cycleImages, imgTimeoutMsecs);
});
There are many improvements that can be made to that example. For instance, you could slightly simplify this code by using setInterval instead of setTimer.
The code you've provided simply iterates through the for loop, writing the images to the browser as it does so. I suggest you take a look at JavaScript setTimeout function.
JS Timing
I have set of images named as img1, img2, img3, img4,......., imgx. So, I want to code a JavaScript to display an image img1 at document.onload() and on first click image to be changed to img2 next on second click the image to be changed at img3 and then same to the next image on every NEXT button click. In this manner I need even PREVIOUS button to go back to the previously viewed images.
How to implement this?
var currentImage = 1;
window.onload = function() {
showImage();
};
document.getElementById("next").onclick = function() {
currentImage++;
showImage();
}
function showImage() {
document.getElementById("image").src = "img" + currentImage + ".jpg";
}
These are the basics and should help you get started. If you need help implementing the rest, ask us what you want to do specificially and what you tried. Hint, you'll need to handle the case where there is no "next" image to show. Do you want it to come back to the beggining or just not work?
<script type="text/javascript">
var images = new Array("img/image1.jpg", "img/image2.jpg", "img/image3.jpg");
var cur_image = 0;
function goNextImage() {
var img = document.getElementById('image');
cur_image++;
if (cur_image == images.length) {
cur_image = 0;
}
img.src = images[cur_image];
}
</script>
<img src="img/image1.jpg" id="image" onclick="goNextImage()" />
I'm trying to create a script for creating an overlay containing an image and some text, but i've run into some problems
1st: the image in the overlay doesn't appear when first clicked, but does on subsequent openings.
2nd: the scrollTo function only works if put in a timeout, otherwise it appears to do nothing.
If anyone could shed any light on this, or any other mistakes i've made, it would be much appreciated.
javascript:
var scrollY;
var i_w;
var i_h;
function showOverlay(filepath,num){
scrollY = document.body.scrollTop || document.documentElement.scrollTop;
hideOverlay();
document.getElementById("num").innerHTML ="image #: " + num + " click image to close";
var preload = new Image();
preload.src = filepath;
i_w = preload.width;
i_h = preload.height;
document.getElementById("blowup").width = i_w;
document.getElementById("blowup").height = i_h;
document.getElementById("blowup").src = filepath;
document.getElementById("overlay").style.display = "inline";
setTimeout("window.scrollTo(0,scrollY)",1);
setOverlayBounds(); //a function to orient the overlay div.
}
html:
<div id="overlay">
<center>
<img id="blowup" src="#" onClick="javascript:hideOverlay()">
<br>
<p id="num"></p>
<br>
</center>
</div>
css:
#overlay
{
display:none;
position:absolute;
background-color:#999;
border:medium;
border-color:#0F0
}
You should use the load event for the image to make sure, it finished loading before you execute your code. Also, you shouldn't use strings in connection with setTimeout. It's better to pass the function directly:
var preload = new Image();
preload.src = filepath;
preload.onload = function() {
i_w = preload.width;
i_h = preload.height;
document.getElementById("blowup").width = i_w;
document.getElementById("blowup").height = i_h;
document.getElementById("blowup").src = filepath;
document.getElementById("overlay").style.display = "inline";
setTimeout(function(){window.scrollTo(0,scrollY);},1);
setOverlayBounds(); //a function to orient the overlay div.
};
This should at least fix your first issue.