top of page
Writer's pictureWeb Coding

How to show and hide a HTML element when the user presses a button

Today I will teach you how to hide HTML elements when a button is pressed using only HTML, CSS and JavaScript


HTML and CSS

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
 body{
 min-height100vh;
 displayflex;
 align-itemscenter;
 justify-contentcenter;
        }
 </style>
</head>
<body>
 <div>
 <p id="text" style="display: none;">Text to be displayed</p>
 <button type="button" id="displayBtn">Show</button>

 <script src="script.js"></script>
 </div>
</body>
</html>

JavaScript

let text = document.getElementById('text');
let showBtn = document.getElementById('displayBtn');

showBtn.addEventListener('click'display)

function display(){
 if(text.style.display == 'none'){
 text.style.display = 'block';
 showBtn.innerHTML = 'Hide'
    }
 else {
 text.style.display = 'none';
 showBtn.innerHTML = 'Show';
    }
}

If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on


YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ

Instagram: https://www.instagram.com/coding_for_the_web/

Twitter: https://twitter.com/LearnWebCoding

3 views

Comments


bottom of page