Denver P. Denver P. - 5 months ago 16
HTML Question

JavaScript AddEventListener exceptions

At the moment, this code is working perfectly for me:

function click(event){
var header = document.getElementById('header');
var text = document.createElement('textarea');
text.multiline = true;
text.cols = 30;
text.rows = 6;
text.style.cssText = "position: absolute; margin-left:" + event.clientX + "px; margin-top:" + (event.clientY - 50) + "px;";
header.parentNode.insertBefore(text, header.nextSibling);
}
document.addEventListener("click", click);


But I'm wondering if you can stop it from activating when you click on the text area.

Answer

Test the target-node using event.target.nodeName

function click(event) {
  if (event.target.nodeName.toUpperCase() !== 'TEXTAREA') {
    var header = document.getElementById('header');
    var text = document.createElement('textarea');
    text.multiline = true;
    text.cols = 30;
    text.rows = 6;
    text.style.cssText = "position: absolute; margin-left:" + event.clientX + "px; margin-top:" + (event.clientY - 50) + "px;";
    header.parentNode.insertBefore(text, header.nextSibling);
  }
}
document.addEventListener("click", click);
<header id='header'>Header</header>