multiple div's display content with click, prevent event bubbling - javascript

I have 3 div's: div1, div2, div3. When the user clicks on each div, I want to console log the content of that particular div only. I read about event bubbling and understood that the click event of the child will also be registered at the parent level. I tried the below code but couldn't get it to work correctly.
$(document).ready(function() {
$('#parent').on('click', 'div', function() {
console.log($(this).text());
})
})
#div1 {
width: 300px;
height: 200px;
padding: 25px;
background-color: red;
text-align: center;
}
#div2 {
width: 250px;
height: 150px;
background-color: blue;
padding: 25px;
text-align: center;
}
#div3 {
width: 200px;
height: 100px;
background-color: green;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="parent">
<div id="div1">div1
<div id="div2">div2
<div id="div3">div3</div>
</div>
</div>
</div>
</body>
How can I make it to print div1 when I click div1, div2 when I click div2 and div3 when I click div3?
is jQuery text() the right method to print the content? I can see it is printing spaces and all

The issue is not just related to event bubbling, but also the fact that the text() of an element contains the text of itself and all its child elements.
To do what you require you would need to filter() the contents() of the current element to retrieve only the text nodes - assuming you want to discard the text which is wrapped in any child element.
Try this:
$('#parent').on('click', 'div', function(e) {
e.stopPropagation();
var nodes = $(this).contents().filter(function() {
return this.nodeType == 3 && this.nodeValue.trim() != '';
});
console.log(nodes[0].nodeValue.trim());
});
Working example

Try this, according to this solution
$('#parent').on('click', 'div', function(e){
e.stopPropagation();
console.log($(this)
.clone()
.children()
.remove()
.end()
.text()
.trim()
);
})

Related

Keep the event, but avoid on links(or inner content)

This is probably asked a thousand of times, but I can't find an answer...
Here is an example:
var div = $('.div');
div.on('click', function(e) {
e.stopPropagation();
e.preventDefault();
div.toggleClass('red');
});
.div {
width: 50vh;
height: 50vh;
background: #eee;
}
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
link
</div>
The problem: event triggered when link(any content) is clicked.
I want remain the event, but avoid when content is clicked/selected/whatever. What are my options here?
Thanks
You just need to set up a "click" event handler for any child element of the div.div that prevents that event from bubbling up to any ancestor elements. This can be done with the * (universal) CSS selector.
Unless, you have reason to that you haven't described here, you don't need:
e.stopPropagation();
e.preventDefault();
in the div event handler.
var div = $('.div');
div.on('click', function(e) {
div.toggleClass('red');
});
// When any child element of the div with class .div is clicked...
$("div.div > *").on("click", function(evt){
// Don't allow the event to bubble up to the ancestor elements
evt.stopPropagation();
console.log("You clicked some child element of the div, but the event won't bubble up to it.");
});
.div {
width: 50vh;
height: 50vh;
background: #eee;
}
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
link
<span>Clicking me will do nothing</span>
</div>

How to remove Jquery event if another element has certain class?

I am trying to build a simple dropdown plugin for small project of mine. I do not want to use ready plugins, I want to learn by making one on my own.
html:
<div>
<span class="dropdown_triger">press</span>
<div class="content dropdown-closed">
</div>
</div>
css:
span{
display:inline-block;
background: green;
padding: 5px;
}
.content{
position: absolute;
top: 40px;
border: solid 1px black;
width: 200px;
height: 100px;
}
.dropdown-closed { display: none; }
.dropdown-open { display: block; }
and JS:
$(document).ready(function(){
$('body').on('click', '.dropdown_triger', function(e){
var $wrapper = $(this).parent();
var $content = $(this).next();
var $triger = $(this);
if($triger.hasClass('selected')){
$(document).off('mouseup.dropdownDocClick');
console.log('hasClass');
}
$triger.toggleClass('selected');
$content.toggleClass('dropdown-closed dropdown-open');
$(document).on('mouseup.dropdownDocClick',function (e){
console.log('fire');
if (!$wrapper.is(e.target) && $wrapper.has(e.target).length === 0){
if($content.hasClass('dropdown-open')){
$content.toggleClass('dropdown-closed dropdown-open');
$(document).off('mouseup.dropdownDocClick');
}
}
});
});
});
Everything works except for this place:
if($triger.hasClass('selected')){
$(document).off('mouseup.dropdownDocClick');
console.log('hasClass');
}
I expect that mouseup event would not fire anymore but it does. Here is a fiddle, just try it. If I open dropdown, mouseup event is attached to document and keeps firing until I have clicked outside container thus closed dropdown.
But if I close dropdown by clicking again on triger button(span in my example) event is not removed and I can not understand why?

Targetting specific jquery element which have identical class names

I have several divs which are generating dynamically which share same class names, If I hover on parent(myDiv) need to trigger an event and on hover need to add a class to myDiv(child button) and once I clicked on parent div(myDiv) need to unbind hover action?
<div class="myDiv">
<div class="myBtn"></div>
</div>
<div class="myDiv">
<div class="myBtn"></div>
</div>
<div class="myDiv">
<div class="myBtn"></div>
</div>
Tried in the below way
$(document).on('click', '.myDiv', function() {
//some task will goes here
$(this).unbind('hover');
}).hover(function() {
$(this).find('.myBtn').css('background','#666666');
});
I believe what you are looking for is the .off() function.
Here is the jsFiddle link.
JavaScript:
$(document).on('click', '.myDiv', function() {
//some task will goes here
$(this).off();
});
$('.myDiv').hover(function() {
$(this).find('.myBtn').toggleClass('active');
});
CSS:
.myDiv {
display: block;
height: 100px;
width: 100px;
background-color: red;
}
.myBtn {
display: block;
height: 50px;
width: 100px;
background-color: white;
}
.active {
background-color: gray;
}
I hope this helps.

How to display the postition absolute div as the position relative div?

I have a parent div "total" in which, there are two children divs namely, "some" and "box". When I click on the link in the div "some" (child-1), the "box"(child-2) must be displayed with width: 100%; and if I click on other parent link, the current "box" (child-2) must be hidden. Also, the paragraph tag must not be hidden when the click button is clicked(as in position: relative).
Here is the fiddle to work this out.
The following lines are the code I tried.
$('.box').hide();
$(".click-btn").on('click', function() {
$('.box').hide();
$(this).parent().parent().children(".box").toggle(1000);
});
check this if it solve your problem jsfiddle
i added this
$('.box').hide();
$(".click-btn").on('click', function() {
$('.box').hide();
$(this).parent().parent().children(".box").toggle(1000);
});
add the css
.box {
width: 100%;
float: left;
position: absolute;
height: 200px;
background: orange;
top: 70px;
left: 0px;
clear: both;
}
My solution would be putting each .box outside of the floating .single and reference them with an data attribute.
<div class="total">
<div class="single">
<div class="some"><a class="click-btn" href="#" data-box="box1">click</a></div>
</div>
<div class="clearfix"></div>
<div class="box" data-id="box1">Box 1</div>
</div>
And the box css
.box {
width: 100%;
height: 200px;
background: orange;
display:none;
}
If you set the display none in css you don't have to use $('.box').hide(); on dom ready.
Since you hide all .box elements on click, the toggle function won't work. To toggle the box if you click the active link again you can use the .not() function of jQuery which will take out an element of the collection.
Alltogether the JS would look like:
$(".click-btn").on('click', function(e) {
e.preventDefault();
var boxId = $(this).data('box');
var activeBox = $('[data-id="'+boxId+'"]');
$('.box').not(activeBox).hide();
activeBox.toggle(1000);
});
I'm using e.preventDefault(); what will prevent the default browser action for clicking a link.
Here is a fiddle: http://jsfiddle.net/mrvtwpjp/40/

jquery does not detect click on child element

I have created a div element which is supposed to be a contact list. It should contain other divs in it.
What I'm trying to do, is attach a click handler on each list item (on each inner div).
But the click handler is never triggered.
$(".contact").on("click", function() {
alert("clicked");
});
.contacts {
position: absolute;
top: 10px;
left: 300px;
width: 100px;
height: 250px;
border-color: black;
border-style: solid;
z-index: 1;
overflow: scroll;
}
.contact {
position: relative;
width: 80%;
height: 20%;
border-style: solid;
border-color: red;
z-index: 100;
}
<div id="contactList" class="contacts">
<div id="1" class="contact">one</div>
<div id="2" class="contact">two</div>
<div id="3" class="contact">three</div>
</div>
If I attach a click handler for the parent DOM object, it gets triggered. Am I missing something here?
EDIT:
silly of me, i forgot to mention that children are added this way:
$(".contacts").append($("<div id='"+id+"' class=contact >"+d[contact].name+"</div>"));
where "d" and "id" variables come from a successful server call.
you have
$(".contact").on("click",function(){
instead of
$(".contacts").on("click",function(){
do you have this on trigger in the document is loaded event?
it won't work otherwise
$(function(){
$(".contact").on("click",function(){
alert("clicked");
});
});
Edit:
Since the OP forgot to mention something critical, here is my answer to that.
There are no ' around the classname. This should work:
$(".contacts").append($("<div id='"+id+"' class='contact' >"+d[contact].name+"</div>"));
Edit 2
You could also use the children() method:
$(function(){
$(".contacts").children("div").on("click",function(){
alert("clicked");
});
});
A slightly better way of putting this event on is in a document ready function that gets loaded with the page combined with using the .click jquery function. This is short hand for .on("click", FUNCTION).
Example:
$(document).ready(function(){
$(".contact").click(function(){
alert("clicked");
});
});

Categories