0

I'm trying to show a textarea element when I click on an input element. The goal is to show the textarea, but when I click anywhere else, the textarea disappears.If I click anywhere on the textarea, it stays visible.

I saw a similar example of one on stackoverflow --> Link to similar question

The method was to add an addEventListener to the html tag by using document.documentElement, so basically the whole page, but I was wondering if there was an alternative? And is it safe to add an addEventListener to an entire page?

The code to addEventListener to entire page:

 document.documentElement.addEventListener('click',clickhandler,false);

I'm not trying to be picky either, but I would like to avoid using a timeout on the element


Besides the code above, I first tried using the click event, and everything works fine, but when I click anywhere else the textarea doesn't disappear.

I then tried the focus/blur events, but when the input loses focus, the textarea disappears.

I was thinking of an if conditional for the click function... but I'm not sure how that would work without adding a click event to the entire page...

JSFiddle : http://jsfiddle.net/LghXS/

HTML\

 <input type="text" id="email">
 <textarea id="suggestion"></textarea>

CSS

 textarea{
 display:none;  
 }

JS

var textarea = document.getElementById('suggestion');

var input = document.getElementById('email');

// Using the Click Event
input.addEventListener('click',function(){
  var display = textarea.style.display;

  if(display === '' || display === 'none'){
    textarea.style.display='inline-block';
  }else{
    textarea.style.display='none';
  }
});

// Using the Focus and Blur
/*
input.addEventListener('focus',function(){

  textarea.style.display='inline-block';

  input.addEventListener('blur',function(){
  textarea.style.display='none';
  });
});
*/

Sooo, any ideas?

Community
  • 1
  • 1
user3029001
  • 389
  • 3
  • 6
  • 15
  • 2
    Why not add a "blur" on the textarea? – El Guapo Jun 10 '14 at 21:03
  • hmmm, good point! and it could work in this case, but I also have other elements like an input and a div. So when I click on the input, the div will pop up like the example in the link. And the div doesn't have blur associated with it. So I guess to be more clear, a more general strategy – user3029001 Jun 10 '14 at 21:09
  • 2
    Events listeners are often bound to `document` or `body` for delegate listeners or simple global events (like keyboard shortcuts). – zzzzBov Jun 10 '14 at 21:16
  • ohh okay, so I guess it's fine. Thanks. I'll start using that method then unless anyone has an alternative approach. – user3029001 Jun 10 '14 at 21:21

0 Answers0