jquery does not detect click on child element - javascript

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

Related

Run a javascript only on the child of the element that triggered it

I want to run a javascript only upon the child from the element that triggered it. I have tried to make a research but couldn't find a way to get an answer. I know this might be simple but I am new to java.
Here is the fiddle of my problem FIDDLE.
What I want is that when I hover on the upper element, only its corresponding rating shows up, not both of them.
I have tried with find() without success
$('.product-image').hover(
function() {
$('.product-image').find('.ratings').css('opacity', '1');
},
function() {
$('.ratings').css('opacity', '0');
});
Thank you
Your problem is you do not select the element. You either need to change your code to use $(this) or $(evt.target) to get the element
How would I do it? With just CSS
.product-image + .ratings {
transition: opacity 0.5s ease;
opacity: 0;
}
.product-image:hover + .ratings {
opacity: 1;
}
.product-image {
height: 50px;
width: 50px;
background: red;
margin-bottom: 10px;
}
.ratings {
height: 50px;
width: 50px;
background: blue;
margin-bottom: 10px;
}
<div class="product">
<div class="product-image"></div>
<div class="ratings"></div>
</div>
<div class="product">
<div class="product-image"></div>
<div class="ratings"></div>
</div>
You can use event.target in your method body, which will give the element that triggered the hover event. Wrap it in $() to have jQuery context available.
$('.product-image').hover(function(event){
$(event.target).next('.ratings').css('opacity', '1');
}, function(event){
$(event.target).next('.ratings').css('opacity', '0');
});
Also updated your jsFiddle: http://jsfiddle.net/Z33kk/21/

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

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

Using addClass to show an interval

I'm attempting to show an interval within a bar. Initially I was using the jQuery plugin for range, but it did not work like I wanted.
I have several different bulleted pointed within my bar. Whenever someone clicks within or near the point (in the class sliderInterval) I want the class rangeSection to be added to that area, basically showing that certain interval active. However, the rangeSection doesn't even show up, nor I am certain I am doing this correctly.
In addition, since I am doing this with intervals. I want to be able to give those intervals values, so that when one is selected I can display that value.
This is what I am trying to get it to look like:
I added a snippet to show what I have done so far. Any advise?
$(function interval() {
$(".slideInterval").click(function() {
$(this).addClass(".rangeSection");
});
});
#sliderBar {
border-radius: 15px;
width: 90%;
height: auto;
margin: 25px 10%;
background: blue;
}
.rangeSection {
width: 100px;
height: 100%;
color: purple;
position: absolute;
z-index: 1;
}
.intervalCircle {
border-radius: 50%;
height: 15px;
width: 15px;
background: red;
z-index: 1;
position: absolute;
}
.sliderInterval {
display: inline-block;
padding: 10px 8%;
}
.sliderInterval:first-child {
padding-left: 0;
}
.intervalCircle:first-child {
padding-left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sliderBar">
<div class="rangeSection"></div>
<div class="sliderInterval" onclick="interval()"><span class="intervalCircle" ></span></div>
<div class="sliderInterval" onclick="interval()"><span class="intervalCircle" ></span></div>
<div class="sliderInterval" onclick="interval()"><span class="intervalCircle"></span></div>
<div class="sliderInterval" onclick="interval()"><span class="intervalCircle"></span></div>
<div class="sliderInterval" onclick="interval()"><span class="intervalCircle"></span></div>
<div class="sliderInterval" onclick="interval()"><span class="intervalCircle"></span></div>
</div>
try this one.
You can use the .ready(); function of the jQuery library and set the .click() listener on all the .sliderInterval elements. I added the active class as well.
try it here:
https://jsfiddle.net/8cxLLts1/
$(document).ready(function(){
$(".sliderInterval").click(function() {
$(this).addClass("active");
});
});
EDIT: actually, if you use toggleClass() instead of addClass(), you'll be able to turn on and off a specific section
Using onclick in your html attribute and then binding a click event also in js could be considered redundant and unnecessary. Try removing the onclick attribute from your html and then adjust your js like so:
$(document).ready(function(){
})
.on('click', '.sliderInterval', function(){
$(this).addClass(".rangeSection");
});
Bind it to the document itself and this will help with your event delegation naturally. Also, take care to double check your class names - your js is missing the 'r' in '.sliderInterval'.

Adding click event handlers recursively

I have an element #standardBox
#standardBox.click --> replaces itself with #newBox
#newBox.click --> replaces itself with #standardBox
But this latest #standardBox has no click event listener. I want it to have an on click event listener and its subsequently created elements too. This is getting into a recursive loop, which I don't know how to address.
I'm using this for header with standard contents, which gets replaced by something intermediate/new contents, which again is to get back to standard contents ...
Thanks.
HTML
<div id="container">
<div id="standardBox"></div>
</div>
CSS
html, body {
margin: 0;
padding: 0;
height: 100%;
}
#container {
position: relative;
height: 5em;
width: 5em;
background: #C5CAE9;
}
#standardBox {
position: absolute;
top: 20%;
right: 20%;
bottom: 20%;
left: 20%;
background: #ffffff;
cursor: pointer;
}
#newBox {
height: 3em;
width: 3em;
background: #000000;
cursor: pointer;
}
JAVASCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('#standardBox').click(function(){
$('#container').html('<div id="newBox"></div>');
// register event handler for new element created
$('#newBox').click(function(){
$('#container').html('<div id="standardBox"></div>');
// but this #standardBox has no click event listener
});
});
http://codepen.io/anon/pen/YPLKLq
Attach the handler to the body instead like this:
$("body").on("click", "#standardBox", function(){
$('#container').html('<div id="newBox"></div>');
})
.on("click", "#newBox", function(){
$('#container').html('<div id="standardBox"></div>');
});
This causes the body to listen for events that come from #standardBox and #newBox. Note that the this variable is still set to either the #standardBox or the #newBox element.
use below code. dynamically created element dose not fire event using 'click' function. you need to Attach the handler to the document( body )
$(document).on('click','#standardBox',function(){
$('#container').html('<div id="newBox"></div>');
// register event handler for new element created
});
$(document).on('click','#newBox',function(){
$('#container').html('<div id="standardBox"></div>');
// but this #standardBox has no click event listener
});
Why you are writing such complex code to do it. As there can be a very simple code.
Lets say this your html.
<div id="container">
<div id="standardBox"></div>
</div>
Now, to change the inner container.
$(function(){
$('#container div').click(function(){
$(this).attr("id")=="standardBox"?$(this).attr("id","newBox"):$(this).attr("id","standardBox");
});
});

Is this possible to force execution of .click() for all elements, even those that are underneath?

Consider this code:
HTML:
<div class='a'>a</div>
<div class='b'>b</div>
<div id='log'></div>
CSS:
.a, .b {
width: 100px;
height: 100px;
border: 1px solid black;
position: absolute;
text-align: right;
}
.a {
left: 100px;
top: 100px;
}
.b {
left: 150px;
top: 150px;
}
JS:
$('*').click(function(e) {
log(this.nodeName + ' ' + this.className);
});
function log(s) {
$('#log').append(s + '<br />');
}
If the intersection is clicked, .click() for .a is not called.
Is there any built-in method to force the execution of click() for all elements, and not only the top one and its parents, or I must implement this myself ?
I think that the behavior you are observing is correct. When clicking the topmost element the one beneath won't get a click event despite it looks it is in the "clicked" area. As a workaround you can manually trigger it's click event:
$('.a').click().
Calling click without arguments is equivalent to trigger('click') which raises the specified event. You can find more info in the trigger help topic.

Categories