Move image in every click javascript - javascript

I try to move the image in every click but it just move one time.See the code:
<img id="myImg" src="">
<script>
function move() {
var img = document.getElementById("myImg")
img.style.left += "2px";
}
</script>
<button onclick="move()"></button>
Anyone knows how to make it work?

When you get the value of left property, it looks like this: 0px. It's a string. So if you want to calculate it, you need to parse it to a number. Before doing that, you can split px part to get the number.
img {
position: absolute;
width: 150px;
height: 100px;
left: 0px;
}
button {
margin-top: 100px;
}
<img id = "myImg" src = "https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80">
<script>
function move(){
var img = document.getElementById("myImg");
img.style.left = +img.style.left.substring(0, img.style.left.length - 2) + 2 + 'px';
}
</script>
<button onclick = "move()">Move</button>

This line
img.style.left += "2px";
produces invalid CSS. You want to extract the integer each time, add 2, then add the "px" unit back in.
const img = document.getElementById("myImg")
function move() {
img.style.marginLeft = img.style.marginLeft ? parseInt(img.style.marginLeft, 10) + 2 + "px" : "2px"
}
<img id="myImg" src="https://placekitten.com/200/200">
<button onclick="move()">Move Image</button>

This is a very clumsy way to move an image. Please educate yourself about canvas object. But as you are a begginer and may just need a quick fix, here's a way to get your code working:
<img id = "myImg" style="width: 100px; height: 100px;" src ="https://upload.wikimedia.org/wikipedia/en/thumb/e/ec/Soccer_ball.svg/600px-Soccer_ball.svg.png">
<script>
var margin = 0;
function move(){
var img = document.getElementById("myImg")
margin += 2;
img.style.marginLeft = margin + "px";
}
</script>
<button onclick = "move()" >Move</button>

if you want to move image then you could move it either right or left for that try to fix your code at left - px
<img id = "myImg" src = "">
<script>
function move(){
var img = document.getElementById("myImg")
img.style.left += "2px";
}
function moveleft() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
</script>
<button onclick = "moveleft();">

Related

change css class property increment

I have a small question!
I'am trying to change css width property using JavaScript like this:
document.getElementById("progressvalue").style.width = "80%";
.progress {
width: 100%;
max-width: 500px;
border: 3px solid black;
height: 20px;
padding: 1px;
}
#progressvalue {
height: 100%;
width: 0%;
background-color: #05e35e;
}
<div class="progress">
<div id="progressvalue"></div>
</div>
But instead of 80% in JavaScript code, I want to increase the width value by 20%.
Like (width = width + 20%)
I want to apply this changing once (So I can use it mutiple times using other conditions), and this is why I need it like this (width = width + 20%)
You can try to read the element's style.width property, by keeping only the numeric part of it and adding it to your step (eg 20%).
const step = 5;
const updateProgress = () => {
const currentWidth = Number(document.getElementById("progressvalue").style.width.replace( "%", ""));
if (currentWidth>=100) {
return;
}
else {
document.getElementById("progressvalue").style.width = `${currentWidth+step}%`;
}
}
You can check this out in this CodePen.
I guess you want to do some animation right ? If so you can use recursivity with setTimeout:
function progress(val) {
val += 20;
document.getElementById("progressvalue").style.width = val + "%";
if (val < 100) // To stop the loop when progress bar is full
setTimeout(function () {
progress(val);
}, 1000)
}
progress(0); // Start the animation
This will increase by 20% every 0.5 seconds.
let percent = 0;
setInterval(() =>
{
if(percent > 100) {
clearInterval();
return;
}
document.getElementById("progressvalue").style.width = percent + "%";
percent += 20;
}, 500);
You can use this:
var el = document.getElementById("progressvalue");
var elementWidth = el.style.width;
var newWidth = `${20+parseInt(elementWidth.substring(0, elementWidth.length-1))}%`
el.style.width=newWidth;
Assuming that you have set the width of the element initially to a percent value.
<button type="button" id="myBtn" onclick="myFunction()">Change the width</button>
<script>
function myFunction() {
let progress = document.getElementById("progressvalue");
let style = window.getComputedStyle(progress, null).getPropertyValue('width');
let currentSize = parseFloat(style);
progress.style.width = (currentSize + 20) + '%';
}
</script>
You can try it
//offsetWidth : returns the width of the element
var element_width=document.getElementById("progressvalue").offsetWidth
document.getElementById("progressvalue").style.width =element_width + (20*element_width/100) +'px' ;
You need to get the current width of <div id="progressvalue"></div>, put it in a variable and add 20 and reassign that value to <div id="progressvalue"></div>.

Function not defined at HTMLButtonElement.onclick

I was trying to make some controls to the box move to left, right, up and down. But when i make all the functions in the script tag, it get an error (in all the four onclick button):
Function not defined at HTMLButtonElement.onclick
in the lines that i make the button tag.
<html>
<button onclick = "leftmove()" id = "b1"> Left </button>
<button onclick = "rightmove()" id = "b2"> Right </button>
<button onclick = "upmove()" id = "b3"> Up </button>
<button onclick = "downmove()" id = "b4"> Down </button>
<h1 id = "box"></h1>
<style type = "text/css">
#box {
width: 50px;
height: 50px;
background-color: black;
}
<script>
var box = document.getElementById("box");
function leftmove() {
margin += 2;
box.style.marginLeft = margin + "px";
}
var box = document.getElementById("box");
function rightmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
var box = document.getElementById("box");
function upmove() {
margin += 2;
box.style.marginTop = margin + "px";
}
var box = document.getElementById("box");
function downmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
</script>
</html>
When using <script> tags like this, the functions and targeted tags have to be defined before usage. To make you example work you have to split you script tag to first define you functions and set the box variable later, after you have defined the corresponding tag. Also the margin variable is missing, I added is as zero but that's probably not how you want it. Working example:
<html>
<body>
<script>
var margin = 0;
function leftmove() {
margin += 2;
box.style.marginLeft = margin + "px";
}
function rightmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
function upmove() {
margin += 2;
box.style.marginTop = margin + "px";
}
var box = document.getElementById("box");
function downmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
</script>
<button onclick="leftmove()" id="b1"> Left </button>
<button onclick="rightmove()" id="b2"> Right </button>
<button onclick="upmove()" id="b3"> Up </button>
<button onclick="downmove()" id="b4"> Down </button>
<h1 id="box"></h1>
<style type="text/css">
#box {
width: 50px;
height: 50px;
background-color: black;
}
</style>
<script>
var box = document.getElementById("box");
</script>
</body>
</html>
A few notes aside the question:
A <div> might be more appropriate instead of the <h1> for the box
For rendering performance you would be better of using transform(x, y) instead of margins to move the box
Some JavaScript variables were created to manipulate the CSS indirectly. Other elements were also implemented to better understand the movements.
<html>
<style type = "text/css">
#box {
margin: 100px;
width: 50px;
height: 50px;
background-color: black;
}
</style>
<button onclick = "start()" id = "b0"> Start </button>
<button onclick = "leftmove()" id = "b1"> Left </button>
<button onclick = "rightmove()" id = "b2"> Right </button>
<button onclick = "upmove()" id = "b3"> Up </button>
<button onclick = "downmove()" id = "b4"> Down </button>
<div id="box"></div>
<script type="text/javascript">
var box = document.getElementById("box");
var margin = 10;
var marginX = 100;
var marginY = 100;
function start(){
box.style.margin = "100px";
marginX = 100;
marginY = 100;
}
function leftmove() {
marginX -= margin;
box.style.marginLeft = marginX + "px";
}
function rightmove() {
marginX += margin;
box.style.marginLeft = marginX + "px";
}
function upmove() {
marginY -= margin;
box.style.marginTop = marginY + "px";
}
function downmove() {
marginY += margin;
box.style.marginTop = marginY + "px";
}
</script>
</html>

Add random image to page at user clicked position

I'm trying to write a script that picks a random image in an array and display it at the mouse x,y position. Also, when the image is shown, you can click somewhere else to add a new one. So you can fill the whole page with random cat images if you want.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("cat1");
cat.style.display = '';
cat.style.position = 'absolute';
cat.style.left = x - cat.width / 2 + 'px';
cat.style.top = y - cat.height / 2 + 'px';
}
.image{
width:100px;
height:auto;
}
#cat1{
background-color:red;
width:100px;
height: auto;
}
<div class="container">
<img alt="catAppear" class ="image" id="cat1" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png"/>
<img alt="catAppear" class ="image" id="cat2" style="display: none" src="https://static.toiimg.com/thumb/msid-67586673,width-800,height-600,resizemode-75,imgsize-3918697,pt-32,y_pad-40/67586673.jpg"/>
</div>
</div>
You can store all the possible image sources in an array, pick a random element each time, and append a new <img> element with the chosen source to the document.
const srcs = ['https://i.pinimg.com/originals/7a/af/0f/7aaf0f1d48f57b7779c0fbcf103c2d0f.jpg', 'https://www.coopmcs.com/dotclear/public/chat.png'];
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
const img = document.createElement('img');
img.classList.add('image');
img.src = srcs[Math.floor(Math.random() * srcs.length)];
img.width = '150';
img.height = '150';
img.onload = function(){
img.style.left = x - img.width / 2 + 'px';
img.style.top = y - img.height / 2 + 'px';
}
document.body.appendChild(img);
}
.image {
position: absolute;
}
var img_cats = ['https://www.coopmcs.com/dotclear/public/chat.png',
'https://static.toiimg.com/thumb/msid-67586673,width-800,height-600,resizemode-75,imgsize-3918697,pt-32,y_pad-40/67586673.jpg'
]
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("cats");
cat.src = img_cats[Math.floor(Math.random() * img_cats.length)];
cat.style.display = '';
cat.style.position = 'absolute';
cat.style.left = x - cat.width / 2 + 'px';
cat.style.top = y - cat.height / 2 + 'px';
}
.image{
width:100px;
height:auto;
}
#cat1{
background-color:red;
width:100px;
height: auto;
}
<div class="container">
<img alt="catAppear" class="image" id="cats" src="" style="display: none"/>
</div>
</div>

For Loop not working and cloning Javascript

I've tried all sorts of things to figure out why my code isn't however, I can't seem to find out why. `
var numberOfFaces = 5;
var theleftside = document.getElementById ("leftSide");
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var theRightSide = document.getElementById("rightSide");
function generatefaces () {
for (var i = 1; i < numberOfFaces; i++) {
var img = document.createElement("img");
img.src = "smile.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
theleftside.appendChild(img);
}
}
<style media="screen">
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
</style>
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
`
I am trying to generate 5 images (smiley faces) on the lefside div at different positions, then trying to clone it to the right hand side,
I'm new with JS, so hints and tips would be much appreciated.
Because you just implemented a function but did not call it. Try adding
generatefaces();
at the end.
Two fold firstly you need to, as burkay says, call the function generatefaces().
Secondly you need to create a second element for the right side using img.cloneNode(true) this creates a duplicate so you can then append that to the right side.
Also you are generating the random position outside of the loop so the same random position is used for each img you instead need to create a random position for every img by moving it inside the loop.
Example:
var numberOfFaces = 5;
var theleftside = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
// You need to call this function
generatefaces()
function generatefaces() {
for (var i = 1; i < numberOfFaces; i++) {
// Generate the new random position for each img
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var img = document.createElement("img");
// The location of your face image
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Emojione_1F60E.svg/64px-Emojione_1F60E.svg.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
// Creates a duplicate version of the image
var imgright = img.cloneNode(true);
theleftside.appendChild(img);
// Appends the duplicate image to the right side
theRightSide.appendChild(imgright);
}
}
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
Hope this helps!

Zoom in picture on hover using javascript

I'm new with JS.
https://codepen.io/Maartinshh/pen/VbGOvm
Here's my code:
html
<img id="imgZoom" width="200px" height="200px" onmousemove="zoomIn(event)" onmouseout="zoomOut()" src="https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAA20AAAAJDZhZjAwOTE3LTExMDQtNDE5OC05NDdhLWUxYTU0ODJiZTdkYQ.png">
<div id="overlay" onmousemove="zoomIn(event)"></div>
css
#overlay {
border: 1px solid black;
width: 450px;
height: 450px;
position: absolute;
display: inline-block;
background-image: url('https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAA20AAAAJDZhZjAwOTE3LTExMDQtNDE5OC05NDdhLWUxYTU0ODJiZTdkYQ.png');
background-repeat: no-repeat;
}
js
function zoomIn(event) {
var element = document.getElementById("overlay");
element.style.display = "inline-block";
var img = document.getElementById("imgZoom");
var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
element.style.backgroundPosition = (-posX * 1) + "px " + (-posY * 1) + "px";
}
function zoomOut() {
var element = document.getElementById("overlay");
element.style.display = "none";
}
Problem that occurs: If you see, then when I mouseover picture on left side, the right side (zoomed) picture, doesn't really follow correctly with zoom. What am I doing wrong?
Also, how can I change zoom level (zoom closer)?
Thanks in advance.
You need to do some calculations to add extra offset to place img at center of the div
var offY = (element.clientHeight -img.clientHeight)/2;
var offX = (element.clientWidth -img.clientWidth)/2;
edited codepen here

Categories