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

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

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');
}
}

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.

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>

if you want to use jquery:
$('.normal').click(function(e){
e.stopPropagation();
$(this).toggleClass('highlight');
});
$(document).click(function(){
$('.normal').removeClass('highlight');
});

Related

How to Add Class to Child Element of Parent using Javascript

I'm attempting to add a class to a p tag using the parent tag. Unfortunately, it does not appear to be adding the class .answer to the p tag. This is the code I have so far:
HTML
<div class="x-acc-content">
<p>This is sample text.</p>
</div>
Javascript
function($) {
$(this).children('div.x-acc-content').getElementsByTagName('p') [0].addClass('answer');
};
You can use .children('p') to get all children inside your div and then use .addClass() to add class to p tags .
Demo Code :
$(".x-acc-content").children("p").addClass("answer")
//or
//$(".x-acc-content").find("p").addClass("answer")
//or only first p tag
//$(".x-acc-content").find("p:first").addClass("answer")
.answer {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="x-acc-content">
<p>This is sample text.</p>
<p>This is sample text.</p>
</div>
Try
$(".x-acc-content").find("p").addClass("answer");
or
$(".x-acc-content"). children("p").addClass("answer");
or
$(".x-acc-content p").addClass("answer");

How to detect that the HTML element has text by clicking on text content area?

I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.
Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/
<div>
some text
<span class="box"></span>
</div>
<div>
some text
</div>
<div><span class="box"></span></div>
JS:
$(document).on('click','div', function(){
if (!$(this).text().trim().length > 0) {
$(this).text("foo");
} else {
$(this).append('<span>You clicked on a text</span>');
}
});
When you bind an event handler to a node, or use event delegation, this refers to the node the event was bonded to (or delegated to in the case of on).
Click the .box inside the 1st div element, gets the div as this. Since the div element contains text, you the wrong result.
Instead you should get the event target. The target is the actual element clicked.
$(document).on('click', 'div', function(e) {
var $target = $(e.target); // the event target
if (!$target.text().trim().length > 0) {
$target.text("foo");
} else {
$target.append('<span>You clicked on a text</span>');
}
});
.box {
background-color: green;
height: 50px;
width: 50px;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
some text
<span class="box"></span>
</div>
<div>
some text
</div>
<div><span class="box"></span></div>
As long as you have id's and classes you can try comparing ids or classes
$(document).on('click','div', function(e){
if (e.target.id.toString() == "box" || $(e.target).hasClass("box")) {
$(this).append('<span>foo</span>');
} else {
$(this).append('<span>You clicked on a text</span>');
}
https://jsfiddle.net/q6vbohxm/
This is the way you should do. As this selects the body element and any element inside body that has text, will go into the if statement, if you need elese statement as well, you add so after the if.
$(document).on('click','body', function(e){
var clickedTag, text;
clickedtag = e.target;
text = $(clickedtag).text().trim();
if(text.length > 0){
console.log(text);
}
});
wrap your text in separate element and fire click event on that element and also use .stopPropagation() method...
$("#demo").click(function(event){
event.stopPropagation();
alert("your text element was clicked");
});
This is happening because of event bubbling, so we need to stop that. Jquery having method to stop it event.stopPropagation();. Here I used div * selector to prevent firing event for all the child element inside div. Instead of div you can use any class to differentiate from other div
$(document).on('click','div', function(){
$(this).append('<span>You clicked on a text</span>');
}).on("click","div *", function(e){e.stopPropagation();});
.box {
background-color:green;
height:50px;
width:50px;
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
some text
<span class="box"></span>
</div>

How to remove the content from a "div" element using a button "onclick" function?

I have a div element that contains a number of images. When the user clicks a button, I want the contents of the div to be removed (not the div itself, I want to reuse the div to potentially add new content).
In my HTML, the div and button are defined as:
<body>
...
<div class="MyDiv"></div>
...
<button id="removeDiv" onclick="removeDivFunction()">remove Div Function</button>
...
</body>
How do I write a function that removes all elements from this div?
You have to call removeChild:
function removeDivFunction() {
MyDiv.parentNode.removeChild(MyDiv);
}
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>Remove div element</button>
$(document).ready(function(){
$("button").click(function(){
$("#div1").remove();
});
});
David has already pointed you to an existing question/solution.
For reference consider reading: http://www.w3schools.com/js/js_htmldom_nodes.asp
Its always a good idea to assign id to the div.
Also if you are using jQuery you can delete element by $("#divid").remove() for reference see: https://api.jquery.com/remove/
I hope this helps.
function removeDivFunction() {
$(".MyDiv").remove();
}
<div class="MyDiv">I need to remove</div>
<button id="removeDiv" onclick="removeDivFunction()">remove Div Function</button>
function removeDivFunction() {
var element = document.getElementsByClassName("MyDiv")[0];
element.parentNode.removeChild(element);
}
DEMO
You can try
Html
<div id="some">Example</div>
<button onclick="myFunction()">Click me</button>
javascript
function myFunction() {
var child = document.getElementById("some");
child.parentNode.removeChild(child);
}
And if you want to erase content of DIV then use
child.innerHTML = "";

Javascript onmouseover and onmouseout

You can see in the headline what it is. I've four "div", and therein are each a p tag. When I go with the mouse on the first div, changes the "opacity" of the p tag of the first div. The problem is when I go on with the mouse on the second or third "div" only changes the tag "p" from the first "div". It should changes the their own "p" tags.
And it is important, that i cannot use CSS ":hover".
The problem is clear, it is that all have the same "id".
I need a javascript which does not individually enumerated all the different classes.
I' sorry for my english.
I hope you understand me.
My script:
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
Javascript:
function normal() {
var something = document.getElementById('something');
something.style.opacity = "0.5";
}
function hover() {
var something = document.getElementById('something');
something.style.opacity = "1";
CSS:
p {
opacity: 0.5;
color: red;
}
As Paul S. suggests, you need to pass this to the function so that it knows which element it has to work on.
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
And then select the child element <p> for the passed <div>. Here I select the first child p, i.e. the first element in the array of children of this element with tag p, that's why you see [0]. So if in each div you had two paragraph, then you could use e.g. getElementsByTagName("p")[1] to select the second <p>.
function normal(mydiv) {
mydiv.getElementsByTagName("p")[0].style.opacity="0.5";
}
function hover(mydiv) {
mydiv.getElementsByTagName("p")[0].style.opacity="1";
}
See the working example here: http://jsfiddle.net/mastazi/2REe5/
Your html should be something like this:
<div onmouseout="normal(1);" onmouseover="hover(1);">
<p id="something-1">LOLOL</p>
</div>
<div onmouseout="normal(2);" onmouseover="hover(2);">
<p id="something-2">LOLOL</p>
</div>
<div onmouseout="normal(3);" onmouseover="hover(3);">
<p id="something-3">LOLOL</p>
</div>
<div onmouseout="normal(4);" onmouseover="hover(4);">
<p id="something-4">LOLOL</p>
</div>
As you can see, we have different ids for your elements, and we pass the ids through the function that we trigger with onlouseover and onmouseout.
For your javascript, your code could be something like this:
function normal(id) {
var something = document.getElementById('something-'+id);
something.style.opacity = "0.5";
}
function hover(id) {
var something = document.getElementById('something-'+id);
something.style.opacity = "1";
}
For normal() and hover() we receive an id and change the style for the current element that have this id.
Please, check this JSFiddle that I've built for you.

How to implement a blinds toggle effect with jQuery

I'm trying to write a "blinds" function that would close a DIV in a display:none mode. The unseen DIV is inside a wider DIV, containing the blind trigger.
This:
$(document).ready(function () {
$("#toggle_blind").click(function () {
$(this).toggle("fast");
});
});
Well, this blinds the button. How can I add a DIV to $this? Something like:
<div id="blind" class="wider_div">
<h3 id="closeButton">Close</h3>
<div style="display:none;" id="closeThis">
<p>some text</p>
</div>
</div>
How do I make the Close Button on H3 to close/open the CloseButton DIV on each click?
The div is the next sibling of the h3 so you can use .next()
E.g
$('#closeButton').click( function(){
$(this).next().toggle();
});
Reference the div directly, you may put something else in between it and the h3.
$(document).ready(function()
{
$("#closeButton").click(function()
{
$("#closeThis").toggle("fast");
});
});

Categories

Resources