Open In App

How to Create a Toggle to Show/Hide Divs in jQuery ?

Last Updated : 13 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A toggle button acts like a switch to hide and show the HTML elements. If a toggle button is ON, it will show the div element. Otherwise, it will hide the element just like a switch, if it gets ON the supply will start, otherwise, it stops the supply. We can use the below approaches to create a toggle button in jQuery.

Using the hide() and show() methods

The hide() and show() methods are respectively used to hide and show an HTML element. We will use these methods to toggle the div element in jQuery.

Syntax:

$('element_selector').show();
$('element_selector').hide();

Example: The below code example is a practical implementation of the hide and show methods to create a toggle button to toggle a div.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        How to create canvas of the same
        size as a div in a grid?
    </title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 100%;
            grid-template-rows: 100px;
            height: 100%;
            width: 100%;
            text-align: center;
        }
 
        .toggle-outer{
            height: 20px;
            width: 50px;
            border-radius: 20px;
            border: 1px solid #ccc;
            background-color: #f4f4f4;
            margin: auto;
            position: relative;
            transition: all 0.3s ease-in;
            cursor: pointer;
        }
 
        .toggle-outer.checked{
            background-color: blue;
        }
 
        .toggle-inner{
            height: 18px;
            width: 18px;
            border-radius: 50%;
            position: absolute;
            left: 0;
            background-color: #fff;
            border: 1px solid #ccc;
            transition: all 0.3s ease-in;
        }
 
        .toggle-outer.checked .toggle-inner{
            left: 30px;
        }
 
        input[type="checkbox"]{
            display: none;
        }
 
        #toggleLabel{
            cursor: pointer;
        }
 
        #result{
            display: none;
        }
    </style>
</head>
 
<body>
    <div class="container">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h3>
            Toggle the div element by clicking the below
            toggle button.
        </h3>
        <div class="toggle-outer">
            <div class="toggle-inner">
                <input type="checkbox" id="toggle">
            </div>
        </div>
        <label id="toggleLabel" for="toggle">
            ON
        </label>
        <div id="result">
            <h3>
                This is the div that toggles on click <br/>
                to the above toggle button.
            </h3>
        </div>
    </div>
 
    <!-- jQuery CDN Link -->
    <script src=
            integrity=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer">
    </script>
 
    <!-- Custom Script -->
    <script>
        $(document).ready(() => {
            $('.toggle-outer').click(function(){
                $(this).toggleClass('checked');
                const res = $('#result');
                if(res.css('display') === 'none'){
                    res.show(300);
                    $('#toggle').attr('checked', true);
                    $('#toggleLabel').text('OFF');
                }
                else{
                    res.hide(300);
                    $('#toggle').attr('checked', false);
                    $('#toggleLabel').text('ON')
                }
                 
            })
        });
    </script>
</body>
 
</html>


Output:

divToggleGIF

Using the toggle() method

We can use the toggle() method of jQuery to hide and show the div element.

Syntax:

$('element_selector').toggle();

Example: The below code example uses the toggle method to create a toggle button to toggle div element.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        How to create canvas of the same
        size as a div in a grid?
    </title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 100%;
            grid-template-rows: 100px;
            height: 100%;
            width: 100%;
            text-align: center;
        }
 
        .toggle-outer{
            height: 20px;
            width: 50px;
            border-radius: 20px;
            border: 1px solid #ccc;
            background-color: #f4f4f4;
            margin: auto;
            position: relative;
            transition: all 0.3s ease-in;
            cursor: pointer;
        }
 
        .toggle-outer.checked{
            background-color: blue;
        }
 
        .toggle-inner{
            height: 18px;
            width: 18px;
            border-radius: 50%;
            position: absolute;
            left: 0;
            background-color: #fff;
            border: 1px solid #ccc;
            transition: all 0.3s ease-in;
        }
 
        .toggle-outer.checked .toggle-inner{
            left: 30px;
        }
 
        input[type="checkbox"]{
            display: none;
        }
 
        #toggleLabel{
            cursor: pointer;
        }
 
        #result{
            display: none;
        }
    </style>
</head>
 
<body>
    <div class="container">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h3>
            Toggle the div element by clicking the below
            toggle button.
        </h3>
        <div class="toggle-outer">
            <div class="toggle-inner">
                <input type="checkbox" id="toggle">
            </div>
        </div>
        <label id="toggleLabel" for="toggle">
            ON
        </label>
        <div id="result">
            <h3>
                This is the div that toggles on click <br/>
                to the above toggle button.
            </h3>
        </div>
    </div>
 
    <!-- jQuery CDN Link -->
    <script src=
            integrity=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer">
    </script>
 
    <!-- Custom Script -->
    <script>
        $(document).ready(() => {
            $('.toggle-outer').click(function(){
                $(this).toggleClass('checked');
                const res = $('#result');
                if(res.css('display') === 'none'){
                    $('#toggle').attr('checked', true);
                    $('#toggleLabel').text('OFF');
                }
                else{
                    $('#toggle').attr('checked', false);
                    $('#toggleLabel').text('ON')
                }
                res.toggle();               
            })
        });
    </script>
</body>
 
</html>


Output:

divToggleGIF

Using the css() method

The css() method be used to hide and show a div by passing the display property with block and none values as parameters according to the current condition.

Syntax:

$('elemen_selector').css('display', 'none');
$('elemen_selector').css('display', 'block');

Example: The below code example implements the css() method to toggle the div element through toggle button.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        How to create canvas of the same
        size as a div in a grid?
    </title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 100%;
            grid-template-rows: 100px;
            height: 100%;
            width: 100%;
            text-align: center;
        }
 
        .toggle-outer{
            height: 20px;
            width: 50px;
            border-radius: 20px;
            border: 1px solid #ccc;
            background-color: #f4f4f4;
            margin: auto;
            position: relative;
            transition: all 0.3s ease-in;
            cursor: pointer;
        }
 
        .toggle-outer.checked{
            background-color: blue;
        }
 
        .toggle-inner{
            height: 18px;
            width: 18px;
            border-radius: 50%;
            position: absolute;
            left: 0;
            background-color: #fff;
            border: 1px solid #ccc;
            transition: all 0.3s ease-in;
        }
 
        .toggle-outer.checked .toggle-inner{
            left: 30px;
        }
 
        input[type="checkbox"]{
            display: none;
        }
 
        #toggleLabel{
            cursor: pointer;
        }
 
        #result{
            display: none;
        }
    </style>
</head>
 
<body>
    <div class="container">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h3>
            Toggle the div element by clicking the below
            toggle button.
        </h3>
        <div class="toggle-outer">
            <div class="toggle-inner">
                <input type="checkbox" id="toggle">
            </div>
        </div>
        <label id="toggleLabel" for="toggle">
            ON
        </label>
        <div id="result">
            <h3>
                This is the div that toggles on click <br/>
                to the above toggle button.
            </h3>
        </div>
    </div>
 
    <!-- jQuery CDN Link -->
    <script src=
            integrity=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer">
    </script>
 
    <!-- Custom Script -->
    <script>
        $(document).ready(() => {
            $('.toggle-outer').click(function(){
                $(this).toggleClass('checked');
                const res = $('#result');
                if(res.css('display') === 'none'){
                    $('#toggle').attr('checked', true);
                    $('#toggleLabel').text('OFF');
                    res.css('display', 'block');
                }
                else{
                    $('#toggle').attr('checked', false);
                    $('#toggleLabel').text('ON');
                    res.css('display', 'none');
                }             
            })
        });
    </script>
</body>
 
</html>


Output:

divToggleGIF



Similar Reads

How to set background color of all divs in which attribute name ends with 'geeks' in jQuery ?
In this article, we will select all HTML div's with the value of name attribute ending with 'geeks' and used CSS background property to set the background color to green. Syntax: The following syntax can be used to get the above. $( "div[name$='geeks']" ).css( "background", "green" ); Approach : Create some tags with some names attribute value endi
2 min read
How to Create Responsive Divs in Bootstrap ?
To create responsive divs in Bootstrap, utilize the grid system with container and row classes. Define columns using col classes and specify breakpoints for different screen sizes. This ensures divs adjust their layout and size responsively across devices. Below are the approaches to creating responsive div in Bootstrap: Table of Content Using Boot
2 min read
Blaze UI Tables using divs
Blaze UI is a free open source UI Toolkit that provides a great structure for building websites quickly with a scalable and maintainable foundation. All components in Blaze UI are developed mobile-first and rely solely on native browser features, not a separate library or framework. It helps us to create a scalable and responsive website fast and e
3 min read
How to prevent inline-block divs from wrapping ?
The display: inline-block; is a layout property in CSS that does not add a line break after the element. As a result, the elements can sit next to each other. The major difference between display: inline; and display: inline-block; is that, display: inline-block; also allows us to set the width and height of the element. We can prevent inline-block
5 min read
How to find all divs with a name attribute that contains word 'geeks' and sets the background color ?
jQuery contains attribute selectors with the help of which we can select the elements with name attribute as a particular string or select the elements which contain a particular string or begin with a particular string or ends with a particular string or don't contain a particular string as a name attribute. In this article, we will learn to find
4 min read
Why are fragments better than container divs ?
React Fragments are a modern way of adding multiple elements to a React Component without wrapping them in additional DOM nodes. React.js renders the JSX using the return statement. To render a component, we use the render method, which renders a single root node at a time. Whenever we need to render multiple elements, we need to enclose them in a
9 min read
How to animates first div left property and synchronizes the remaining divs ?
In this article, we will learn how to animate a division element's left property in sync with the other division elements. This can be used in situations where multiple division elements have to be repositioned or animated using only one property. Approach: We will be using the jQuery click(), animate(), gt() and css() methods. Each element will th
2 min read
React Fragments: Eliminating Unnecessary Divs in the DOM
React Fragments function as wrapper elements that help us to group multiple components without using any additional DOM node. Fragments in React avoid unnecessary div tags or containers which helps in maintaining an efficient DOM structure. Table of Content What are React Fragments?Shorthand Syntax for FragmentsReact Fragments and their impact on D
3 min read
How to create slide left and right toggle effect using jQuery?
The task here is to create a slide left and right toggle effect in the JQuery, you can use the jQuery animate() method. .animate() method: It is used to change the CSS property to create the animated effect for the selected element. Syntax: (selector).animate({styles}, para1, para2, para3); Approach: Actual Box width is stored in the variable whose
3 min read
How to create Disable flip toggle switch using jQuery Mobile ?
jQuery Mobile is a web based technology used to make responsive content that can be accessed on all smartphones, tablets and desktops. In this article, we will be making Disable flip toggle switch using jQuery Mobile. Approach: First, add jQuery Mobile scripts needed for your project. &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.
1 min read