Setting border property on clicked element and not the parent - javascript

I'm trying to enable clicking on specific element on the page, and after click to set border on that element. You can find working example here link
And some code:
<div>
Test
</div>
$(document).ready(function() {
$('a, div').on('click', function() {
$(this).css({'border-color': 'red'});
})
});
The problem is, if anchor element is clicked, div as a parent element also gets click event, and the border is set there. Is there a way to restrict click event only to most specific element(in this case anchor) ?

Your current selector targets all a and div elements. The selector below target all a elements in a div element. More accurately, you can use div > a.
$(document).ready(function() {
$('div > a').on('click', function(e) {
e.preventDefault();
$(this).css({'border-color': 'red'});
})
});
The construct you're trying to use is: jQuery( selector [, context] ) .. see http://api.jquery.com/jquery/:
jQuery( selector [, context ] )Returns: jQuery
Description: Accepts a string containing a CSS selector which is then used to match a set of elements.
jQuery( selector [, context ] )
selector
Type: Selector
A string containing a selector expression
context
Type: Element or jQuery
A DOM Element, Document, or jQuery to use as context

You can simply focus on the element that was clicked, using event.target:
$('a, div').on('click', function (e) {
e.target.style.borderColor = 'red';
});
$('a, div').on('click', function (e) {
e.target.style.borderColor = 'red';
});
div, a {
border: 2px solid transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>link text</div>
<div>link text</div>
<div>link text</div>
Or, to use a slightly more-jQuery approach:
$('a, div').on('click', function (e) {
$(e.target).css({'border-color' : 'red'});
});
$('a, div').on('click', function (e) {
$(e.target).css({'border-color' : 'red'});
});
div, a {
border: 2px solid transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>link text</div>
<div>link text</div>
<div>link text</div>
References:
Event.target.
on().

You could stop the event propagation, but it's discouraged as there could be some library which does something if the user clicks away/anywhere. A better solution is this one:
$(document).ready(function() {
$('a, div').on('click', function(e) {
if (!e.isDefaultPrevented()) { //Don't do anything if we already processed that event.
e.preventDefault();
$(this).css({'border-color': 'red'});
}
})
});

Use
$(document).ready(function() {
$('a, div').on('click', function() {
if ($(this).prop('tagName').toLowerCase() == 'a') {
$(this).css({'border-color': 'red'});
}
})
});
This will check if the anchor element is clicked.

$(document).ready(function() {
$('div a').on('click', function() {
$(this).css({'border-color': 'red'});
})
});

You can use event.stopPropagation() to prevent the event from bubbling up the DOM tree.
Reference: http://api.jquery.com/event.stopPropagation/

the issue was click event was being propagated to div from anchor tag , anchor being the child element of div, so just we need to stop the propagation.
Check below code:
$(document).ready(function() {
$('a, div').on('click', function(event) {
$(event.currentTarget).css({'border-color': 'red'});
event.stopPropagation();
})
});
div {
padding: 50px;
border: 1px solid #cccccc;
}
a {
border: 1px solid #cccccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
Test
</div>

Related

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 hide parent when click anywhere outside the child element

I have this code
<style>
.Parent {width:500px;height:500px;background:#000}
.Parent .Child {width:250px;height:250px;background:#F00}
</style>
<div class="Parent">
<div class="child"></div>
</div>
<script>
$(document).ready(function() {
$('.Parent').click(function () {
$(this).hide()
});
/*
But if i click on <div class="Child"></div> ,
<div class="Parent"></div> won't get hidden .
*/
});
</script>
I want my code to hide'.parent',
When I click on areas in .Parent witch doesn't include .Child elementand if the areas I click was included in '.child' area , it don't do anything .
so what would u guys suggest ?
Simply make of event.stopPropagation(); to stop event of child from propagating to parent.
So script becomes:
$('.Parent').click(function () {
$(this).hide();
});
$('.child').click(function (e) {
e.stopPropagation();
});
See the fiddle: "http://jsfiddle.net/sftknxeo/1/"
just do this:
$('.Parent, .child').click(function(e) {
if ($(this).hasClass('child')) {
return false;
}
$(this).hide();
});
$('.Parent, .child').click(function(e) {
if ($(this).hasClass('child')) {
return false;
}
$(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='Parent' style='width:auto; padding:50px; border:red solid 1px;'>
<div class='child' style='width:200px; height:200px;border:green solid 1px;'>
child
</div>
</div>
You can use the event's target to determine what you have clicked on. This way you can also assign an event to happen if you have clicked on the child. (If need be.)
$('.Parent').click(function(e){
if(e.target == this){
$(this).hide()
}
});
DEMO
Quick and dirty version would be simply to add another event handler. Add a click handler to child that hides parent. Then if you click on parent, it hides itself, and if you click on child, it hides parent.
$('.child').click(function (e) {
$('.parent').hide();
});
Not the most elegant solution, sure, but it's quick and easy and should get the job done.
$('.Parent').click(function () {
$(this).css("visibility", "hidden");
$(".Parent" ).children().css("visibility", "visible");
});
If you just want to hide parent then it will do the needful.
Check for the clicked element by looking at the target property of the event object. Here is something you might want to do:
$(function () {
$('.Parent').click(function (e) {
if ($(e.target).hasClass("child")) {
return false;
}
$(this).hide();
});
});
$('.parent').click(function(e) {
if ($(this).hasClass('child')) {
return false;
}
$(this).hide();
});

Why can't I add class to this html element?

I'm trying to add this the active class to the element when the user clicks it. Why does it not work? Is there something wrong with the syntax?
HTML code:
<div class="accordion">
<h3>a</h3>
<p class="active">b</p>
<h3>a</h3>
<p>b</p>
<h3>b</h3>
<p>b</p>
<h3>b</h3>
<p>b</p>
</div>
jQuery code:
jQuery(function($) {
$('div.accordion').click(function(e) {
e.preventDefault();
$(this).addClass("active");
});
});
What i wanna do is when the user clicks h3, thats when it sets the p tag below it the active class
You need to bind click event to H3 elements. Also make sure you remove previously active elements:
var $h3 = $('.accordion > h3').click(function(e) {
e.preventDefault();
$h3.next('p').removeClass('active');
$(this).next('p').addClass('active');
});
Demo: http://jsfiddle.net/2DB37/
I'm trying to add the active class to the p tag.
You forgot to add a click event to the p tag:
jQuery(function($) {
$('div.accordion h3').click(function(e) {
e.preventDefault();
$(this).next('p').addClass("active");
});
});
WORKING DEMO
change jQuery to like this
jQuery(function($) {
$('div.accordion p').click(function(e) {
e.preventDefault();
$(this).addClass("active");
});
});
UPDATED DEMO
jQuery(function($) {
$('div.accordion h3').click(function(e) {
e.preventDefault();
$(this).next().addClass("active");
});
});

Hover class on other elements not on selected - javascript

HTML
<div>
<ul class="navBar">
<li class="selected">HOME</li>
<li>WORKS</li>
<li>ARTICLES</li>
<li>ABOUT</li>
</ul>
</div>
CSS
.selected{
background-color: #CCCCCC;
}
.onHover{
display: block;
background-color: #0088FF;
}
JAVASCRIPT
$(function() {
$("ul.navBar li a").hover(
function(){
$(this).addClass("onHover");
},
function(){
$(this).removeClass("onHover");
});
});
What I want here is the javascript to not add 'onHover' class to the HOME link when hovered over, just the other three links.
You can use not() selector to not allow the item to be picked.
$(function() {
$("ul.navBar li:not(.selected) a").hover(
function(){
$(this).addClass("onHover");
},
function(){
$(this).removeClass("onHover");
});
});
BUT you can do this with a pure CSS only solution if you really wanted. No JavaScript is needed.
Use the jQuery :not() selector to not include the "selected" class. Also better to use event delegation .on() rather directly binding the event to elements ie. .hover().
See http://api.jquery.com/not-selector/ for more information on using :not().
$(function () {
$(document).on('mouseenter', 'ul.navBar li:not(.selected) a', function () {
$(this).addClass('onHover');
});
$(document).on('mouseleave', 'ul.navBar li:not(.selected) a', function () {
$(this).removeClass('onHover');
});
});
See fiddle: http://jsfiddle.net/4rZ3D/

Onclick change div style + onclick outside div remove style change

I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.
I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?
<head>
<style type="text/css">
.account{
width: 100px;
height: 100px;
border: 1px solid #000;
}
.selected{
border: 2px solid #F00;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".account").click(function(){
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
});
</script>
</head>
<body>
<h1>the test</h1>
<div class="account">test 1</div>
<div class="account">test 2</div>
</body>
Thank you very much for any help you can give me!!!
The following should do it:
$(document).on('click', function(e) {
if($(e.target).hasClass('account')) {
// do style change
}
else {
// undo style change
}
});
It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation().
Try this.
$(document).ready(function(){
$(".account").click(function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
//This event handler will take care of removing the class if you click anywhere else
$(document).click(function(){
$(".selected").removeClass("selected");
});
});
Working demo - http://jsfiddle.net/yLhsC/
Note that you can use on or delegate to handle click event on account elements if there are many on the page.
Something like this.
Using on if using jQuery 1.7+
$('parentElementContainingAllAccounts').on('click', '.account', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
Using delegate
$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
You can achieve this behavior with attaching click listener on body element e.g.:
$("body").click(function(){
});
Try this:
$(document).ready(function() {
$('.account').click(function(e) {
e.stopPropagation();
$(this).addClass("selected");
});
$(document).click(function(){
$('.selected').removeClass('selected');
});
});

Categories

Resources