Body onclick go to textarea

2019-08-04 05:33发布

问题:

This may not seem like a useful script, but I need something that will basically allow the user to click anywhere on the page and the cursor will go to the textarea.

How I imagine this happening is by having but I don't know that much about javascript to do this.

When the user clicks on the body, paragraph, image, or anything inside the body the cusor will automatically go to the textarea and he will be able to type in it.

I know this doesn't seem like it would be useful for anything, but trust me, I have a use for it. Thanks for the help!!

回答1:

Easy with jquery. But how useful, I don't know.

$('body').on('click', function(){
  $('textarea').focus();
});


回答2:

Vanilla JS:

document.onclick = function(){ document.getElementById('yourIDHere').focus(); }


回答3:

without jQuery (pure JS):

document.body.addEventListener('click', 
function(){
  document.getElementsByTagName('textarea')[0].focus();
});