I want my picture to go step by step to the left until 1300px with the jobbra button so I have added an if statement to achieve this, but this doesn't work to onlclick. If I delet the if statement the button click function works by itself. What is the problem with my if statement? Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PingPongKép</title>
<link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<div id="ilonakep">
<img src="/img/ilona.jpg" alt="ilona">
</div>
<p id="gombok">
<button onclick="balra()">Balra</button>
<button onclick="jobbra()">Jobbra</button>
</p>
<script>
var jobbAnim = 1;
var speed = 1;
var balAnim = 0;
function jobbra() {
if ( jobbAnim < 1300){
var jobbAnim = jobbAnim + speed;
}
document.getElementById("ilonakep").style.marginLeft = jobbAnim + "px";
}
function balra() {
document.getElementById("ilonakep").style.marginLeft = balAnim + "px";
}
</script>
</body>
</html>
Hopes this solves the issue
var jobbAnim = 1; var speed = 10; var balAnim = 0; var max = 80; // 1300 here. function jobbra () { var ilonakep = document.getElementById("ilonakep"); if (ilonakep.clientWidth + parseInt(ilonakep.style.marginLeft) < max || ilonakep.style.marginLeft == '') { jobbAnim = jobbAnim + speed; ilonakep.style.marginLeft = jobbAnim + "px"; } else console.log(max+' reached'); } function balra () { document.getElementById("ilonakep").style.marginLeft = balAnim + "px"; jobbAnim = 0; }
#ilonakep { width: 50px; height: 50px; border: 1px solid #000; margin: 0; }
<div id="ilonakep"> <img src="/img/ilona.jpg" alt="ilona"> </div> <p id="gombok"> <button onclick="balra()">Balra</button> <button onclick="jobbra()">Jobbra</button> </p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.