JavaScript trying to change image - javascript

There are four files at the same folder directory
- 1.jpg
- 2.jpg
- index.html
- 1.js
I am hoping to write the code so it will load 1.jpg at first, but it will load 2.jpg next
The JavaScript is
var img = new Image(); // Create new img element
img.src = '2.jpg';
var getElementIMG = document.getElementById("imageid");
getElementIMG.src = img.src;
And the HTML is
<img id="imageid" src="1.jpg">
but when the page finishes loading it still displays 1.jpg

Try this:
<!doctype html>
<html>
<body>
<img id="imageid" src="1.jpg">
<script>
var getElementIMG = document.getElementById("imageid");
getElementIMG.src = '2.jpg';
</script>
</body>
</html>

If your Javascript is on the header you need to specify when do you want the image to be replaced, which is when it exists.
After the window has been loaded:
window.onload = function () {
document.getElementById("imageid").src = "2.jpg";
}
Demo: http://jsfiddle.net/5a6Jx/2/
Or you can just stick the script at the end of the page:
<img id="imageid" src="1.jpg" />
<script type="text/javascript">
document.getElementById("imageid").src = "2.jpg";
</script>
On both ways your image will be there already, so you can manipulate it.

<head> <script type="text/javascript" src="1.js"></script> </head>
The script is loaded in the head and executed immediately. There is no element '#imageid', so document.getElementById returns null. An error is probably thrown on the getElementIMG.src = img.src; line. If something doesn't work, one of the first things you should do is check for errors in the debugger/console. (F12 in most browsers.)
Later on the page, the browser sees an image. It displays it.
What you want to do is load the script after the image. If you put it at the end of the page, the <img> will be seen by the browser, and only after that, its src will be changed.

You will have to make your move when the document and your image are both loaded.
window.onload = function () {
var img = new Image();
img.src = '2.jpg';
img.onload = function() {
var getElementIMG = document.getElementById("imageid");
getElementIMG.src = img.src;
}
}

Related

how to change an image source more than once using onclick on html and javascript

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.

Changing the src of an image with JavaScript does not cause the image to change

I am trying to toggle an image if I click on it. The JavaScript does seem to replace the image, however, the updated image does not appear on the screen. Here is my HTML code:
<!DOCTYPE html>
<html>
<script src="myscript.js" defer></script>
<div><img id="light" src="images/light_off.png" width="200px"></div>
</html>
and my JavaScript code:
var light_src = document.getElementById('light').src;
var image = light_src.substring(light_src.lastIndexOf("/")+1);
light.addEventListener("click", function(){
if (image == "light_off.png"){
alert("1");
light_src = "file:///H:/mydir/images/light_on.png";
}
else {
alert("2");
light_src = "file:///H:/mydir/images/light_off.png";
}
});
The source does seem to be changing because each time I click on the image, the alert toggles between 1 and 2. However, the image does not appear to change on the screen.
I have verified that both images work by copying the URL into the browser address bar.
What am I doing wrong?
The problem is that you're changing the value of light_src, not the element's source. In other words, light_src is a copy of the source, and changing it does not change the images source.
Instead of storing the source in a variable, you should just store the image element, like this:
// The image URLs
const imageOn = 'file:///H:/mydir/images/light_on.png'
const imageOff = 'file:///H:/mydir/images/light_on.png'
// Store the image element to use later
const imageElement = document.getElementById('light')
// Add the event listener
imageElement.addEventListener("click", function() {
if (imageElement.src === imageOn) {
imageElement.src = imageOff
console.log('Switched light off')
} else {
imageElement.src = imageOn
console.log('Switched light on')
}
});
Dont use .src with the selector
var light=document.getElementById('light');
var image = light.src.substring(light.src.lastIndexOf("/")+1);
light.addEventListener("click", function(){
if (image == "light_off.png"){
console.log(light.src);
light.src = "file:///H:/mydir/images/light_on.png";
}
else {
console.log(light.src);
light.src = "file:///H:/mydir/images/light_off.png";
}
});
<!DOCTYPE html>
<html>
<script src="myscript.js" defer></script>
<div><img id="light" src="images/light_off.png" width="200px" alt="image"></div>
</html>

Add Links to Images in a Script

This script replaces the background of the DIV 'middle' with the images listed in the array. Currently the script works perfect but I want to be able to assign a link to each image, tried just replacing with but then the image doesn't show up nor does the link work.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg');
var nextimage=0;
doSlideshow();
function doSlideshow(){
if(nextimage>=images.length){nextimage=0;}
$('.middle')
.css('background-image','url("'+images[nextimage++]+'")')
.fadeIn(500,function(){
setTimeout(doSlideshow,5000);
});
}
</script>
What I'm looking for is something like this.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg'); To: var images=new Array('<img src="/images/home/imgone.jpg"', '<img src="/images/home/imgtwo.jpg"', '<img src="/images/home/imgthree.jpg"', '<img src="/images/home/imgfour.jpg"', '<img src="/images/home/imgfive.jpg"');
</script>
Although this does not fully answer your question, maybe you can get some ideas from DOM functions.
Example
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.body.appendChild(image);
</script>
This appends an image to the body. If you would like to add it to a specific ID, you could do the following (assuming your div id is "destination").
Example
<!DOCTYPE html>
<html>
<body>
<div id="destination">
<!-- Destination Div -->
</div>
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.getElementById("destination").appendChild(image);
</script>
</body>
</html>
Good luck!

Paperclip image set within script tags shows the image text url not the image - expandablebanners.js

I'm using expandablebanners.js on a rails site, the code I have to display the rollover image is;
<script type="text/javascript">
var roll_img = "<%= #advert.roll_img.url %>"
var squarecenterbottom = ExpandableBanners.banner("squarecenterbottom", roll_img);
squarecenterbottom.animated = true;
squarecenterbottom.setDirection('down', 'center');
squarecenterbottom.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
the main image is displayed on the page as so;
<%= link_to image_tag(#advert.img(:horizontal) title: #advert.name,),
#advert.target_url, :id => 'squarecenterbottom' %>
when you rollover the main image it should show the rollover image but
when I rollover the image it just shows the rollover image's url (i.e as text), I don't know what the problem is....
the code output is;
<script type="text/javascript">
var roll_img = "http://localhost:3000/system/adverts/large_imgs/000/000/004/original/1n.jpg?1401967781"
var squarecenterbottom = ExpandableBanners.banner("squarecenterbottom", roll_img );
squarecenterbottom.animated = true;
squarecenterbottom.setDirection('down', 'center');
squarecenterbottom.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
<img alt="test22" height="90" src="/system/adverts/imgs/000/000/004/horizontal/2n.jpeg?1401818651" title="test22" width="730" />
</div>
and this is the code from the documentation that shows how it works;
<script type="text/javascript">
var squaretopleft = ExpandableBanners.banner("squaretopleft", "images/square_expanded.jpg");
squaretopleft.setCloseImage("images/closebutton.jpg", 'left', 'top');
squaretopleft.animated = true;
squaretopleft.setDirection('up', 'left');
squaretopleft.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
</head>
<body>
<a id="squaretopleft" href="www.yourwebsite.com"><img src="images/square.jpg" /></a>
</body>
</html>
This might be a path or HTML structure problem.
Things to check:
In your output, your <a> element comes right after <script>. Then there is a </div> closing tag. Do you have an opening <div> before all? Are they all in the <body>?
Since ExpandableBanners code sets up onload and DOMContentLoaded listeners, try moving that in the <head> of the document.
Your original image has .jpeg extension and roll image has .jpg. Nothing wrong with this but make sure you have the correct images (and extensions) in the right paths. e.g. original image is under /imgs folder and roll is under /large_imgs. Is this ok?
Try relative path for your roll image. In this case: remove http://localhost:3000 in the beginning. (Assuming your original image is showing ok.)
Few points:
Missing semicolon at the end of var roll_img... declaration
As Ruby Racer mentioned, the generated anchor tag is missing double quote <a href="www.example.com

How can i return img.src by clicking on an image with javascript?

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>

Categories