Click on the screen or any element to execute a function

S.alhaider :

How can I reverse a function so when I click on an input it transforms the y value to -100% and when i click elsewhere on the screen or another element it reverse so the value returns to 0%.

I want to do it in js not in css

let movingName = document.querySelectorAll('.span-name');
let input = document.getElementsByTagName('input')

input[0].onclick = function() {
  movingName[0].style.transform = "translateY(-100%)";
}
.span-name {
  position: relative;
  color: black;
  bottom: 34px;
  left: 10px;
  font-size: 18px;
  padding: 2px;
  z-index: 1;
  pointer-events: none;
  display: block;
  width: fit-content;
  transition: 500ms;
}
<input type="email" name="email_config" required>
<span class="span-name">Email Configuration</span>

d_bhatnagar :

Try using the body to get that click event and filter the events basis the target.

let movingName = document.querySelectorAll('.span-name');
let input = document.getElementsByTagName('input')

document.getElementsByTagName('body')[0].onclick = function(e) {
    var tagName = e.target.tagName;
    if (tagName !== 'INPUT') {
        movingName[0].style.transform = "translateY(100%)";
    }
}    

input[0].onclick = function() {
  movingName[0].style.transform = "translateY(-100%)";
}
.span-name {
  position: relative;
  color: black;
  bottom: 34px;
  left: 10px;
  font-size: 18px;
  padding: 2px;
  z-index: 1;
  pointer-events: none;
  display: block;
  width: fit-content;
  transition: 500ms;
}
<div style="height:100vh; width:100vw">
    <input type="email" name="email_config" required>
    <span class="span-name">Email Configuration</span>
</div>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31998&siteId=1