Conceal an element from view upon clicking on it

Task at Hand :

  • Implement a smooth element hiding effect upon clicking, similar to the behavior on this website , where the letter A fades away smoothly when clicked.
  • Is it possible to achieve this effect using only HTML, CSS, and JavaScript?

    var targetElement = document.getElementById('target-element');

document.getElementById('hide-button').onclick = function () {
    targetElement.className = 'hidden';
};

document.getElementById('show-button').onclick = function () {
    targetElement.className = '';
};
       #target-element {
    transition-property: visibility, opacity;
    transition-duration: 0s, 1s;
}

#target-element.hidden {
    opacity: 0;
    visibility: hidden;
    transition-property: opacity, visibility;
    transition-duration: 1s, 0s;
    transition-delay: 0s, 1s;
}
<a href="#" id="target-element">Text</a>
<button id="hide-button">Hide</button>
<button id="show-button">Show</button>

Answer №1

To implement this feature, utilize jQuery's fadeOut function as demonstrated in the code snippet below:

jQuery Example

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>FadeOut Demo</title>
  <style>
    .hide {
      font-size: 150%;
      cursor: pointer;
      text-align: center;
    }
    
    h1 {
      text-align: center;
    }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>

  <div class="hide">
    <h1>A</h1>
    <p>
      Clicking on this paragraph will cause it to fade away.
    </p>
  </div>
  <script>
    $(".hide").click(function() {
      $(".hide").fadeOut("slow");
    });
  </script>

</body>

</html>

JavaScript Implementation

function fadeOutEffect() {
  var fadeTarget = document.getElementById("hide");
  var fadeEffect = setInterval(function() {
    if (!fadeTarget.style.opacity) {
      fadeTarget.style.opacity = 1;
    }
    if (fadeTarget.style.opacity > 0) {
      fadeTarget.style.opacity -= 0.1;
    } else {
      clearInterval(fadeEffect);
    }
  }, 200);
}

document.getElementById("hide").addEventListener('click', fadeOutEffect);
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>FadeOut Demo</title>
  <style>
    #hide {
      font-size: 150%;
      cursor: pointer;
      text-align: center;
    }
    
    h1 {
      text-align: center;
    }
  </style>
</head>

<body>

  <div id="hide">
    <h1>A</h1>
    <p>
      Clicking on this paragraph will make it fade away.
    </p>
  </div>

</body>

</html>

Answer №2

If you want to make something disappear smoothly on a webpage, consider using the jQuery fadeOut() effect. Check out the reference from W3Schools below:

https://www.w3schools.com/jquery/eff_fadeout.asp

By clicking on the "try it yourself>" button, you can tweak the code to suit your needs.

For another practical example, take a look at this working demo:

https://jsfiddle.net/kag4jqyh/

Answer №3

Give this a shot:

$(document).ready(function() {
    $('#spantext').on('click', function() {
      // $(this).hide();

      $(this).fadeOut("slow"); // You can slow down the hiding effect
        
    });

    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="spantext">This is some text in a span element.</span>

Answer №4

Here is a solution using plain JavaScript instead of jQuery

HTML

<a href="#" id="foo" class="foo">Text</a>
<br />
<button id="hide-button" onclick="hideButton()">Hide</button>
<button id="show-button" onclick="showButton()">Show</button>

JavaScript

const hideButton = () => {
    document.getElementById("foo").classList.add('hidden');
}

const showButton = () => {
    document.getElementById("foo").classList.remove('hidden');
}

CSS

 .foo {
  transition-property: visibility, opacity;
  transition-duration: 0s, 1s;
}

.foo.hidden {
  opacity: 0;
   visibility: hidden;
   transition-property: opacity, visibility;
   transition-duration: 1s, 0s;
   transition-delay: 0s, 1s;
}

Answer №5

If you're looking to create a simple animation to conceal the view, there is an easy solution available.

One way to achieve this is by utilizing the following code snippet:

   <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn1").click(function(){
                $("#box").animate({opacity: 0});
            });
            $("#btn2").click(function(){
                $("#box").animate({opacity: 1});
            });
        });
    </script>

    </head>
    <body>
        <button id="btn1">Animate</button>
        <button id="btn2">Reset</button>
        <div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;"></div>
    </body>

Answer №6

Looking to implement JavaScript instead of relying on jQuery? Give this a shot:

/******define time-delay only in s(seconds)****/
    var timeSlot = '.3s';
     function hide(obj){
        obj.style.visibility= 'hidden';
        obj.style.opacity= 0.8;
        obj.style.transition= 'visibility 0s linear'+timeSlot+', opacity '+timeSlot+' linear';
    }
.div1 {
          font-size: 1.2rem;
          cursor: pointer;
          text-align: center;
          margin-top:-100px;
       }
.logo {
         font-size: 10rem;
      }
<div class="div1" onclick="hide(this);">
    <h1 class="logo">A</h1>                 
 </div>

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

The controller remains unresponsive when attempting to activate the button on the webpage

I'm a beginner in frontend development and I'm currently working on a website that uses Thymeleaf. On this website, there is a div block with a button. Please take a look at the HTML code below, specifically the button at the last three rows. &l ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

Maintaining fixed panels as you scroll through a centrally aligned layout

I am looking to create a layout with three divs set up as columns. The outer two will be for navigation and need to stay in place while the user scrolls, but the middle section will contain content that should scroll normally along with the page. I know t ...

Include a return or delete from the default IO statement

I am utilizing an intersection observer that alters the header's font-color and background-color based on the content intersecting with it. This change is determined by the presence of data-color and data-background attributes declared on the div/sect ...

Here's a way to run JavaScript code from a <script> tag included in an AJAX response

Currently, I am making a jQuery GET request in this format: $.get($(this).attr("href"), $(this).serialize(), null, "script"); I'm expecting the response to be enclosed in script tags. I know that the browser won't run the response if it contai ...

Jasmine tests for AngularJS directive failed to invoke the link function

I can't figure out why the link function of my directive isn't being called in a Jasmine test. I've created a simple example to illustrate. Here is the code for my directive (TestDirective.js): 'use strict'; angular.module(&ap ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

Tips for accessing every "results" (parameters) from an API

Here is the response I received after making an API call in my attempt to retrieve each "bloc" result using a .forEach. const app = express(); const axios = require('axios') jobList = []; app.get('/getAPIResponse', function(req, res) ...

Node text: three.js and ngraph.tree working together

I am currently working on developing a 3D network (network of people) for a browser using three.js and ngraph. The graph has been successfully created, but the nodes are currently displayed as squares. My goal is to replace these squares with the text "nod ...

The slash character is escaped by the RegExp constructor, but the dot character is

Consider the following code: console.log(new RegExp('.git')); console.log(new RegExp('scripts/npm')); which produces the following output: /.git/ /scripts\/npm/ The puzzling question here is - why does it escape the slash in &a ...

`methods that exhibit peculiar behaviors`

My routes are set up with the get method. app.get("/info/teachers", controller1); app.get("/info/teachers/:teacherid", controller2); app.get("/info/students", controller3); app.get("/info/students/:studentid", contr ...

Guide to creating a vertical handler that can be resized

Did you know that you can resize tables in http://www.jsfiddle.net? I'm curious about how to resize just the "Vertical Handler". Could someone share the source code with me? If possible, please provide an example on http://www.jsfiddle.net. ...

Fetching client-side data in a Functional Component using Next JS: The proper approach

I have a functional component that includes a form with existing data that needs to be populated and updated by the user. Within this component, I am using a custom hook for form handling. Here is an example: const [about, aboutInput] = useInput({ t ...

How can you insert a title or key into an array containing numerous objects using javascript?

I have a function that extracts data from files and returns it in an array const extractTestCases = () => { const filesArray = [] const filterTestSuite = files.filter(test => test.includes('.test.ts')) filterTestSuite.forEach(te ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

JWT authentication for restricted routes

I'm currently developing an application that requires users to log in and allows them to join private groups. I have successfully implemented the login part using JWT, but I'm struggling with how to prevent users from joining private groups until ...

Retrieving Data from all Rows in jQuery DataTables

Is there a way to copy all rows in jQuery DataTables into a JavaScript array by clicking the header checkbox? https://i.sstatic.net/57dTB.png I need to locate where jQuery DataTables store the HTML for the remaining page of rows so that I can manipulate ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

Interpret the ng-model data into the input field

My challenge involves translating a value within an input. The input is disabled to prevent users from typing text into the textbox. Currently, the data is entered using ng-model and appears as shown below: <input ng-model="reason" ng-disabled="true" t ...