Day 7 ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ”ฅ, Interactive Web: Exploring JavaScript Events and Interactivity

Day 7 ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ”ฅ, Interactive Web: Exploring JavaScript Events and Interactivity

ยท

5 min read

Welcome back, talented programmers! We'll take an interesting journey into the realm of JavaScript events and interaction in this blog article. Prepare to make your web pages come to life and respond to user activities. Prepare to develop color-changing buttons, slidable pictures, and forms that check user input. Let's get started with interaction!

Understanding JavaScript Events:

Events are occurrences or events that occur in the browser window, such as a button click, mouse movement, or keyboard input. We can use JavaScript to catch and manage these events, allowing us to construct interactive and dynamic websites.

Event Handlers:

Event handlers are functions that are run when an event happens. Event handlers are attached to HTML elements and respond to user actions, activating the required functionality.

// Event handler function
function handleClick() {
  console.log("Button clicked!");
}

Explanation:

In this code sample, we define the handleClick event handler method. When the corresponding event (e.g., button click) happens, this function is called. The function just records the message "Button clicked!" to the console in this case.

// Attaching event handler to a button
const button = document.querySelector("#myButton");
button.addEventListener("click", handleClick);

Explanation:

  • Using document.querySelector(), we choose an HTML element with the id "myButton" in this sample.

  • The button variable contains a reference to this button element.

  • Then, using addEventListener(), we connect an event listener to the button.

  • The "click" event is the one we're looking for, and the related event handler method is handleClick.

Common Event Types:

In JavaScript, there are various event types. Let's look at some popular ones:

1. Click Event:

The click event occurs when an element is clicked by the user.

const button = document.querySelector("#myButton");
button.addEventListener("click", function() {
  console.log("Button clicked!");
});

Explanation:

  • This code sample shows another way to define the event handler function right within the event listener.

  • When you click the button, the anonymous function is called, which reports the message "Button clicked!" to the console.

2. Mouseover and Mouseout Events:

When the mouse cursor enters an element, the mouseover event happens, and when the mouse pointer exits the element, the mouseout event occurs.

 const element = document.querySelector("#myElement");
element.addEventListener("mouseover", function() {
  console.log("Mouse over the element!");
});

element.addEventListener("mouseout", function() {
  console.log("Mouse out of the element!");
});

Explanation:

  • These snippets demonstrate how to use the "mouseover" and "mouseout" events.

  • Using document.querySelector(), we choose an HTML element with the id "myElement" and save it in the element variable.

  • There are now two event listeners: one for the "mouseover" event and one for the "mouseout" event.

  • The "mouseover" event handler function is performed when the mouse cursor enters the element, reporting "Mouse over the element!" to the console.

  • Similarly, when the mouse pointer departs the element, the "mouseout" event handler function is called, and the message "Mouse out of the element!" is logged.

3. Keydown Event:

When a key on the keyboard is pushed, the keydown event is triggered.

document.addEventListener("keydown", function(event) {
  console.log(`Key ${event.key} pressed!`);
});

Explanation:

  • This code sample shows how to use the "keydown" event.

  • For the "keydown" event, we add an event listener to the document object.

  • When a key on the keyboard is pushed, the relevant event handler function is called.

  • The event object, which holds information about the key event, such as the pressed key, is accessed by the function.

  • In this example, we log a message to the console that includes the key that was pushed.

Real-Time Examples:

1. Color Changer:

Create a button that, when pressed, changes the background color of a webpage.

<button id="colorButton">Change Color</button>

<script>
  const button = document.querySelector("#colorButton");
  button.addEventListener("click", function() {
    document.body.style.backgroundColor = "red";
  });
</script>

Explanation:

  • We have an HTML button element in this snippet with the ID "colorButton."

  • We use document.querySelector to select the button and add a click event listener to it.

  • The anonymous function is called when the button is pressed. We access the document.body element, which represents the full homepage, within the function.

  • We alter the background color of the webpage to red by adjusting the style.backgroundColor attribute.

2. Form Validation:

When the submit button is hit, offer a form that verifies if the email input is in a valid format.

<form id="myForm">
  <input type="email" id="emailInput" required>
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.querySelector("#myForm");
  const emailInput = document.querySelector("#emailInput");

  form.addEventListener("submit", function(event) {
    event.preventDefault();
    if (!emailInput.checkValidity()) {
      alert("Please enter a valid email address!");
    } else {
      alert("Form submitted successfully!");
    }
  });
</script>

Explanation:

  • Form validation is demonstrated in this code sample.

  • We have a "myForm" HTML form element with an email input field and a submit button.

  • We use document.querySelector to choose the form and email input.

  • When the user submits the form by clicking the submit button, we attach a submit event listener to it.

  • We use event.preventDefault() within the event listener method to prevent the form from submitting.

  • The checkValidity() function is then used to validate the email input. If the email address is incorrect, we display an alert message requesting that the user supply a legitimate email address. If the email address is correct, we will display a success message confirming that the form was successfully submitted.

Conclusion:

By collecting user activities and responding appropriately, JavaScript events enable us to construct dynamic web pages. We can develop interesting and dynamic user experiences by using the capabilities of event handlers and numerous event kinds. Ready to introduce interaction to your web pages?

Stay tuned for the next blog article, in which we'll look at JavaScript DOM manipulation, which allows us to dynamically change web page elements.

๐Ÿคž Remember to subscribe to remain up to speed on the newest blog entries!

Happy coding!๐Ÿ‘จโ€๐Ÿ’ป

ย