Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing attributes of an element on clicking outside with Vanilla JS

Tags:

javascript

How can I remove an attribute of an element on click outside or on another div of same type? Here's my code:

HTML:

<div id="container">
  <div data-something></div>
  <div data-something></div>
</div>

JavaScript:

var elements = document.querySelectorAll("[data-something]");    

Array.prototype.forEach.call(elements, function(element) {

  // Adding
  element.onclick = function() {
    this.setAttribute("data-adding", "");
  };

  // Removing -- Example
  element.onclickoutside = function() {
     this.removeAttribute("data-adding");
  };

});
like image 236
inodaf Avatar asked Feb 11 '23 02:02

inodaf


2 Answers

I would probably use a click handler on the document, and then remove the attribute from any element that had it that wasn't in the bubbling path.

document.addEventListener("click", function(e) {
    Array.prototype.forEach.call(document.querySelectorAll("*[data-adding][data-something]"), function(element) {
        var node, found = false;
        for (node = e.target; !found && node; node = node.parentNode) {
            if (node === element) {
                found = true;
            }
        }
        if (!found) {
            element.removeAttribute("data-adding");
        }
    });
}, false);

...or something along those lines.

Live Example:

    document.addEventListener("click", function(e) {
      Array.prototype.forEach.call(document.querySelectorAll("*[data-adding]"), function(element) {
        var node, found = false;
        for (node = e.target; !found && node; node = node.parentNode) {
          if (node === element) {
            found = true;
          }
        }
        if (!found) {
          element.removeAttribute("data-adding");
        }
      });
    }, false);
*[data-adding] {
  color: red;
}
<div data-adding data-something>One</div>
<div data-adding data-something>Two</div>
like image 50
T.J. Crowder Avatar answered Feb 12 '23 16:02

T.J. Crowder


You can use Node.contains() inside a global click event handler to check if a click is outside an element, and handle the event appropriately:

box = document.getElementById('box');
lastEvent = document.getElementById('event');

box.addEventListener('click', function(event) {
  // click inside box
  // (do stuff here...)
  lastEvent.textContent = 'Inside';
});

window.addEventListener('click', function(event) {
  if (!box.contains(event.target)) {
    // click outside box
    // (do stuff here...)
    lastEvent.textContent = 'Outside';
  }
});
#box {
  width: 200px;
  height: 50px;
  background-color: #ffaaaa;
}
<div id="box">Click inside or outside me</div>

<div>Last event: <span id="event">(none)</span>
</div>
like image 26
Frxstrem Avatar answered Feb 12 '23 14:02

Frxstrem