JavaScript: Is there a way to toggle the visibility of an element on click?

I am currently working on writing a code that will allow me to make any part of the screen clickable. When a user clicks on the screen, a message saying "click!" should be displayed. So far, this is the code I have:

HTML:

<html>
    <head>
         <title>Handling Events Anywhere</title>
         <script type="text/javascript" src="anywhere.js"></script>
         <link type="text/css" rel="stylesheet" href="anywhere.css" />
    </head>
    <body id="body" onload="init();">
      <div id="message"> Click! </div>
  </body></html>

JavaScript:

var element;
function init(){
   element = document.getElementById("message");
   document.getElementById("message").style.visibility = "hidden";
   element.onmousedown = displayMessage(element);
   element.onmouseup = hideMessage;
}     
function displayMessage(element) {
   element.style.visibility = "visible";
}
function hideMessage() {
   element.style.visibility = "hidden";   
}

CSS:

body {  
}
div#message{
}

So far, my attempts to show and hide the message when clicked have not been successful. I apologize for any language errors in my explanation. English is not my first language. If anyone could assist me with this, it would be greatly appreciated. Thank you.

Answer №1

let isVisible = true,
elementBody = document.getElementById("body"),
elementMessage = document.getElementById("message");

elementBody.onclick = function() {
     if (isVisible === true) {
        elementMessage.style.visibility = "hidden";
        isVisible = false;
    } else {
        elementMessage.style.visibility = "visible";
        isVisible = true;
    }
}

Update Changed selector to target any part of the screen clicked, as per your request.

Answer №2

Here is a suggested solution:

function toggleVisibility(targetID){
    var target = document.getElementById(targetID),
        visibility = target.style.visibility;
    target.style.visibility = visibility && visibility == 'visible' ? 'hidden' : 'visible';
}

document.body.addEventListener('click', function(){
    toggleVisibility('message');
});

Check out this simple demonstration on JS Fiddle.

An alternative approach using visibility instead of display:

function toggleVisibility(targetID){
    var target = document.getElementById(targetID),
        visibility = target.style.visibility;
    target.style.visibility = visibility && visibility == 'visible' ? 'hidden' : 'visible';
}

document.body.addEventListener('click', function(){
    toggleVisibility('message');
});

Here's another demo on JS Fiddle for reference.

For more information, see the following resources:

Answer №3

If you are looking to hide elements on a webpage using jQuery, there are different approaches you can take. One method is to use the display property rather than the visibility property. When an element is hidden using display: none;, it is completely removed from the layout, whereas with visibility, the element still occupies space.

Here is an example of how to hide an element using display:

<div id="message"> Click! </div>

The CSS for this solution would be:

#message {
   display: none;
}

And here is the jQuery code:

$(document).ready(function(){
    $(window).click(function(){
        $('#message').toggle();
    });
});

You can see a live demo of this in action here.


Alternatively, if you prefer to use the visibility property, here is another solution using jQuery:

HTML:

<div id="message">Click!</div>

jQuery:

$(document).ready(function () {
    $('#message').css('visibility', 'hidden');
    $(window).click(function () {

        if ($('#message').css('visibility') == 'hidden') 
        $('#message').css('visibility', 'visible');

        else $('#message').css('visibility', 'hidden');

    });
});

You can view this second approach in action with a demo here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I obtain hosting XULDocument for a ContentWindow or HTMLDocument within a Firefox extension?

I have a Firefox Extension with a XUL overlay that includes some Javascript with event handlers. One of these event handlers is an EventListener for DOMContentLoaded. I want to load a second overlay only when visiting a specific website. Here is a snippet ...

Jquery loader for loading html and php files

My html and php pages contain a significant amount of data which causes them to take a few extra seconds to load from the server. I was wondering if there is a way to implement a "loader animation" for these pages using jquery. The idea is for the loader a ...

Enhancing Donut Chart with d3.js

After working for several hours, I'm having trouble getting my d3.js donut graph to update with new data. Here's my HTML: <body> <div id="pie"></div> <script src="pie.js"></script> </body> And he ...

Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly. The methods that execute when the cursor enters and leaves my component: // Included in the "methods" section of my Vue component file onMouseEnter( ...

Holding off $ajax requests until specific code finishes executing

I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in t ...

Does SCSS have a specific 'self' identifier?

I am looking to incorporate SCSS styles on the body by default, and then reapply them specifically to the P and LI tags (since I do not have complete control over the site and want to prevent plugins from interfering with my p's and li's). To ac ...

Persist the scroll position within a div even after refreshing a PHP file using AJAX

I have a specific div set up with its own scroll bar, which is being refreshed using AJAX (with a PHP file). Whenever I scroll within this div and trigger a reload, the inner scrollbar resets back to the top. My goal is to retain the position of the scroll ...

Examining the false positive detection of an apparent visibility issue with

My goal is to check if the document is NOT scrollable using this code snippet: $el = document.documentElement const noscroll = $el.clientHeight === $el.scrollHeight // false console.log($el.clientHeight) // 977 console.log($el.scrollHeight) // 991 consol ...

After the page has finished loading, I aim to have the modal window pop up after 10 seconds. Thank you to all!

$(document).ready(function() { var id = "#dialog"; //Calculate screen dimensions var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Adjust mask to cover entire screen $('#mask').css({'wid ...

Should you prioritize internationalizing your image alt attributes?

Do you localize your alt attribute in img tags for internationalization? Is it beneficial in the long run? ...

After closing the modal, I am attempting to reset it, but unfortunately, it is not functioning as expected

I have a modal box with the following structure: <div class="modal-coupon-code"> <center class="show-code"><button type="button" class="btn btn-warning" data-toggle="modal" data-target="#couponcode<?php echo $result->id; ?> ...

Error unfound: [CLIENT_MISSING_INTENTS]: The Client requires valid intents to function properly

I've gone through multiple tutorials, but I keep encountering an uncaught TypeError. Despite following the suggested solutions, the error persists. I even tried implementing the "intent" solution, but it's prompting a change in "const client = ne ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

Customizing the Height of Elements in Bootstrap

When working with two columns in bootstrap, let's say one column has a height of 800 PX. If you want the text in the second column to start after 200 PX, is there a way to achieve this without using padding or margin? Are there any predefined classes ...

The occurrence of "Error [ERR_STREAM_WRITE_AFTER_END]" was noted when trying to write to an HTTP server in

How to set up a new http server using Node.js After launching the server, the initial HTML text is displayed correctly. However, moving to other links in the code (e.g., localhost:5001/about) results in an error appearing in the IDE console. events.js:377 ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

Problem with keyframe animations in Internet Explorer 10

My CSS animation works flawlessly in all modern browsers, except for IE10 which is causing some trouble. It appears that IE is having difficulty properly rotating 360deg. I am still searching for a workaround that won't compromise the functionality in ...

Responsive Bootstrap 4 Login Form with customized top height

This login form was created using Bootstrap 4, starting with a preset that I then customized to fit my needs. As someone new to Bootstrap and CSS, I struggled with making the form responsive. When resizing the window, the top portion gets cut off and is no ...

Tips for live streaming a canvas element using WebRTC

While researching about WebRtc, I stumbled upon this amazing project on GitHub: https://github.com/mexx91/basicVideoRTC I have successfully tested the communication between 2 cameras using node.js. Is it possible to capture a stream from getUserMedia, m ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...