Make a div element fade on click using JavaScript

JavaScript is the programming language that widely used for the Web browser. It can make web pages interactive. JavaScript is easy to learn. In this tutorial, we will learn a cool and an interactive way to fade out a div element on a click of a button.

Let’s start: First of all, we need a basic HTML with a div element in the body. Give the div element a id, to use it inside. CSS and JS.

<!DOCTYPE html>

<html>
<head>
    <link rel="stylesheet" type="text/css" href="./styler.css">
    <title>Fader</title>
</head>

<body>
    
    <div id="source">
        <h1>All these Headings</h1>
        <p>and these paragraphs will be faded.</p>
    </div>

    <button id="doFade">Fade the content</button>
    <button id="fadeRev">Unfade the content</button>

</body>
</html>

In the above code, we have made a div with id “source” containing an h1 heading and paragraph. And added two buttons just below the div to fade-in and fade-out the div. We also added a link referring to the stylesheet which is stored inside the same directory.

Now coming to the CSS(Cascading Style Sheet) to give our div color and size.

#source{
    height: 100px;
    width: 400px;
    background-color: crimson;
    opacity: 1;
    transition: opacity 1s;
}

#source.fade{
    opacity: 0;
}

#source.nofade{
    opacity: 1;
}

In this part of the code, we have selected the div using the id selector(#) and the id name(source). And we have given it a height of 100 pixels and a width of 400 pixels and a background color. We have also declared two sub-classes defining the opacity of the div.

Now we are already halfway through the post, the most important and only thing left is adding the functionality to the buttons. We do this using the JavaScript.

<script>

    var source = document.getElementById('source');

    document.getElementById('doFade').onclick = function () {
        source.classList.toggle('fade');
    }

    document.getElementById('fadeRev').onclick = function () {
        source.classList.toggle('nofade');
    }

</script>

Source is a variable created to access the div with id source and on clicking the first button that has an ID doFade it toggles the ‘fade’ sub-class that has the opacity = 0. And the second button on click toggles the ‘nofade’ subclass that sets the opacity of the div to be 1 again.

THANK YOU

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *