How to switch 4 images using a button - javascript

<html>
<head>
<title>How To Insert an Image</title>
<script>
function changeImage(){
var img = document.getElementById('image');
image.src='image4.jpg';
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
I am quite new to Javascript so please dont be too harsh. Basically im trying to switch from one picture to another using a button. So far with this code i have only managed to do 2 images but when i try to add a 3rd or 4th the first image messess up. I was hoping if someone could help me fix this problem.

Here's simplest approach the I used before, for two images. Easily extended to accomodate three, four, or more alternate images.
<div id="image1">
<img ... >
<button ...>
</div>
<div id="image2" style="display: none">
<img ... >
<button ...>
</div>
That is, put the first image, and a button, inside a "< div >" element, and a second image, and a button inside a second "< div >" element that's initially hidden.
Then, each button's javascript simply needs to set its own div's CSS style to "display: none", and remove this style from the other div element, effectively hiding one image, and displaying the other one.
This approach also makes it possible to update the button's text or label, accordingly. If both buttons have the same label, the only apparent result is the image change.

Try this script block instead:
<script>
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg']
function changeImage() {
var img = document.getElementById( 'image' )
var url = images.shift() // remove first url from list
image.src = url // use it
images.push( url ) // append url to the end of the list
}
</script>

What you could do is declare an array which contains all your image urls:
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
Then when clicking the button, you remove the first image url from the the array by using shift and assign that to variable imageUrl.
Then you set that imageUrl to the src attribute of the image element on your page.
Then you add that imageUrl at the end of the array using push.
This will rotate the images in the imageUrls array on every click.
<html>
<head>
<title>How To Insert an Image</title>
<script>
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>

You were very close! You just made mistake to assign a value to image.src instead of img.src. have a look at the code below :)
Using clicks:
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}
</script>
</head>
<body>
<img id="image" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" height="100px" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
Automatic image slider
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
setInterval(function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}, 5000)
</script>
</head>
<body>
<img id="image" src="image1.jpg" height="100px" />
</body>
</html>

Related

simple slide show in JS- buttons are not working properly

I want to create a basic page in html that displays a single image.
I also added two buttons Previous and Next. These buttons should allow the user to move forward or backward. Have 6 images in total. When the user reaches the end (or beginning when clicking on the back button) of the slide show, the slide show should not wrap around to the beginning (or end).
button onclick function for both the cases is not working. Its only getting displayed the first image as what mentioned in the img src attribute.
This is what I have done so far. I put all the images into an array and try to travel the array forward and backward side based on the button click.
<body>
<img src="img1.jpg" id="demo" style="width:400px;height:600px"/img>
<br/>
<input type="button" onclick="preImage()" value="Previous
">
<input type="button" onclick = "nextImage()" value="Next
">
<script>
var slider_content = document.getElementById("demo");
var image = ['img1','img2','img3','img4','img5','img6'];
var i = image.length;
function nextImage(){
if(i<image.length){
i=i+1;
}else{
i=1;
}
slider_content.innerHTML="<img src="+image[i-1]+".jpg>";
}
function preImage(){
if(i<image.length+1 && i>1){
i=i-1;
}else{
i=image.length;
}
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
}
</script>
</body>
Create a wrapper div to your image and change the innerHTML of the div.
<div id="demo" style="width:400px;height:600px">
<img src="img1.jpg">
</div>
An error needs to be corrected in the preImage function:
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
to
slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
and also what Daniel said.

href javascript is not working on my image

I'm adding images stored in firebase to my html page from the database. That works and the image shows up, but I am unable to make the href property work on the img element. I want it to be clickable. Suggestions what I am doing wrong here?
var img = document.createElement("img");
img.src = snapshot.child("urlToImage " + (i) + " Content").val();
img.href = snapshot.child("urlToImage " + (i) + " Content").val();
img.height = 30;
img.width = 30;
contentA[i].appendChild(img);
Clickable image
function clickMe(){
alert('Clicked!');
}
<!DOCTYPE html>
<html>
<body>
An image as a link:
<a onclick="clickMe()">
<img src="https://s3.eu-central-1.amazonaws.com/live-resource/productCategories/HF-AT/HF_PRINT_WEB_F781A5E7-1575-4D81-8317-BC51C8653EBB.jpeg" border="0" alt="W3Schools" src="logo_w3s.gif" width="100" height="100">
</a>
</body>
</html>
You have to wrap the img element in an a tag.
<a href='urlToImage'><img src='urlToImage' /></a>
You can of course have an href attribute on an img if you want to, it just doesn't have any special default meaning to browsers like it would on an anchor
Is href a valid attribute of img? I've never seen that before. If you want it to be clickable just wrap it in a anchor.

JS photogallery. Getting the big image to display and and thumbnails to be clickable

I have a quick issue that I need help with and hoping a fresh set of eyes can pinpoint my issue. I have a photo gallery and I want to display a larger image of the thumbnail when it is clicked. The thumbnails images show up fine at the bottom but are not clickable and the main (or larger image) does not show up. I am using an external .js file. I will upload the HTML also, and maybe some one can point me in the right direction and help me understand what I am overlooking.
<!doctype html>
<html>
<head>
<title>Photo Gallery Final Project</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" href = "gallery.css">
</head>
<body>
<div class = "main">
<div class = "wrapper">
<div id = "largeImage">
<img src = "images/machine_1_big.jpg" alt = "machining image" width = "920" height = "400" id = "myImage" class = "border"/>
</div>
<div class = "thumbnail">
<img src="machine_1.jpg" alt = "machining lathe" id="machine_1"/>
<img src="machine_2.jpg" alt = "machining lathe" id="machine_2"/>
<img src="machine_3.jpg" alt = "machining lathe" id="machine_3"/>
<img src="machine_4.jpg" alt = "machining lathe" id="machine_4"/>
<img src="machine_5.jpg" alt = "machining lathe" id="machine_5"/>
<img src="machine_6.jpg" alt = "machining lathe" id="machine_6"/>
</div>
</div>
</div>
<script src = "gallery.js"></script>
</body>
</html>
//this will load the gallery in the browser and enable the gallery function
//window.onload = gallery;
//gallery funtion declared
function gallery(){
//variable allGalleryImages created. This is where all the images will be held
var allGalleryImages = document.images;
//for loop declared for the image array
for(var i = 0; i < allGalleryImages.length; i++){
if(allGalleryImages[i].id.indexOf("small") > -1){
//this will add a listener to the thumb images
allGalleryImages[i].onclick = imgChanger;
}
}
}
//this is the image changer function
function imgChanger(){
//this will change the src attribute value of the large image.
//document.getElementById('myImage').src ="images/"+this.id+"_big.jpg";
document.getElementById('myImage').src = " " + this.id +"_big.jpg";
}
I used JQuery. Did not have to change your HTML. And there is no reason to make and array of all the thumbnails.
$(document).ready(function() {
$(".thumbnail img").on("click", function() {
imgChanger($(this).attr("src"));
})
//this is the image changer function
function imgChanger(theSRC) {
//this will change the src attribute value of the large image.
//document.getElementById('myImage').src ="images/"+this.id+"_big.jpg";
var beforeJPG = theSRC;
console.log(beforeJPG);
beforeJPG = beforeJPG.substring(0, beforeJPG.length-4);
console.log(beforeJPG + "_big.jpg");
$("myImage").attr("src", beforeJPG + "_big.jpg");
}
})
Fiddle: https://jsfiddle.net/6v8arhp2/
Get the src of the clicked image
Chop off ".jpg"
Add "images/" to the front, add "_big.jpg" to the back
Change src of #myImage
** Of course your images are not inside JSFiddle so you cannot see it work, but the console logs show the transformation.

How To Change Image And Link On Click As Toggle Function?

I want a Pure JavaScript code that will change an image and also its link to another image and another link on same place as toggle function. I have a web page and I have Anchors Links button as <img src="DownArrow.png"/> and I want that after clicking on this image, first it will lead you to the DIV2 and then it will change the code to <img src="UpArrow.png"/>. How to do this using pure JavaScript? Waiting for perfect reply and code?
This should work:
var link = document.querySelector('#arrow a');
link.onclick = function() {
var image = document.querySelector('#arrow a img');
if(this.href.slice(-1) === '1') {
this.href = '#DIV2';
image.src = 'https://cdn1.iconfinder.com/data/icons/nuvola2/48x48/actions/1uparrow.png';
} else {
this.href = '#DIV1';
image.src = 'https://cdn1.iconfinder.com/data/icons/nuvola2/48x48/actions/1downarrow.png';
}
}
See it in action here: http://jsfiddle.net/TM9ap/7/
Note that I've changed the href attribute in the link to #DIV1 like this <a href="#DIV1">
<!DOCTYPE html>
<html>
<title></title>
<head></head>
<body>
<a href = "#DIV1" style="color:BLACK;" onclick="execute();">Click me
<img src="UpArrow.png" />
</a>
<div id="DIV1" ></div>
<div id="DIV2" ></div>
<script>
function execute()
{
if ( document.getElementsByTagName("a")[0].getAttribute("href")==="#DIV1"){
var img = document.getElementsByTagName("img")[0];
img.setAttribute("src","DownArrow.png");
img.parentNode.setAttribute("href","#DIV2");
}
else
{
var img = document.getElementsByTagName("img")[0];
img.setAttribute("src","UpArrow.png");
img.parentNode.setAttribute("href","#DIV1");
}
}
</script>
</body>
</html>

javascript image rollover inside div

i have a single div 100px X 300px. What's the easiest way in JavaScript so when I hover over the div i show an image and then when i leave the div the image disappears.
for starters i thought the following would get me started but i can't seem to remove the image properly
<script type="text/javascript">
function MouseOver_Event(elementId) {
var imgToCreate = document.createElement('img');
imgToCreate.setAttribute('id', 'imgHandle');
imgToCreate.setAttribute('src', elementId + '.png');
imgToCreate.setAttribute('onmouseout', 'MouseOut_Event('+elementId+')');
var targetDiv = document.getElementById(elementId);
targetDiv.appendChild(imgToCreate);
targetDiv.removeAttribute('onmouseover', 'MouseOver_Event');
}
function MouseOut_Event(elementId) {
var imgToRemove = document.getElementById('imgHandle');
var targetDiv = imgToRemove.parentNode();
if (imgToRemove != null)
targetDiv.removeChild(imgToRemove);
targetDiv.setAttribute('onmouseover', 'MouseOut_Event(' + elementId + ')');
}
</script>
</head>
<body>
<div id="div1" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div2" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div3" onmouseover="MouseOver_Event(this.id)"><img src="Div3.png" alt="test" onmouseout="MouseOut_Event(parentNode's id or something)" /></div>
</body>
You're attaching your MouseOut_Event to onmouseover instead of onmouseout. But you probably don't need to be messing with dynamic event creation anyway; just add onmouseout="MouseOut_Event(this.id)" to the three divs and that should do it.
Why don't you use CSS instead ?
For example:
#div1{background:none;}
#div1:hover{background:url('src/div1.png') no-repeat;}

Categories

Resources