Home » JavaScript Tutorial

focus() Method with Example in JavaScript

JavaScript | focus() Method: Here, we are going to learn about the focus() method with example in JavaScript.
Submitted by Siddhant Verma, on January 10, 2020

JavaScript | focus() Method

The focus() method in DOM is used to give focus to an element. Its counterpart is blur() method which removes that particular element from focus. It does not take any parameters and doesn't have a return type.


<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Focus method</title>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

    body {
        background: palegreen;
    form {
        position: absolute;
        top: 50px;
        left: 250px;
        border: 2px solid white;
        background: whitesmoke;
        text-align: center;
        padding: 12px;
        margin: 12px;
        width: 700px;

    <div class="container">
        <form action="">
            <input type="text" name="Name" id="name" placeholder="Name">
            <input type="email" name="Email" id="email" placeholder="Email">
            <input type="password" name="Password" id="password" placeholder="Password">
            <button class="btn">Submit form!</button>



JavaScript | focus() method | Example 1

You can see that materialize styles its forms in such a way that when you click an input field, a blue underline appears underneath that field.

JavaScript | focus() method | Example 2

On clicking the password field, there’s a blue underline indicating that the field is in focus. We can set a field to focus without clicking it by triggering it an onmousemove event.

<input type="text" name="Name" id="name" placeholder="Name" onmousemove="focus()">
JavaScript | focus() method | Example 3

Now, when I move my mouse over the name input field, the onmousevent gets triggered and it fires the focus function due to which we see the little blue underline on the field.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.