JavaScript Functions And Events | Lecture 32 - BLOG PK
Skip to content

JavaScript Functions And Events | Lecture 32

JavaScript Functions And Events

Let’s begin with Lecture 32 of the HTML5 & CSS3 series. JavaScript Functions & Events – Reusable Code and User Interaction. This lecture is for absolute beginners; even kids can follow along and understand.

🎯 Objective:

By the end of this lecture, you will:

  • Understand how to define and call JavaScript functions
  • Know how to use events like click, mouseover, input, and submit
  • Be able to write reusable code that responds to user actions
  • Create interactive features like form validation , tooltips , and dynamic messages
  • Make your website more powerful and responsive using JavaScript!

πŸ” What Are Functions?

Functions are blocks of code designed to perform a specific task.
You can run them anytime β€” just like pressing a button to turn on a light.

Think of it like this:

If JavaScript is your robot brain, then functions are its buttons β€” each one makes something happen when pressed.

Basic Syntax:
function sayHello() {
    alert("Hello!");
}

To run it:

Think of it like this:

If your webpage was a playground, events would be all the things kids do β€” running, jumping, sliding β€” and JavaScript helps respond to those actions!

πŸ–±οΈ What Are Events?

Events happen when users interact with your webpage β€” like clicking a button, typing in a box, or moving the mouse over an element.

Think of it like this:

If your webpage was a playground, events would be all the things kids do β€” running, jumping, sliding β€” and JavaScript helps respond to those actions!


πŸ”€ Common Event Types
EVENTWHEN IT HAPPENS
clickWhen a user clicks an element
mouseover / mouseoutWhen the mouse enters or leaves an element
inputWhen a user types into a field
submitWhen a form is submitted
keydown / keyupWhen a key is pressed or released
πŸ’» Try This: Build a Greeting Generator with Input

Let’s create a simple script that takes a name from a text box and displays a greeting.

Step 1: Add HTML

Create a new file named:

greeting-generator.html

Add this inside <body>:

<h2>Greeting Generator</h2>
<label for="userName">Enter your name:</label>
<input type="text" id="userName">
<button onclick="showGreeting()">Say Hello</button>

<p id="greetingMessage"></p>
Step 2: Add JavaScript

Before </body>:

<script>
    function showGreeting() {
        let name = document.getElementById("userName").value;

        if (name === "") {
            document.getElementById("greetingMessage").innerHTML = "Please enter your name!";
        } else {
            document.getElementById("greetingMessage").innerHTML = "Hello, " + name + "! 😊";
        }
    }
</script>

πŸŽ‰ Now users can type their name and see a custom greeting appear!

JavaScript Functions And Events
A kid typing into a computer screen clicking a giant button labeled Click Me and seeing a message pop up

πŸ’‘ Bonus: Show Tooltip on Hover

Let’s add a fun tooltip that appears when users hover over a question mark.

Add HTML:
<h2>Hover Over Me!</h2>
<p>What is your favorite color? <span id="tooltip" style="color: blue; cursor: pointer;">❓</span></p>
<div id="tooltipText" style="display: none; background: #333; color: white; padding: 5px; border-radius: 4px; margin-top: 5px;">Your favorite color is blue! 🎨</div>
Add JavaScript:
<script>
    // Show tooltip on hover
    document.getElementById("tooltip").addEventListener("mouseover", function() {
        document.getElementById("tooltipText").style.display = "block";
    });

    // Hide tooltip when not hovering
    document.getElementById("tooltip").addEventListener("mouseout", function() {
        document.getElementById("tooltipText").style.display = "none";
    });
</script>

Now when someone hovers over the ❓ icon, a fun fact appears!

πŸ’‘ Bonus: Form Validation on Submit

Let’s make sure a form is filled out before submitting.

Add HTML:
<h2>Sign Up</h2>
<form onsubmit="return validateForm(event)">
    <label>Name: </label><input type="text" id="signupName"><br><br>
    <label>Email: </label><input type="email" id="signupEmail"><br><br>
    <button type="submit">Submit</button>
</form>

<p id="formResult"></p>
Add JavaScript:
<script>
    function validateForm(event) {
        event.preventDefault(); // Stop actual form submission

        let name = document.getElementById("signupName").value;
        let email = document.getElementById("signupEmail").value;

        if (name === "" || email === "") {
            document.getElementById("formResult").innerHTML = "❌ Please fill in both fields.";
        } else {
            document.getElementById("formResult").innerHTML = "βœ… Thank you, " + name + "! You're signed up.";
        }

        return false; // Prevent page reload
    }
</script>

Now users get instant feedback without leaving the page!

πŸ§ͺ Try It Yourself!

  1. Add a counter button that increases a number every time it’s clicked.
  2. Make a password strength meter that shows a message as the user types.
  3. Use oninput to update a preview live as the user types in a comment box.
  4. Add a dark mode toggle button that changes the theme using JavaScript.
βœ… Summary of What You Learned Today
CONCEPTDESCRIPTION
FunctionA block of code that does something when called
Event ListenerListens for actions like click, hover, input
Common Eventsclick, mouseover, input, submit
ReusabilityWrite once, use many times
User FeedbackShow messages instantly based on user action

πŸš€ Next Lecture Preview:

In Lecture 33 , we’ll explore loops and arrays in JavaScript β€” so you can work with lists of data, repeat tasks automatically, and build dynamic content like quizzes, counters, and more!

Stay Updated

If you found this information useful, don’t forget to bookmark this page and Share.

HTML5 and CSS3 Compleate Series

Najeeb Alam

Najeeb Alam

Technical writer specializes in developer, Blogging and Online Journalism. I have been working in this field for the last 20 years.