Vinith Almeida
Vinith Almeida

Reputation: 1471

Add a class when clicked on element, remove it when clicked elsewhere

I need to add a class(.highlight) to an element when its clicked upon, and it should be removed when clicked either on the element or anywhere else in the document.

I have managed to add and remove the class when the element is clicked using the classList.toggle() method but have no idea how to remove the class when a click happens in the document.

Here's my HTML, CSS and JS.

<p class="normal" onclick="detectClick(this)">This is paragraph 1</p>
<p class="normal" onclick="detectClick(this)">This is paragraph 2</p>
<p class="normal" onclick="detectClick(this)">This is paragraph 3</p>

.highlight {
    background-color: yellow;
}

function detectClick(element) {
    element.classList.toggle("highlight");
}

And here's where you can see the code in action, http://codepen.io/vbcda/pen/GodZmr

Upvotes: 1

Views: 239

Answers (4)

Yogi
Yogi

Reputation: 7184

A simple lightweight solution

This can be done with just a couple of lines of CSS. The trick in this case is that you must add the tabindex attribute to each P so that it can receive focus.

Run the snippet below and click on the text to try.

p:not(:focus) { background-color: lightgray;}
p:focus { background-color: yellow;}
<p tabindex=1>This is paragraph 1</p>
<p tabindex=2>This is paragraph 2</p>
<p tabindex=3>This is paragraph 3</p>

Upvotes: 1

Nate
Nate

Reputation: 121

if you want to use jquery:

$('.normal').click(function(e){
  e.stopPropagation();
  $(this).toggleClass('highlight');
});

$(document).click(function(){
  $('.normal').removeClass('highlight');
});

Upvotes: 0

Rakesh Patidar
Rakesh Patidar

Reputation: 74

It can happen if you first remove exiting class 'highlight' from the element by using mousedown event by clicking anywhere in the body.

<body onmousedown="outerClick(this)"> // Add this in your html file

function detectClick(element) {
    element.classList.toggle("highlight");
}
function outerClick(el){
  var elements = document.querySelectorAll(".highlight");
  for (var i = 0; i < elements.length; i++) {
      elements[i].classList.remove('highlight');
   }
}

Upvotes: 2

NMunro
NMunro

Reputation: 910

I'd do something like this.

function detectClick(element) {
  var elements = document.getElementsByClassName("normal");
  Array.from(elements).forEach(function(element) {
    element.setAttribute("class", "normal");
  });
  element.setAttribute("class", "normal highlight");
}

You could be explicit and use document.getElementsByClassName("normal highlight") too.

Upvotes: 1

Related Questions