Home » Javascript » jquery – Javascript how to add a click event listener in the body?

jquery – Javascript how to add a click event listener in the body?

Posted by: admin February 26, 2020 Leave a comment

Questions:

How do i add a click event listener to the body so when i click anywhere within the body the .arrow-up and .login-form will fade out.

$(document).ready(function() {
  var arrow = $(".arrow-up");
  var form = $(".login-form");
  var status = false;
  $("#login").click(function(event) {
    event.preventDefault();
    if (status == false) {
      arrow.fadeIn();
      form.fadeIn();
      status = true;
    } else {
      arrow.fadeOut();
      form.fadeOut();
      status = false;
    }
  })

  document.getElementByTagName("body").addEventListener('click', function() {
    arrow.fadeOut();
    form.fadeOut();
    status = false;
  });
})
How to&Answers:

There is no such function as document.getElementByTagName so

Either use:

document.getElementsByTagName("body")[0].addEventListener('click', function() {console.log('clicked')  });

or just:

document.body.addEventListener('click', function() {console.log('clicked')});

And since you anyway use jQuery, you can do

$('body').on('click', function(){console.log('clicked')});