User Input in HTML and JavaScript: A Quick Reference

Buttons

Perhaps the most straightforward way to interact with your application is to create a button. Buttons use the <button></button> HTML tag. Make sure to give each button a unique ID so that you can easily reference it with jQuery.

<!-- in your HTML -->
<button id="my-button">Click me!</button>
// in your JavaScript
$("#my-button").on("click", () => {
  // do some stuff
});

Form Elements

Form elements are excellent for allowing users to supply custom settings for their application. Many of these elements are variations on the <input /> tag. Some examples are as follows:

<!-- an ordinary text box -->
<input id="my-input" type="text" />

<!-- a number box -->
<input id="my-input" type="number" />

<!-- a slider -->
<input id="my-input" type="range" />

<!-- a toggle -->
<input id="my-toggle" type="checkbox" />

<!-- a dropdown menu -->
<select id="my-input">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

Generally speaking, you can get the value of most input elements as follows:

$("#my-input").val();

However, checkboxes require a different construction:

$("#my-input").is(":checked");

For more on inputs—as well as how to set useful attributes like minimum and maximum values, step sizes, and default values—look at the MDN page for the input element. Also, if you'd like to make your inputs more user-friendly, you can pretty them up with the <label></label> and/or <fieldset></fieldset> tags.

Mouse and Keyboard

You can get the state of the mouse using jQuery, as follows:

$(document).on("click", () => {
  // do something when you click the mouse
});

$(document).on("mousemove", (event) => {
  // get x and y coordinates of the mouse
  let xValue = event.pageX;
  let yValue = event.pageY;
});

You can also get the state of the keyboard using jQuery, as follows:

$(document).on("keydown", (event) => {
  // get ASCII value of the key that's pressed
  // (check out asciitable.com)
  let asciiValue = event.which;
});

Vocabulary

Self-Quiz

  1. Create a slider that ranges from -1 to 1, with a step size of 0.05 and a default value of 0.05.
  2. Write a function that displays the value of the slider in a <p></p> element below the slider, updating whenever the slider is moved. Hint: look at the jQuery $().on("change") event and $().html() function.

Additional Resources


This page was last modified: .