Set width and height for image random by Javascript - javascript

Something hard to understand for me that, how can I set width and height for the random images when they displayed. Can anyone help me, please?
This is my code
function randomImage(){
var imagesArray = ['images/person1.jpg', 'images/person2.jpg', 'images/person3.jpg'];
var num = Math.floor(Math.random() * 3);
document.canvas.src = imagesArray[num];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display random image</title>
</head>
<body>
<input type="button" id="randomImage" onclick="randomImage()" value="Random">
<img src="" name="canvas" />
</body>
</html>
And I do not know how to set width and height so I did not write code for this yet, this code just display images random when I click button
Your help is my pleasure

To identify your image by name attribute, use getElementsByName or the newer querySelector and for setting width and height you can use style attribute:
document.getElementsByName("canvas")[0].src = imagesArray[num];
or
document.querySelector("img[name=canvas]").src = imagesArray[num];
and for width and height (you can also use querySelector here):
document.getElementsByName("canvas")[0].style.width = "100px";
document.getElementsByName("canvas")[0].style.height= "100px";
function randomImage(){
let imagesArray = ['images/person1.jpg', 'images/person2.jpg', 'images/person3.jpg'];
let num = Math.floor(Math.random() * 3);
let image = document.getElementsByName("canvas")[0];
image.src = imagesArray[num];
image.style.width = "100px";
image.style.height = "100px";
}
<input type="button" id="randomImage" onclick="randomImage()" value="Random">
<img src="" name="canvas" />
if you want a random value for width and height, use it instead of the 100 in my sample

You should create a class: "image"
and in CSS you should add:
.image{
width: 220px; // you put your value here
height: auto; // to considere the proportions of the image
}
I am notsure if this answers your question, but you can also choose other approach you can do as following:
<div class="wrapper">
<img>
</div>
where .wrapper has overflow set to hidden and img has width of 100% and height auto,

You could've used window.canvas here, but that's not advisable. To retrieve one element, document.querySelector is your friend.
randomImage();
document.addEventListener("click", evt => {
if (evt.target.nodeName === "BUTTON") {
randomImage();
}
});
function randomImage() {
const imagesArray = [
'https://picsum.photos/200/300',
'https://picsum.photos/300/400',
'https://picsum.photos/100/100'
];
const randomNumber = Math.floor(Math.random() * 3);
document.querySelector("img[name='canvas']").src = imagesArray[randomNumber];
}
button {
float: right;
position: fixed;
right: 30vw;
top: 1rem;
}
<img name="canvas" src="" />
<br><button>Another picture</button>

Related

Is there a solution for a font size slider affecting body tag but just need it to affect some css classes

I have the following code to change the body font size on a web site. Its working fine but the resizing gets awful as it affects every text into de body. So I have tried to transform it to only apply the font resizing just to some css classes but I can not find the solution. What I would like to do is that the resizing just affect, for example, .content-block, .main-content, .etc,....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1"/>
</div>
<div>
<h1>Changing Font Size</h2>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
if (curSize) {
var saveSize = curSize;
body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function (e) {
var newSize = this.value,
defaultSize = body.style.getPropertyValue('font-size'),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>
You can use css variable in needed classes and in javascript simply change value of that variable:
var curSize = null; // localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
var defaultSize = body.style.getPropertyValue('font-size');
if (curSize) {
var saveSize = curSize;
document.documentElement.style.setProperty("--font-size", saveSize + "px");
//body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function(e) {
var newSize = this.value,
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
document.documentElement.style.setProperty("--font-size", newSize + "px");
// body.style.fontSize = newSize + 'px';
// localStorage.setItem("saveSize", newSize);
}
});
:root {
--font-size: 1em;
}
.affected,
.dynamic {
font-size: var(--font-size);
}
/* ignore this */
.affected:before,
.dynamic:before,
.content :not(.affected):not(.dynamic):before {
content: "dynamic font size:";
background-color: lightgreen;
border: 1px solid grey;
font-size: initial;
margin: 1em;
padding: 0.2em;
}
.content :not(.affected):not(.dynamic):before {
content: "static font size:";
background-color: pink;
}
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1" />
</div>
<div>
<div class="content">
<h1>Changing Font Size</h2>
<p class="dynamic">I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
</div>
The Vanowm answer is ok and works very well but I need the localStorage to store the selected font size to persist over sessions, so I am going to post an answer with that enabled just in case someone else could need a similar approach.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1"/>
</div>
<div>
<h1>Changing Font Size</h2>
<p class="dynamic">I am just a boring text, existing here solely for the purpose of this demo</p>
<p class="affected">And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
var defaultSize = body.style.getPropertyValue('font-size');
if (curSize) {
var saveSize = curSize;
document.documentElement.style.setProperty("--font-size", saveSize + "px");
// body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function(e) {
var newSize = this.value,
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
document.documentElement.style.setProperty("--font-size", newSize + "px");
// body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>

Change image position on button click

I don't know very much about coding, but I would like to be able to make it so when I click one of the "test" buttons, the image moves. I would like it to be a variable, so that it is constantly checking the variable (I have no idea how to use variables), and at any given moment, when variable = number, it is in a specific position I have designated. And when I click test 1, that variable goes up by one, and when I click test 2, it goes down by one. And at any given variable from 0-10, there is a specific place the image should be for each number. And once the variable reaches 11, the variable will instantly reset to 0 as if in a loop. It can include HTML, CSS and Javascript, sorry if this is confusing I really am a noob at coding :(
This is all the code I have so far, it really isn't helpful but I thought I should add it anyway.
<img id="img01" src="https://cdn.shopify.com/s/files/1/0080/8372/products/tattly_triangle_yoko_sakao_ohama_00_1200x1200.png?v=1575322215" height="300">
<button id="test1" type="button">test 1</button>
<button id="test2" type="button">test 2</button>
Thank you for any help :)
Take a look at the code below. I hope this example will help you to undestand a block move principe.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>moved image</title>
</head>
<body>
<div class="wrapper">
<div>
<img class="image" src="" width="50" style="left: 200px;">
</div>
</div>
<button class="button" type="button" id="left-button" onclick="moveLeft()">Left</button>
<button class="button" type="button" id="right-button" onclick="moveRight()">Right</button>
<style>
.wrapper {
position: relative;
width: 500px;
min-height: 200px;
background-color: yellow;
}
.image {
position: absolute;
top: 40px;
width: 100px;
height: 70px;
background-color: blue;
}
</style>
<script>
'use strict'
const getNumber = function(str) {
return parseInt(str, 10);
}
const transformToString = function(num) {
return num + 'px';
}
const SHIFT = 10;
const MARGIN = 10;
const element = document.querySelector('.image');
const LEFT_MARGIN = getNumber(element.style.left) - SHIFT * MARGIN;
const RIGHT_MARGIN = getNumber(element.style.left) + SHIFT * MARGIN;
const moveLeft = function() {
if (getNumber(element.style.left) > LEFT_MARGIN) {
element.style.left = transformToString(getNumber(element.style.left) - SHIFT);
}
}
const moveRight = function() {
if (getNumber(element.style.left) < RIGHT_MARGIN) {
element.style.left = transformToString(getNumber(element.style.left) + SHIFT);
}
}
</script>
</body>
</html>

I am working on stack any 3 pictures. When I click one of them, the one I click should be displayed on the top.

I am working on stack any 3 pictures. When I click one of them, the one I click should be displayed on the top.
I want you to help me in my code. I have already mention in title. Here I am attaching the body, style and java Script. every ting is fine but still i am unable to work this.
<!Doctype>
<html>
<head>
<style>
div {
width:420px;
height:300px;
}
div.box1 {
background:#dad7d7;
position:relative;
z-index:1;
}
div.box2 {
background:#ffe7bc;
position:relative;
top:-200px;
left:50px;
z-index:2;
}
div.box3 {
background:#fc9458;
position:relative;
top:-360px;
left:100px;
z-index:2;
}
</style>
</head>
<body>
<div class="box1"> <img class = "imagel" id = "imagel" height = "300" width = "420" src = "images/image1.png"
alt = "(Image1)" onclick = "toTop('image1')" /> </div>
<div class="box2"> <img class = "image2" id = "image2" height = "300" width = "420" src = "images/image2.png"
alt = "(Image2)" onclick = "toTop('image2')" /> </div>
<div class="box3"> <img class = "image3" id = "image3" height = "300" width = "420" src = "images/image3.png"
alt = "(Image3)" onclick = "toTop('image3')" /> </div>
</body>
</html>
Here JavaScript
<script>
var topp = "image3";
function toTop(newTop) {
var domTop document.getElementById(topp).style;
var domNew document.getElementByld(newTop).style;
domTop.zIndex = "0";
domNew.zIndex = "10";
topp = newTop;
}
</script>
You seem to be setting the zIndex attribute to the div element with .box class.
I'd suggest you do document.getElementById(topp).parentElement.style or pass the parent class instead.
Also, you forgot your equal signs here
var domTop document.getElementById(topp).style;
var domNew document.getElementByld(newTop).style;
which should be
var domTop = document.getElementById(topp).style;
var domNew = document.getElementByld(newTop).style;

JavaScript Image (how to set height and width, using document.getElementById().src=' ')

How do I set the Bush picture to 100px by 100px?
<!DOCTYE html>
<html>
<head>
<title> Title </title>
<script>
</script>
</head>
<body>
<button type = button onclick = "document.getElementById('myImage').src='bush.jpg'">Bush</button>
<button type = button onclick = "document.getElementById('myImage').src='obama.jpg'">Obama</button>
<p>Default is Obama </p>
<img id = "myImage" src = "obama.jpg" style = "width: 100px; height: 100px">
</body>
</html>
I am in the beginning phase of learning javascript. Not sure what other information is really needed. I'm just trying to get a job in full-stack web development and realized there's less jobs in what I learned in school (Java/C/C++). I know it's a relatively simple question but don't know how to google the answer either since I don't know how to phrase the question... ha... anyone with some decent experience know how to do this?
Your style attribute is has invalid information in it. Your image tag looks like this:
<img id = "myImage" src = "obama.jpg" style = "width: 100px height: 100px">
and it should look like this:
<img id = "myImage" src = "obama.jpg" style = "width: 100px; height: 100px;">
Notice the added ;
Here is an example of setting style on the image dynamically. I used a function to switch the images.
<button type = button onclick = "changeImage('bush');">Bush</button>
<button type = button onclick = "changeImage('obama')">Obama</button>
<p>Default is Obama </p>
<img id = "myImage" src = "https://whitehouse.gov1.info/photos_obama_face/obama-happy-flag.jpg" style = "width: 100px; height: 100px" />
<script>
function changeImage(chump) {
var img = document.getElementById('myImage');
if(chump === 'obama') {
img.src = 'https://whitehouse.gov1.info/photos_obama_face/obama-happy-flag.jpg';
img.style.width = '100px';
img.style.height = '100px';
}
else {
img.src = 'http://www.capitolhillblue.com/wp-content/uploads/2011/07/071511bush.jpg';
img.style.width = '200px';
img.style.height = '200px';
}
}
</script>

Show images one after one after some interval of time

I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>​
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}​
Maybe something like this?

Categories

Resources