Resize an image from data entered in a textbox - javascript

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>

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

I can't figure out how to append a user's input into an array in Javascript

I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
And the Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it.
An image of the console log:
https://imgur.com/a/AiV4hRM
I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.
You need to get the value of the input from value attribute.
The below code will just return the reference to the input not the value.
var inputText = document.getElementById("inputBox");
To get the value of the input, you need to get it from the value attribute.
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
Working Example:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
You are pretty close, just missing that you need to get the value attribute of the textbox. See working example below.
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText.value);
console.log(customList);
});
<input id="inputBox" />
<button id="addButton">Add</button>

Change image onclick using 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>

Changing element text isn't working

It always seems to be a problem and I fail to see why, I'm trying to change element p text by using his ID, element p id="para1" is inside PostEditor.html:
The elementID I want to change is para1 in the following html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
The following function is issued by a click on a link inside index.html and displaying the page you are seeing above and is then supposed to change its content:
From index.html I issue the function from link:
<a onclick="postEditing()"> Edit</a>
This line issue the following function:
function postEditing()
{
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.document.getElementById("para1").innerHTML = "11111111111";
result.document.getElementById("para1").innerText = "11111111111";
result.document.getElementById("para1").value = "11111111111";
}
As you can see I tried three methods. I'd never understand what is the difference between them, but I tried all three and none worked!
It's because you're searching the document of the window which shows the index.html, not the document of the newly opened window. try following:
...
var editorWindow = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
editorWindow.document.getElementById("para1").innerHTML = "11111111111";
...
EDIT:
NOW i see the problem: in the function you're trying to access a property of the parameter element, but you don't pass a value for it. So this will end in an error because the accessed object is undefinded!
So you have three options to get it working:
test the parameter (always a good idea): var ID = null; if(element) ID = element.id;
pass a value: <a onclick="postEditing(this)"> Edit</a>
remove the line var ID = element.id;
SOLUTION: (TESTED)
I could not really say why, but the index.html found the para1 and can successfully set the new text. But somehow the new window will reinitialize the old value again.
So you have to do the changing in an handler you run at onLoad:
index.html:
<html>
<head>
<script>
function postEditing() {
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.onload = function() {
result.document.getElementById("para1").innerHTML = "11111111111";
}
}
</script>
</head>
<body>
<a onclick="postEditing()"> Edit</a>
</body>
</html>
PostEditor.html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
I'm fairly sure you will need to query the return result of calling window.open like this:
function postEditing(element)
{
var ID = element.id;
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.getElementById("para1").innerHTML = "11111111111";
result.getElementById("para1").innerText = "11111111111";
result.getElementById("para1").value = "11111111111";
}
[Untested though]
Your button type is submit, which is posting the form. The object is changing in the DOM, only after the script runs, the DOM is reloaded back to it's original state. Try changing your button type to "button", and you should see the P element change appropriately.
Edit: Here's the HTML I used to determine the above. Keeping the button as "submit" caused me to see the text change and then swap back. The HTML below should keep the text in place. HTH!
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script>
function postEditing(element)
{
document.getElementById('para1').innerHTML = "asdafs";
}
</script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="button" onclick="postEditing('caller')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>

Categories