Shrink img using javascript - javascript

I'm trying to shrink an image based off of what I learned on the mobile app SoloLearn. Please help.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css"/>
</head>
<body>
<img id="image" src="myImage.jpg"/>
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.style.width = 50;
img.syle.height = 25;
};
</script>
</body>
</html>

Rather then using img.style just set the width and height values of the image.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css" />
</head>
<body>
<img id="image" src="http://www.placehold.it/150" />
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.width = 50;
img.height = 25;
};
</script>
</body>
</html>

The width and height styles aren't numbers, they need units as well, like px for pixels. So
function shrnk() {
img.style.width = '50px';
img.style.height = '25px';
}
The only time you can omit the units is when you're setting them to 0, since that's the same regardless of the units.

If you'd like to use the style property you need to set the unit of the number you're talking about (ie. "px").
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css" />
</head>
<body>
<img id="image" src="http://lorempixel.com/200/200" />
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.style.width = "50px";
img.style.height = "25px";
};
</script>
</body>
</html>

Related

Getting width and height from a picture using Javascript

How can I get width and height from a picture stored in a directory using Javascript?
From a web browser:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Dimensions</title>
</head>
<body>
<img id="myImage" src="image.png">
<script>
var img = document.getElementById("myImage");
img.onload = function (event) {
console.log(`natural: ${img.naturalWidth}, ${img.naturalHeight}`);
console.log(`width,height: ${img.width}, ${img.height}`);
console.log(`offset: ${img.offsetWidth}, ${img.offsetHeight}`);
}
</script>
</body>
</html>

How to change the height of an element using Javascript?

I am trying to modify the height of a div element in a Javascript function. The height is initially
set to 50px in the style section. Neither of the attempts shown below have any effect. I would appreciate your help on this. Thanks.
<html>
<head>
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
window.onload = function () {
setHeight();
}
function setHeight() {
var testElement = document.getElementById("test");
testElement.style.offsetHeight = 200;
testElement.offsetHeight = 200;
}
</script>
</head>
<body>
<div id="test" style="height:50px;border-style:solid;border-width:thin;">
<p>Some text</p>
</div>
</body>
</html>
Just set style.height
testElement.style.height = '200px';

script no longer updating the page

I have the following html page which displays a picture at a random location and updates it every 10 seconds :
<!DOCTYPE html>
<html>
<head>
<title>Domoos | Screen saver screen</title>
<meta http-equiv="refresh" content="10">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<meta http-equiv="pragma" content="no-cache">
<link rel="stylesheet" type="text/css" href="css/mystyle_saver.css" />
<script type="text/javascript" src="scripts/date_time.js"></script>
<script type="text/javascript">
function init() {
var xmin = 0;
var xmax = 890;
var ymin = 0;
var ymax = 430;
var xCoord = Math.floor((Math.random()*xmax)+xmin);
var yCoord = Math.floor((Math.random()*ymax)+ymin);
var xCoordStr = xCoord.toString() + "px";
var yCoordStr = yCoord.toString() + "px";
document.getElementById("randomPlacement").style.left = xCoordStr;
document.getElementById("randomPlacement").style.top = yCoordStr;
}
</script>
</head>
<body onload="init();">
<div style="position:absolute" id="randomPlacement">
<p><img src="assets/pictures/texte_sortie_veille.png" alt ="" style="width:60px;height:60px;"></p>
</div>
</body>
</html>
It works very well. Now, I would like to add two 'div' tags so I could display the date and the time. So, I updated the body tag as follows (the rest of the page remains unchanged) :
<body onload="init();">
<div style="position:absolute" id="randomPlacement">
<p><img src="assets/pictures/texte_sortie_veille.png" alt ="" style="width:60px;height:60px;"></p>
</div>
<div id="date">
<script type="text/javascript">window.onload = getDate('date');</script>
</div>
<div id="time">
<script type="text/javascript">window.onload = getTime('time');</script>
</div>
</body>
The problem by doing so is that the image is never displayed at a random location. What am I missing and hopefully how can I solve the issue? I have added an extract of the console in Chrome.
Thanks a lot for your help.
replace
<div id="date">
<script type="text/javascript">window.onload = getDate('date');</script>
</div>
<div id="time">
<script type="text/javascript">window.onload = getTime('time');</script>
</div>
with
<div id="time">
</div>
then in init()
function init() {
var xmin = 0;
var xmax = 890;
var ymin = 0;
var ymax = 430;
var xCoord = Math.floor((Math.random()*xmax)+xmin);
var yCoord = Math.floor((Math.random()*ymax)+ymin);
var xCoordStr = xCoord.toString() + "px";
var yCoordStr = yCoord.toString() + "px";
document.getElementById("randomPlacement").style.left = xCoordStr;
document.getElementById("randomPlacement").style.top = yCoordStr;
document.getElementById("date").innerhtml=getDate('date');
document.getElementById("time").innerhtml=gettime('time');
}

javascript img onclick reference error to function

I keep on getting ReferenceError: toggleExpand is not defined in console on firefox when I click the img
I am trying to get the image to enlarging, floating in center screen on click, no jquery, pure javascript, html, css.
HTML
<body>
<script type="text/javascript">
function toggleExpand(id){
var doc = document.getElementById(id);
doc.style.z-index = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
<img id="img1" onclick="toggleExpand('img1');" src="I:\Images\image.jpg" alt="image" style="width:128px; height:auto; cursor:pointer; z-index:0"/>
</body>
This is my code used this can used this
<html>
<head>
<script>
function toggle(){
var doc = document.getElementById("divSection");
doc.style.z-index = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<p class="button" onclick="toggle()">Show/hide</p>
</body>
</html>
First of, a property cannot contain a -
so change it to CamelCase zIndex or wrap in brackets ["z-index"]
also, strange no-one mentioned, no need to pass the ID! You already have the this reference to the clicked referring HTMLIMGElement,
so yes, use simply onclick="toggleExpand(this);" without the ID
Also I see you named your function TOGGLE... so let's toggle!
img[onclick]{vertical-align:top; cursor:pointer; }
<script>
function toggleExpand(el){
var io = el.tog ^= 1; // Store the toggle state
el.style.zIndex = io ? 1 : 0;
el.style.width = (io ? 256 : 128) +"px";
}
</script>
<img onclick="toggleExpand(this);" src="https://www.gravatar.com/avatar/6edc0ac8cd9f3e790389f3284eaaf9e9?s=32&d=identicon&r=PG" alt="image" style="width:128px; height:auto; z-index:0"/>
<img onclick="toggleExpand(this);" src="https://i.stack.imgur.com/1ZIkv.jpg?s=48&g=1" alt="image" style="width:128px; height:auto; z-index:0"/>
jsBin playground
change doc.style.z-index to doc.style['z-index'] and check
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<body>
<script type="text/javascript">
function toggleExpand(id) {
var doc = document.getElementById(id);
doc.style['z-index'] = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
<img id="img1" onclick="toggleExpand('img1');" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Alexanderplatz_Stadtmodell_1.jpg/1920px-Alexanderplatz_Stadtmodell_1.jpg" alt="image" style="width:128px; height:auto; cursor:pointer; z-index:0"
/>
</body>
</body>
</html>
Why you are passing your id as a function argument! why not use something like this-
<body>
<img id="img1" onclick="toggleExpand();" src="I:\Images\image.jpg" alt="image" style="width:128px; height:auto; cursor:pointer; z-index:0"/>
<script type="text/javascript">
function toggleExpand(){
var doc = document.getElementById('img1');
doc.style.z-index = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
</body>
It is better to do in this way.
var doc = document.getElementById(id)
doc.addEventListener('click',toggleExpand);

document.querySelector(...) is null error

For image upload in a cakephp project I used java-script.I added this js file in app\View\Layouts default.ctp
js code
document.querySelector('input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
if (files[i].type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
event.target.value = '';
I have checked there are no problem.
now in add.ctp file I adder
<input type="file" multiple />
In output I am seeing the file type field.Now when I clicked on this field and upload a image then mojila bug given me a error.That is
document.querySelector(...) is null error
I have no idea about this error.In here why saying queryselector is null?
document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.
I would suggest you call all JS script bottom of the page.
To make sure that your DOM is ready you could add this to your JS file.
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.querySelector('input[type=file]')
.addEventListener('change', function(event){
...
}
});
This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.
Also take a look at this other Google rule.
file.js
const heading1 = document.querySelector(".heading1");
console.log(heading1);
Solution 1
Use defer (best & recommended way):
<!DOCTYPE html>
<html lang="en">
<head>
<script src="./file.js" defer></script>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
</body>
</html>
Solution 2
Place your JavaScript in bottom before closing body tag
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
<script src="./file.js"></script>
</body>
</html>
I suggest writing your <script type="text/javascript" src="your js file"></script> in body, before the closing tag
There is now another "better" way to address this issue.
put your scripts in the head tag and add the defer attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="main.js" defer></script>
</head>
<body>
yoyoyo
</body>
</html>
you can read more about it here and here
TLDR (may be inaccurate and misleading so read the sources above!):
the defer attribute tells the browser to load the file but hold off its execution until the dom is ready, which is close to the behavior you implicitly get when you put the script tag at the bottom of the body tag, the difference being that in the old way you have to wait for the whole body tag to be parsed until you start downloading the script tag.
I ran into this issue where I was trying to do (slimmed down for simplicity):
<script type="text/javascript">
var svg = document.querySelector('svg');
console.log(svg);
</script>
on an element in the <body>:
<svg id="svg" viewBox="0 0 120 120" width="500px" height="500px"></svg>
Once I added jQuery and moved my lines inside of a $(document).ready(), it was fine:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var svg = document.querySelector('svg');
console.log(svg);
});
</script>
Here's a quick fix. I was trying to effect some changes in my HTML page using DOM and was getting this error. The problem was I linked my Javascript file inside the head tag of the HTML page, when I changed that and linked it at the body just before the closing body tag, it worked!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Soft dog</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.4.1/dist/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link rel="stylesheet" href="landing.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Cormorant+SC:wght#300&family=Edu+VIC+WA+NT+Beginner&display=swap"
rel="stylesheet">
</head>
<body>
<div class="container">
<h2 id="newBrand">Welcome to SOFTDOG</h2>
<p><em>property of soft 6</em></p>
<a id="ceo" href="home.html"><img src="softdogmerch1.jpg" alt="check network"></a>
<p id="enterstatement">Please<a href="home.html">
<P><span>ENTER HERE</span></P>
</a><span>to feed your eyes and fill your wardrobe</span>
</p>
<label for="emailinput">email:</label>
<input id="emailinput" type="email" name="useremail" placeholder="user#email.com" required>
<label for="passwordinput">password:</label>
<input id="passwordinput" type="password" name="userpassword" placeholder="" required>
<input id="clickme" type="submit" name="login" value="log in">
<input id="clickme" type="submit" name="signup" value="sign up">
</div>
<script src="landing.js"></script>
</body>
</html>

Categories

Resources