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


i need add class(.highlight) element when clicked upon, , should removed when clicked either on element or anywhere else in document.

i have managed add , remove class when element clicked using classlist.toggle() method have no idea how remove class when click happens in document.

here's html, css , js.

<p class="normal" onclick="detectclick(this)">this paragraph 1</p> <p class="normal" onclick="detectclick(this)">this paragraph 2</p> <p class="normal" onclick="detectclick(this)">this paragraph 3</p>  .highlight {     background-color: yellow; }  function detectclick(element) {     element.classlist.toggle("highlight"); } 

and here's can see code in action, http://codepen.io/vbcda/pen/godzmr

it can happen if first remove exiting class 'highlight' element using mousedown event clicking anywhere in body.

<body onmousedown="outerclick(this)"> // add in html file  function detectclick(element) {     element.classlist.toggle("highlight"); } function outerclick(el){   var elements = document.queryselectorall(".highlight");   (var = 0; < elements.length; i++) {       elements[i].classlist.remove('highlight');    } } 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -