This question already has answers here:
jquery stop child triggering parent event
(7 answers)
Closed 8 years ago.
I am not sure this is really bubbling, I will explain.
I have this:
<div>
<div>
text here
</div>
</div>
How to bind an on click event so that it will affect only the enclosed div? If I set it like this:
jQuery('div').bind('click', function() {
jQuery(this).css('background','blue');
});
it makes blue all the divs. If I add false as the third argument(prevent bubbling) to the bind function it does nothing.
How can I solved this?
http://api.jquery.com/event.stopPropagation/
Add event.stopPropagation(); inside the hander.
(It might be better, though, to assign an ID or class to the nested DIV so you can be sure it's the only one affected.)
You should really use identifiers like IDs or classes, but for your example, you could do this:
jQuery('div > div').bind('click', function() {
jQuery(this).css('background','blue');
});
...which will bind the handler to any div that is a direct descendant of another div.
So either make your initial selection specific to the element(s) you want to affect, or use event delegation, placing a handler on an ancestor, and testing for the element you want.
Delegation example: http://jsbin.com/ehemac/edit#javascript,live
<div id="container">
<div class="outer">
<div>
text here
</div>
</div>
<div class="outer">
<div>
text here
</div>
</div>
</div>
jQuery('#container').delegate( '.outer > div', 'click', function() {
jQuery(this).css('background','blue');
});
This uses the delegate()[docs] method that places a handler on the ancestor with the ID #container.
The first argument to .delegate() is a selector. Any elements that are clicked inside #container will have that selector compared against the element clicked. If the selector matches, the handler will be invoked.
http://jsfiddle.net/vol7ron/WzSkj/
Targeting the last descendant
Credit to Patrick DW:
jQuery('div:not(:has(div))').bind('click', function() {
jQuery(this).css('background','blue');
});
This should be all you need as it will look at all div and find those that don't have child divs (thus, they will be the last descendant of that element type. You could further filter this to make sure they have a parent that is a div, if you wanted to exclude those divs that are standalone.
Older Answer:
This is not by any means meant to be a complete/robust plugin. It serves as only an example of how to target the last element in a chain. See the revision history for a way to do it w/o the plugin. This should be modified if you wish to use it for production.
Plugin:
(function($){
$.fn.lastDescendant = function(el){
var found = jQuery(el + ':first').siblings(el).andSelf();
var prev, curr;
var stack = this;
for (var i=0,n=found.length; i<n; i++){
curr = found.eq(i).find(el);
while (curr.length){
prev = curr;
curr = curr.find(el);
}
stack = stack.add(prev);
}
return stack;
};
})( jQuery );
Example Call:
jQuery.fn.lastDescendant('div')
.click(function(){
jQuery(this).css("background","#09c");
});
Note:
this will not select the first (ancestor) element. If you want to select that as well, you could wrap the whole thing in a new div, and then do the above.
if I were to make this a production plugin, I would include checking the parameter, and allow you to be able to pass in an object and a starting point (so that siblings are not selected)
To fix this just use a more specific selector
jQuery('div > div').bind('click', function() {
jQuery(this).css('background','blue');
})
The best way to solve it would be to give your inner div an identifiable feature such as a class, e.g., <div class="inner"></div>.
Alternatively, change your selector:
$('div > div').click(function() {
$(this).css('background', 'blue');
}
try giving the inner div an id tag and refer to it...
<div><div id=foo>text goes here</div></div>
...
$('#foo').bind('click', function() {
$(this).css('background','blue');
});
HTH
-- Joe
Related
Think of the following HTML code to apply Jquery:
HTML code:
<div id="outer_div">
<div id="inner_div_1"></div>
<div id="inner_div_2"></div>
<div id="inner_div_3"></div>
</div>
By default, the "outer_div" is hidden. It appears while clicked on a button using Jquery show() function.
I wanted to do the following: On click within anywhere of "outer_div" excluding the area within "inner_div_1" , the "outer_div" would again be hidden. I failed while tried the following codes. What should I amend?
Attempted Jquery 1:
$("#outer_div:not(#inner_div_1)").on("click",function(){
$("#outer_div").hide("slow");
});
Attempted Jquery 2:
$("#outer_div").not("#inner_div_1").on("click",function(){
$("#outer_div").hide("slow");
});
Your support would be highly appreciated.
You need to consider that a click in the inner div is also a click on the outter div. That being said, you just need to check the target and target parents :
$("#outer_div").on("click",function(e){
if(!$(e.target).closest('#inner_div_1').length) $("#outer_div").hide("slow");
});
You can use some of the data in the event
$("#outer_div").on("click",function(e){
if( // Fast check to see if this is the div
e.target.id !=='inner_div_1'
// We limit the 'closest()' code to the outer div. This adds children to the exclude
&& $(this).closest('#inner_div_1, #outer_div')[0].id=='outer_div'){
alert('good click');
}
});
This is a solution for your code now, this works perfect when not too many excluding objects. But no wildcard selectors, which is nice.
And a jsFiddle demo.
Other properties can be used to, like a class:
$("#outer_div").on("click",function(e){
if( e.target.className!=='even'
&& $(this).closest('.even, #outer_div')[0].id=='outer_div'){
alert('yay, clicked an odd');
}
});
I made 7 lines, gave the even ones a class 'even'.
How do i even put these, let me try. In the following sets of codes, i want to click 'parentclass' and have an alert value of 'child1' and when i click the class below it which is 'Parent 2' have an alert fire with a value of 'child2'
So this must alert the content of that class only and not the entire class.
Here's some Javascript in Jquery.
var childclass = $('.childclass').html();
$('.parentclass').click(function(e) {
alert (childclass)
});
$('.childclass').click(function(e) {
e.stopPropagation()
e.preventDefault()
});
And HTML
<a href="" onClick="return false">
<div class='parentclass'>
Parent 1
<div style="display:none" class="childclass">child1</div>
</div>
</a>
<a href="" onClick="return false">
<div class='parentclass'>
Parent 2
<div style="display:none" class="childclass">child2</div>
</div>
</a>
This line var childclass = $('.childclass').html(); doesnt make sense as it doesn't know which element in particular you mean. The result of that will just be child1child2 which is just a concatenation of the .html() of all the elements with class childclass. This is obviously not what you want.
Therefore you should dynamically find the child with a class of childclass upon receiving the click event.
$('.parentclass').click(function(e) {
alert($(this).find('.childclass').html())
});
Also, you should know that your child class event handler is useless as we don't care if the event gets propogated downwards. If you DID care, then your e.stopPropagation() and e.preventDefault() should be in the event handler of the parent class.
You need to fetch the html of the clicked parent element within the click handler
$('.parentclass').click(function (e) {
alert($(this).find('.childclass').html())
});
$('.childclass').click(function (e) {
e.stopPropagation()
e.preventDefault()
});
Demo: Fiddle
Several ways you can go about this.
First, if your HTML will not be dynamic (elements already exist when page loads), then you can select elements by the parent class name and assign click event as so:
$('.parentclass').click(function(e) {
// the first variable here is selecting the inner elements having class 'childclass'
// keep in mind, if more than one child having that class is present within this parent, it will select all of them
var child = $(this).find('.childclass');
// here we alert the text of the inner child found
// if it is more than one, you will have undesired results. you may want to specify `.first()`
alert(child.text())
})
For newer jQuery you can also use $('.parentclass').on('click', function(e) {.
If you expect any pieces of parentclass to be dynamic, then you'll want to delegate the event based on either a static parent to the parents or document. This can be like so:
$(document).on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Or, if you have a static (already there when page loads) wrapping element, give it an ID like `parentClassWrapper' and assign the click event dynamically as:
$('#parentClassWrapper').on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Some helpful links:
jQuery API
jQuery Selectors
.click()
.on()
Some info on Event Delegation
jquery on vs click methods
jQuery .on('click') vs. .click() and .delegate('click')
jquery .live('click') vs .click()
I made several adjustments to your html that are worth noting. There's no need for the <a> tag. Don't use inline js - onlick in your html. Note that I wrapped the text inside of the div in the <a> tag instead. This markup is more semantic. Also, move your styles to css rather than in the html.
<div class="parent">
<a>Parent 1</a>
<a class="child">child of parent 1 contents</a>
</div>
<div class="parent">
<a>Parent 2</a>
<a class="child">child of parent 2 contents</a>
</div>
css:
.parent > .child { /* good practice: only select an immediate child of the parent */
display: none;
}
The other answers here are using find() to select the child, but I recommend children() instead. For example, if you had additional nested .childs, find() will select them all, but children() will only select direct .childs of the parent, so it is better in this case. I also recommend using the console for debugging rather than alert.
Live demo here (click).
$('.parent').click(function() {
var $child = $(this).children('.child');
var cls = $child.attr('class');
console.log(cls);
$child.show(); //added so that you can click the child
});
$('.child').click(function() {
var html = $(this).html();
console.log(html);
//if you just want the text, use this instead:
var text = $(this).text();
console.log(text);
});
I have multiple containers that I need to animate.
Basically: you click on class: box-n (e.g. box-1) and you slideToggle: box-child-n (e.g. box-child-1).
Instead of a click function for every box-n to toggle box-child-n, I want a simple line of code that matches box-n with its children class.
html:
<div class="box-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
<div class="box-2">Some clickable container</div>
<div class="box-child-2">This should toggle when box-2 is clicked</div>
Et cetera...
current jquery:
$('.box-1').click(function() { $('.box-child-1').slideToggle() });
$('.box-2').click(function() { $('.box-child-2').slideToggle() });
Sort of desired jquery (allInt function is made up.):
var $n = allInt();
$('.box-' + n).click(function() {
$('.box-child-' + _n).slidetoggle() // local variable to inter alia .box-1
})
I can't seem to think of any solution, so I am asking for help once again.
I appreciate every suggestion you folks give me!
Here's one way to do it that allows for the elements to have other classes besides the ones that you're using to pair them up:
$('div[class*="box-"]').click(function() {
var c = this.className.match(/\bbox-\d+\b/);
if (c)
$('div.' + c[0].replace(/-/, '-child-')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/
That is, use the [name*=value] attribute contains selector to find any divs with a class attribute that has "box-" in it somewhere. Then when clicked extract the actual class and check that it matches the "box-n" pattern - this allows for multiple (unrelated) classes on the element. If it does match, find the associated "box-child-n" element and toggle it.
Having said all that, I'd suggest structuring the markup more like this:
<div data-child="box-child-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
...because then the JS is simple and direct:
$('div[data-child]').click(function() {
$('div.' + $(this).attr('data-child')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/1/
To just answer your question, this will do the trick :
$("div[class^='box-']").click(function(){
$(this).parent().find('.' + $(this).attr('class').replace('-','-child-') ).slideToggle();
});
jsfiddle here.
Anyway i dont think you use a good approach (you may wrap child into parent div or use ids).
I have an element which listens to the onclick event. It calls a function once it was clicked. After that element is a < dd > which I want to select in a CSS selector. The element which is clicked, is a < select >. How would I do that?
This is the HTML:
<select onclick="myFunction();">...</select>
<dd>...</dd>
function myFunction() {
// What do I have to write for the ??????
$$('?????? dd').toggle();
}
Note: There are many of those select/dd combination, so I really have to get the next dd after the firing element.
The minimal change is: Pass this into your function:
<select onclick="myFunction(this);">...</select>
...and then:
function myFunction(select) {
$(select).next().toggle();
}
$ enhances the element, then you can use next to move to the next element. If you like, you can use .next('dd'), but in your case the dd is the next element.
That still uses onxyz attributes, which is a bit old-hat. You might consider hooking things up via observe instead.
I am guessing you mean this:
this.next("dd");
(specifying dd so when there's an error in the mark up, no other element is selected)
If you are trying CSS selectors only, try the following:
$("select + dd").toggle();
Note: this will toggle all dds that follow a select.
Note 2: apparently this does not work in Prototype but it does work in jQuery.
See T.J.Crowder's comment:
[This doesn't work in Prototype] because $ in Prototype looks up elements by ID. $$ is more like
jQuery's $, but what it returns doesn't do set-based operations like
jQuery does (or rather, not the same set-based operations as the ops
you can do on individual elements; you have to use invoke).
next() works on both jQuery as Prototype.
Use:
$(this).next("dd").toggle(); --> this is Jquery
$(element).next("dd").toggle();
see the link Element.next
<select>...</select>
<dd>...</dd>
$('select').change(function(){
$(this).next("dd").toggle();
});
Better use unobtrusive javascript, so your js is better coupled from html markup.
HTML:
<select><option value="test">Test</option></select>
<dd>Test</dd>
JS:
//Event.observe(window, "load", function() {
document.observe('dom:loaded', function() {
$$('select')[0].observe('click', function(event) {
var next = event.element().next();
next.toggle();
});
});
JSFiddle
I'm using a javascript function to set the value of a text field, based on the option chosen from a select field.
The javascript contains a lot of other stuff, but only the following is relevant to this question.
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next('.target')[0];
----other stuff----
});
});
I originally had my form set up as follows, and everything worked fine.
<select class="source"></select>
<input class="target"></input>
I've subsequently added some styling, which has required extra divs.
<select class="source"></select>
<div class="level1">
<div class="level2">
<input class="target"></input>
</div>
</div>
Now the javascript function does not work, because the next method only targets siblings and not descendants.
So my question is, what method should I be using to target a specific descendant?
An important fact: this markup is part of a nested form, and is repeated several times on the same page. It is important that the function targets the correct .target field, i.e. immediately subsequent and descendant.
I've tried obvious candidates – .find(), .children() — but these don't seem to work. Would appreciate any ideas or pointers.
Thanks!
Now that in the new markup structure .target input is wrapped in a div with class level1 you can find that div first using next() and then use find() method to get to the .target input.
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next('.level1').find('.target')[0];
----other stuff----
});
});
Note: Even if you don't pass any selector to next() also it will work fine because it only selects the immediate next sibling optionally filtered by the selector which we pass.
In your case this would work:
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next().find('.target')[0];
----other stuff----
});
})
;
It's a descendant of the sibling, so this should do the trick:
var target = $(this).next('.level1').find('.target')[0];