javascript function changeimage() - javascript

I have a problem with a function that's should change the image when I click on the button it pass directly from the first image to the last image. What is wrong in my code ?
<script language="javascript">
function changeImage() {
if (document.getElementById("image").src == "1.jpg")
{
document.getElementById("image").src = "2.jpg";
}
else if (document.getElementById("image").src == "2.jpg")
{
document.getElementById("image").src = "3.jpg";
}
}
</script>

Accessing DOMNode.src will return the full path to the image:
var img = document.createElement('img');
img.src = 'a.png';
console.log(img.src); // https://example.com/a.png
console.log(img.getAttribute('src')) // a.png
Your changeImage function can be rewritten as:
function changeImage() {
var image = document.getElementById("image");
var src = image.getAttribute('src');
if (src == "1.jpg") {
image.src = "2.jpg";
}
else if (src == "2.jpg") {
image.src = "3.jpg";
}
}

Maybe you should use something like this:
function changeImage() {
var image = document.getElementById("image");
var src = image.getAttribute("src");
if (src === "1.jpg") {
image.src = "2.jpg";
} else if (src === "2.jpg") {
image.src = "3.jpg";
}
}
Give me a shout if it works.

<html>
<head>
<script language="javascript">
function changeImage() {
if (document.getElementById("image").src == "1.jpg")
{
document.getElementById("image").src = "2.jpg";
}
else (document.getElementById("image").src == "2.jpg")
{
document.getElementById("image").src = "3.jpg";
}
}
</script>
</head>
<body>
<img id="image" src="1.jpg" ><br><br></img>
<button id="clickme" onclick="changeImage();"> : pass </button>
</body>
</html>

Related

HTML How to change image onClick

I'm trying to have an image that changes when clicked: when image 1 is clicked, change to image 2, when image 2 is clicked change to image 3 and when image 3 is clicked it changes to image 1.
<p>
<img alt="" src="assets/img1.png"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "assets/img1.png")
{
document.getElementById("imgClickAndChange").src = "assets/img2.png";
}
else if (document.getElementById("imgClickAndChange").src == "assets/img2.png")
{
document.getElementById("imgClickAndChange").src = "assets/img3.png";
}
else if(document.getElementById("imgClickAndChange").src == "assets/img3.png"){
document.getElementById("imgClickAndChange").src = "assets/img1.png"
}
Clean and optimal solution in my opinion. As the users before said. It is good to use array to held the images paths.
var images = ["https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350", "https://i2.wp.com/beebom.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg?resize=640%2C426", "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350"]
var imgState = 0;
var imgTag = document.getElementById("imgClickAndChange");
imgTag.addEventListener("click", function (event) {
imgState = (++imgState % images.length);
event.target.src = images[imgState];
});
Solution
There were a lot of syntax errors in your code. I cleaned them up in a codepen here where you can see that your basic logic was correct. Though, as other users pointed out, there are more elegant ways to solve this problem.
https://codepen.io/anon/pen/MPYgxM
HTML:
<p>
<img alt="" src="https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
</p>
JS:
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg")
{
document.getElementById("imgClickAndChange").src = "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg";
}
else if (document.getElementById("imgClickAndChange").src == "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg")
{
document.getElementById("imgClickAndChange").src = "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg";
}
else if(document.getElementById("imgClickAndChange").src == "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg"){
document.getElementById("imgClickAndChange").src = "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"
}
}
you can increment value on each click and update img. on base of incremented value
<img alt="" src="assets/img1.png" style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
var counter = 1;
function changeImage() {
counter > 3 ? counter = 1 : counter++;
document.getElementById("imgClickAndChange").src = "assets/img"+counter+".png";
}
</script>
Hi this is different approach.
new ClickListener() is the class used to handle your logic & dom logic
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Image click</title>
</head>
<body>
<div id="player">
</div>
<script>
class ClickListener {
constructor() {
this.rootElement = document.querySelector( "#player" );
this.element = document.createElement("img");
this.rootElement.appendChild(this.element);
this.images = ['./1.jpg', './2.jpg', './3.jpg']
this.idx = 0
this.init()
}
init() {
this.element.src = this.images[this.idx]
this.element.style.width = `400px`;
this.element.style.height = `400px`;
this.element.onclick = this.nextImage.bind(this)
}
nextImage() {
this.idx++;
if(this.idx >= this.images.length) {
this.idx = 0;
}
this.element.src = this.images[this.idx]
}
}
new ClickListener()
</script>
</body>
</html>

How to store the value of document.getElementById("myNumber") in a variable and add an if-else statement

<html>
<head>
<title>question 5</title>
</head>
<body>
<button id="b0" onclick="start()">Start Game</button>
<br>
<img src="happy_fish.png" id="fish" onclick="mySore()">
<script type="text/javascript">
var image_tracker = 'happy';
var image = document.getElementById('fish');
image.style.display = "none";
function change() {
if (image_tracker == 'happy') {
image.src = 'happy_fish.png';
image_tracker = 'sad';
} else {
image.src = 'sad_fish.png';
image_tracker = 'happy';
}
}
var timer;
function start() {
image.style.display = "block";
timer = setInterval('change();', 600);
}
function stop() {
clearInterval(timer);
}
function mySore() {
if (image_tracker == 'sad') {
var x = document.getElementById("myNumber").stepUp();
if (x >= 10) {
clearInterval(timer);
}
} else {
var y = document.getElementById("myNumber").stepDown();
if (y <= -10) {
clearInterval(timer);
}
}
}
</script>
<p><strong>Your Score: <input type="number" id="myNumber"></strong>
</body>
</html>
In this code i want to store the value of number in a variable so that in the if-else statement i can compare the value of that number and with 10 and -10 and perform the action in the if-else statement.
I also want to print out that if the number becomes more than 10 it will print out you win and when the number become less than -10 then it will print out you loss.
You could this <p id="message"></p> element next to your input, in your if-else statement add the following statements var xVal=document.getElementById("myNumber").value; and if(xVal>=10){ clearInterval (timer); document.getElementById("message").innerHTML="You Win"}, do the same work with other case. Check the following working solution:
<html>
<head>
<title>question 5</title>
</head>
<body>
<button id="b0" onclick="start()">Start Game</button>
<br>
<img src ="https://images.pexels.com/photos/45910/goldfish-carassius-fish-golden-45910.jpeg?auto=compress&cs=tinysrgb&h=650&w=940" id ="fish" onclick="mySore()" height="200" width="200">
<script type="text/javascript">
var image_tracker = 'happy' ;
var image = document.getElementById('fish');
image.style.display = "none";
function change() {
if (image_tracker == 'happy'){
image.src = 'https://images.pexels.com/photos/45910/goldfish-carassius-fish-golden-45910.jpeg?auto=compress&cs=tinysrgb&h=650&w=940';
image_tracker = 'sad';
}
else{
image.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCvJNQB6U62UvdD5oinU1hbpUWeUDAniae39-rlP6T7ONJARhQ';
image_tracker = 'happy';
}
}
var timer;
function start(){
image.style.display = "block";
timer = setInterval ('change();',1600);
}
function stop() {
clearInterval (timer);
}
function mySore() {
if( image_tracker == 'sad' ){
var x = document.getElementById("myNumber").stepUp();
var xVal=document.getElementById("myNumber").value;
if ( xVal >= 10){
clearInterval (timer);
document.getElementById("message").innerHTML="You Win";
image.style.display = "none"; document.getElementById("myNumber").disabled=true
}
}
else{
var y = document.getElementById("myNumber").stepDown();
var yVal=document.getElementById("myNumber").value;
if ( yVal < -10){
document.getElementById("message").innerHTML="You lost";
image.style.display = "none"; document.getElementById("myNumber").disabled=true
clearInterval (timer);
}
}
}
</script>
<p><strong>Your Score: <input type="number" id="myNumber"></strong></p>
<p id="message"></p>
</body>
</html>

Javascript Next and Previous images

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"); }

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>

Replace one of multiple image with javascript

I have multiple same images. When i click on one of them img need to be replaced. I have JS script:
var newsrc = "slide_down";
function changeImage() {
if ( newsrc == "slide_down" ) {
document.images["pic"].src = "img/slide_up.png";
document.images["pic"].alt = "slide_up";
newsrc = "slide_up";
}
else {
document.images["pic"].src = "img/arrow.png";
document.images["pic"].alt = "slide_down";
newsrc = "slide_down";
}
}
But when I press the second img, always the first to be replaced. Help please.
Html code of image is <img src="img/arrow.png" alt="slide_up" class="head" id="pic" onclick="changeImage()">
Try
var newsrc = "slide_down";
function changeImage() {
if ( newsrc == "slide_down" ) {
this.src = "img/slide_up.png";
this.alt = "slide_up";
newsrc = "slide_up";
}
else {
this.src = "img/arrow.png";
this.alt = "slide_down";
newsrc = "slide_down";
}
}

Categories