Change image onclick using javascript - javascript

Here's my problem:
I am new to Javascript and I am trying to make my image change on click.
It's a simple counter game that does a 2 frame animation of squidward hitting the dab.
So far I have got the counter to work but I cannot get the image to change on click as well. Also, it's going to have to change back to the original image so that it can be clicked and counted again.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div class="container">
<button onclick="dabMan()"><img src="./squid-dab1.gif"> .
</button>
<br><br>
How many dabs??
<input type="text" id="text">
</div>
<script src="./script.js"></script>
</body>
</html>
var dabcount = 0;
function dabMan() {
dabcount = dabcount + 1
document.getElementById('text').value = dabcount;
console.log("dabMan", dabMan)
document.getElementById("./squid-dab1.gif") .src = "./squid-dab2.gif";
console.log("changeimage", dabMan)
}

instead of using the "onclick(){}" attribute in your html, write an event listener in js. Assuming your image tag is like this:
<img src='./squid-dab1.gif' id='myImage'>
Note: Javascript needs to know how to find your image... Hence the ID
Your javascript code should look like this:
<script>
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = './squid-dab2.gif';
}
</script>
That will make it so that when you click the image, it will change. If you wanted a button to do that, simply create a button with the id "myImage" instead like so:
<button id='myImage'>Click me to change the picture</button>

Related

How do I update the input value using an onchange event and get the value in vanilla Javascript?

I am doing an assignment where I make a simple API call using fetch to retrieve an image a of dog by breed. The one issue I can't resolve is that the input value never changes when I try to retrieve an image of a different breed. the default value, which is 'hound', reappears after I press submit. I know I need to attach an onchange event to my input but I am not sure how to write it or how to get the value after the onchange event is triggered. Any help would be greatly appreciated. I originally wrote this with jQuery but decided to rewrite it in vanilla Javascript so that's why there is no jQuery.
I put a '<---' on the line I am struggling with.
P.S I know my code isn't very good, I am new to this.
Javascript
function getJson(breed) {
fetch("https://dog.ceo/api/breed/" + breed + "/images/random")
.then((response) => response.json())
.then((responseJson) => displayResults(responseJson));
}
function displayResults(responseJson) {
const dogImage = responseJson.message;
let breedImage = "";
let container = document.createElement("div");
console.log(dogImage);
breedImage += `<img src="${dogImage}">`;
container.innerHTML = breedImage;
document.querySelector(".results-img").innerHTML = "";
document.querySelector(".results-img").appendChild(container);
}
function submitButton() {
let breedName = document.querySelector("#numberValue").value;
breedName.addEventListener().onchange.value; <---
document.getElementById("dog-input").addEventListener("submit", (e) => {
e.preventDefault();
getJson(breedName);
});
}
submitButton();
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form>
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need an onchange event handler. Currently you're storing the value of the input in breedName when you call submitButton. That means that breedName will never change because it is merely a reference to the value at that moment.
Instead create a reference to the element and read the value property in the submit event handler. That will get the value how it is at the time you submit.
function getJson(breedName) {
console.log(breedName);
}
function submitButton() {
const form = document.querySelector('#dog-form');
const input = document.querySelector('#numberValue');
form.addEventListener('submit', event => {
event.preventDefault();
const breedName = input.value;
getJson(breedName);
});
}
submitButton()
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="dog-form">
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>

After a button is clicked/form submit, the CSS stylesheet doesn't appear

After the use button is clicked, the sources when I inspect the page show that the style.css page goes away, and no styles are applied. I can't figure out why this is happening.
My index.html page looks like this:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#400;500&family=Roboto:wght#100;300;400;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" placeholder="First name" class="fname">
<input type="submit" value="Use" class="submit">
<script src="app.js"></script>
</body>
</html>
And my app.js is this:
const useBtn = document.querySelector('.submit');
const reloadBtn = document.querySelector('.btn__reload')
document.body.style.fontFamily = "Roboto;"
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
document.write(`<h2>It's ${person}'s turn!</h2>`)
document.write(`<h4>How long will they live?</h4>`)
let oldAge = `<p>${Math.floor((Math.random() * 10)+ 30)}</p>`
document.write(oldAge)
document.write(`<h4>What will be their yearly salary?</h4>`)
let salary = `<p>${Math.floor(Math.random() * 10000)}</p>`
document.write(salary)
document.write(`<h4>What will be their career</h4>`)
const jobs = [ 'plumber', 'doctor', 'witch', 'president', 'trump supporter']
let job = Math.floor(Math.random() * jobs.length)
document.write(jobs[job])
redoBtn();
})
function redoBtn(){
let tryAgain = document.createElement('button')
document.body.appendChild(tryAgain)
let buttonText = document.createTextNode('Try Again')
tryAgain.appendChild(buttonText)
tryAgain.addEventListener('click', function(){
window.location.href = window.location.href;
})
}
Any help is so appreciated!
Your document.write is overwriting all your html, including your linked stylesheet.
From https://developer.mozilla.org/en-US/docs/Web/API/Document/write:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
If you really want to use document.write, you'll need to rewrite your stylesheet link into the new document. But it might be better to just replace the html of some container element on your page, like the body element.
Instead of using document.write which overwrites your html you could try this approach:
<input type="submit" value="Use" class="submit">
<!-- add new div to show the result -->
<div id="result"></div>
<script src="app.js"></script>
And in the click event:
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
let res = document.getElementById('result');
res.innerHTML = "<h2>It's "+person+"'s turn!</h2>";
// add further information to innerHTML here
// hide input fname and submit button
redoBtn();
})

How to change color of html in page 2 by clicking the button in page 1

**page1.html**
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.querySelector(".example").style.backgroundColor = "red";
}
</script>
**page2.html**
<h2 class="example">A heading with class="example"</h2>
The background color of the h2 tag with class named example won't change after clicked the button in page 1.
A possible solution is using Local Storage who persist over pages on the same domain. Then in the target page read the value in "onload".
On the page1:
function myFunction() {
localStorage.setItem("exampleBGColor", "red");
}
On the page2:
window.onload = function() {
let BGcolor = localStorage.getItem("exampleBGColor");
if(BGcolor) {
document.querySelector(".example").style.backgroundColor = BGcolor;
localStorage.removeItem("exampleBGColor");
}
}
Hope this can help you.
For making a change in another page it's not possible to directly access it from your page.
So you can do it from some innovative ways !
For Example :
You can pass a parameter to another page ('page2') in your url and then in
'page2' read it from query params and set the color for element.
You can set the color in the localstorage and then in new page read
it from localstorage and set the color of element.
You can achieve similar behavior using LocalStorage api.
First Page:
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Local Storage</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script>
function setColor() {
localStorage.setItem('currentColor', 'red');
}
</script>
</head>
<body>
<button onclick="setColor()">
Change Color
</button>
</body>
</html>
Second Page:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Local Storage</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script>
window.addEventListener('storage', function(e) {
const div = document.getElementById('div');
div.style.backgroundColor = e.key === 'currentColor' ? e.newValue : null;
});
</script>
</head>
<body>
<div id="div">
My Color Will Change
</div>
</body>
</html>
Using storage event listener allows div in Page 2 to update its color reactively.
You can learn more about LocalStorage here.
As #juanram0n, Ilia #Afzali and #dev_junwen said, you can make it by using JavaScript Window localStorage Property.
*page1.html*
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
// Store backgroundColor
localStorage.setItem("bgColor", "red");
}
</script>
*page2.html*
<h2 class="example">A heading with class="example"</h2>
<script>
document.querySelector(".example").style.backgroundColor = localStorage.getItem("bgColor");
</script>

display an image only when button is clicked

Just beginning to learn HTML & Javascript.
I have the following code, which works. however, because I have have an img tag in my body it is trying to show a place holder for an image before I click the button. How can I stop this.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
<script type="text/javascript">
function picture(){
var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
document.getElementById('bigpic').src = pic.replace('90x90', '225x225');
}
</script>
</head>
<body>
<img id="bigpic" src="bigpic" />
<button onclick="picture()">Enlarge</button>
</body>
</html>
Best wishes.
Add style "display:none" to picture tag
<img id="bigpic" src="bigpic" style="display:none;"/>
And in function picture change it for show image
document.getElementById('bigpic').style.display='block';
There is demo: http://jsfiddle.net/eX5kx/
Use display property in css, try this:
javascript:
function showPicture() {
var sourceOfPicture = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg";
var img = document.getElementById('bigpic')
img.src = sourceOfPicture.replace('90x90', '225x225');
img.style.display = "block";
}
html:
<img style="display:none;" id="bigpic" src="bigpic" />
<button onclick="showPicture()">Enlarge</button>
I like shin solution, i would do the same thing myself. However theres a lot of way to do that, another option is to put a tiny trasparent image as default and then replace like you did to the other one. like this:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
<script type="text/javascript">
function picture(){
var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
document.getElementById('bigpic').src = pic.replace('90x90', '225x225');
}
</script>
</head>
<body>
// tiny trasparent image
<img id="bigpic" src="https://maps.gstatic.com/mapfiles/markers2/dd-via-transparent.png" alt="" />
<button onclick="picture()">Enlarge</button>
</body>
</html>
this way no css is needed but like i said before i prefer Shin's solution.

Resize an image from data entered in a textbox

ive a form with a image , button and textbox. ive to resize the images height and width to what ever is entered in the textbox, when the button is clicked. My image just disappears when the button is clicked.
heres my code
<!DOCTYPE HTML>
<html>
<head>
<title>Resize Image</title>
</head>
<body>
<script>
function resizeimage()
{
var theImg = document.getElementById('image');
theImg.height = size;
theImg.width = size;
}
var size=parseInt(document.getElementById('txtbox'));
</script>
<form name ="ResizeImage">
<img src = "cookie.jpg" id="image">
</br>
<input type=button value="Resize" onclick="resizeimage()">
</br>
<input type=text id="txtbox"
</form>
</body>
</html>
Apart from the HTML problems (please run it through the validator), the main problem is that the part of code that reads the size of the image is outside of the function. On page load, this is what happens.
The function resizeimage() is defined
The var size is set to whatever is in the input at that point
The contents of the page are loaded.
At 2. the input doesn't even exist yet because 3. isn't done yet, so var size is set to undefined. It never changes after that, because the function resizeimage() does not try to read the size of the image again.
Also, document.getElementById returns an element. You will have to read what the user put into it by using it's .value property
Try this:
function resizeimage()
{
var size=parseInt(document.getElementById('txtbox').value);
var theImg = document.getElementById('image');
theImg.height = size;
theImg.width = size;
}
Working example: http://jsfiddle.net/KZH5p/
I would cache the ids first:
var input = document.getElementById('txtbox');
var theImg = document.getElementById('image');
function resizeimage() {
var size = input.value;
theImg.height = size;
theImg.width = size;
}
function changeDogsSize() {
var dogSize = parseInt((id_input).value);
id_dog.width = dogSize;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container bg-light mt-3"></div>
<!--changing dogs image-->
<div class="container">
<img id="id_dog" src="https://i.pinimg.com/originals/e4/9d/75/e49d755afcd02cdbf39d374b42a10ecd.jpg" alt="dog">
<input id="id_input" type="text" class="form-control mt-4" id="exampleInputAmount" placeholder="enter img width">
<button id="id_changeBtn" onclick="changeDogsSize()" type="button" class="btn btn-secondary btn-lg mt-3 text-dark">Change</button>
</div>
</body>
</html>

Categories