Solution: Move by a Certain Number

Solve the challenge using concepts learned so far.

Customizing behavior based on user input

Add the JavaScript code logic to move the box by user input (We've already added the HTML code for you). Instead of moving the box by a fixed amount, let the user type how many pixels they want the box to move.

Below are some hints to help you get started:

Hints:

  • 1️⃣ Use a <form> and <input type="number">: This lets the user type a number into the input box (We've already done this for you).

  • 2️⃣ Add .addEventListener("submit", ...) to the form: This will run a function when the user submits the form.

  • 3️⃣ Inside your event handler, call event.preventDefault(): Stops the page from refreshing when the form is submitted.

  • 4️⃣ Get the number from the input using event.target.elements.inputName.value: Don’t forget to replace inputName with the actual name of your input.

  • 5️⃣ Convert the string to a number using parseInt(...): This makes sure you're working with a number, not text.

  • 6️⃣ Update the box’s position using .style.left = value + "px": Add "px" to the number so the browser understands it as a CSS value.

See the solution in the widget below:

Get hands-on with 1400+ tech skills courses.