How to create a function in which a box moves in accordance with 2 user inputs (direction and # of pixels to move)
Tags: javascript,html,css
Problem :
Here's what I have so far:
The following is my CSS for the box:
p
{
width: 100px;
padding: 25px;
border: 25px solid red;
margin: 25px;
position: fixed;
top: 100px;
}
And here is the JavaScript and HTML I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Box Mover</title>
<link rel="stylesheet"; style="text/css"; href="style.css">
</head>
<script>
function initialize()
{
var positionBox = document.getElementById("positionBox");
positionBox = addEventListener("click", moveBox);
}
function moveBox()
{
var positionBox = document.getElementById("positionBox");
positionBox.style.position = "absolute";
}
</script>
<body>
<p>This is a box.</p>
<form>
Number of pixels to move:
<input id="numPixels">
<br>
<br>
Direction to move:
<select id="directionSelection">
<option>Up</option>
<option>Down</option>
<option>Left</option>
<option>Right</option>
</select>
<br>
<br>
<input id="positionBox" type="button" value="Move Box">
</form>
</body>
</html>
The part I am stumped on is how I can get my positionBox button to interact with my directionSelection drop-down menu and numPixels within my JavaScript. Could someone help me out here?
In my class yesterday, my prof showed us an example of getting a button to move with hard-coded parameters, but now I need to do that with a box, making it move in the direction the user specifies, along with the number of pixels to move. I could also post that example code if it could be helpful to anyone.
Solution :
The part I am stumped on is how I can get my positionBox button to interact with my directionSelection drop-down menu and numPixels within my JavaScript
In your moveBox
function, use document.getElementById("numPixels").value
and document.getElementById("directionSelection").value
to get the number of pixels and the direction to move.
showed us an example of getting a button to move with hard-coded parameters, but now I need to do that with a box
To be able to move the box from your moveBox
function, you will need to add an id
attr to the <p>This is a box.</p>
element so that you can select it with var box = document.getElementById("myBox");
. Then, apply the values to box.style.top
and box.style.left
to move the box around instead of applying the values to the positionBox
.