$.on() bubbling after stopPropagation(); - javascript

I'm trying to use .on() to tell me what i clicked on inside of a region. To capture the exact element I clicked on, I'm calling event.stopPropagation() to keep it from bubbling but my output is always #containerDiv and its contents.
How can I see exactly what was clicked on within #containerDiv? A code snippet is below:
$("#containerDiv").on("click",function(event){
event.stopPropagation();
console.log($(this));
});

Use event.target, not $(this); the latter will always be the element to which the handler was assigned.

When you capture the event on the container, the event has already bubbled.

Try giving the on() method a selector:
$("#containerDiv").on("click", "*", function(event){
event.stopPropagation();
console.log($(this));
});
Demo: http://jsfiddle.net/SnPjS/2/

Related

jQuery: How to find an element inside of hashchange event handler?

A web-page has some links:
example-1
example-2
example-n
Clicking any on them it runs an event of hashchange and we going to handle it:
$(window).on('hashchange', function(event){
// Is it possible (inside this handler) to find out which of a.link was clicked?
});
Or, is there another way to do it?
While I believe adding click listeners to the actual links would be best, you could also search for the element that would have changed the hash as such:
$(window).on('hashchange', function(event){
$('a[href$='+window.location.hash+']').action();
});
I think you could use onclick as an attribute in the tag or you could use the .click() event through jQuery. I think that will accomplish the same as the window on hashchange.
event.target will hold which element triggered the event.
I can't check at the moment, but I believe that this also binds.
try this:
$(window).on('hashchange', function(event){
var hash = location.hash;
var $this = $(hash);
alert($this.html());
});

How to take document on event handler except one class in document using jQuery?

I need to take whole document in mousemove event except one class in document using jQuery
My class is no-mousemove-node.
$(document).mousemove(
function(e){
....
});.
I tried like below, but no working
$(document).not('.no-mousemove-node').mousemove(
function(e){
....
});.
Is it possible to do this?
Use e.target inside your event handler to see if the source element matches your criteria, and abort execution if it does not:
$(document).mousemove(
function(e){
if ($(e.target).is(".no-mousemove-node")) return;
// now do what you need
}
});
Update: if you need to also filter out descendants of .no-mousemove-node use .closest to determine if you are, or have a parent that is, a .no-mousemove-node:
function(e){
if ($(e.target).closest(".no-mousemove-node").length) return;
}

Parent Took Precedence Over Child on DIV Click Event

I have a div and within the div there is a child img element.
Both div and img have their very own javascript click handler.
My objective is to have when I click on the img, only the img click is triggered.
But currently the div click handler is responding before the img click handler.
Here's the example: http://jsfiddle.net/5j73w/
I'm not sure if parent's position: relative is the culprit. But that's a compulsory style.
I also tried with z-index for img but no avail.
Thanks in advance!
Replace the deprecated .live() by .on() as you're using jQuery 1.7+.
$('#parent > img').on('click', function(e) {
Fiddle
Or, if you need the event delegation (e.g. in case you're adding content dynamically to #parent):
//run this line when #parent is in the DOM
$('#parent').on('click', '> img', function(e) {
Fiddle
.live bubbles the event all the way up to the document to then check if the given selector matches the target element, by then you can't stop the event propagation anymore. From the docs:
Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
Also, to answer the "parent takes precedence" question, that's not case. When you call .live, you're actually attaching a handler to the document.
In this case, the handler attached through .click(function(){}) (which in jQuery 1.7+ is a shorthand for .on('click'[, null], function(){}), executes before the handler attached to the document, which is the expected event propagation bubbling behavior.
Was able to fix by doing the following:
$('#parent').click(function(e)
{
console.log("parent click");
});
$('#child').click(function(e)
{
console.log("child click");
e.stopPropagation();
});
​
Here's the Fiddle.

Using .on() and e.stopPropagation() on dynamic elements

I have been experimenting with capturing click events outside of elements using stopPropagation().
$(".container").children().on('click',function(e){
e.stopPropagation();
});
$(".container").on("click",function(){
alert("outside the box?");
})​
Here is a jsFiddle set up to demonstrate it functioning. An alert should fire when you click anywhere outside of the white box.
Now, I am trying to have the same principle applied to dynamically created elements. As far as I understand, the on() method of event assignment in jQuery should allow this to function without changing the script.
Here is a second jsFiddle where you must first click a link to create the elements. Once you have done this, the theory is that the same script will work, but it does not. What am I missing about this method?
When the item is added dynamically, you should attach the handler to the closest parent that will surely be there - in your case this is body. You can use on() this way to achieve a functionality that delegate() used to offer:
$(selector-for-parent).on(events, selector-for-dynamic-children, handler);
So your code rewritten would simply be this:
$("body").on('click', '.container', function(e){
var $target = $(e.target);
if ($target.hasClass('container')) {
alert("outside the box!");
}
});
I used e.target to find which element actually triggered the event. In this case, I identify the item by checking whether it has the container class.
jsFiddle Demo
In short word you need to put on() on existing parent element to make it works:
$('body').on('click', 'a', function(e){
e.preventDefault();
$('<div class="container"><div class="box"></div></div>').appendTo('body');
$(this).remove();
});
$('body').on('click', '.container > *', function(e){
e.stopPropagation();
});
$('body').on('click', '.container', function(){
alert("outside the box?");
})​
Code: http://jsfiddle.net/GsLtN/5/
For more detail check '.on()' on official site at section 'Direct and delegated events'
The demo.
When you bind a event handler to a element use .on, the target you bind to must exist in the domcument.
$('body').on('click', '.container > *', function(e){
e.stopPropagation();
});
$('body').on("click",'.container',function(){
alert("outside the box?");
})​
You need to bind the .on() to a parent.
What you're trying to do is - bind the handler to a parent that listens for an event, then checks whether the event was triggered by an element that matches that selector.
$("body").on("click", '.container',function(){
alert("outside the box?");
})​
Updated fiddle here
According to the documentation for jQuery.on():
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
You will have to bind the event to a parent container. Perhaps something like THIS.

Global jQuery `.click()`

I would like to fire an event when anything on the page is clicked, and then process normally. For example a click would be fired, I would see if the target matched something, alert if it did, and then have the click event continue (no preventDefault()).
$(document).click(function(e) {
// e.target is the element which has been clicked.
});
This will handle all click events unless a handler prevents the event from bubbling up (by calling the stopPropagation() method of the event object).
$("body").click(function (event) {
// Your stuff here
}
3 options for you:
This is how .live() in jquery works. Everything bubbles to the top, and it matches the selector you set.
http://api.jquery.com/live/
A more efficient way to do it is using .delegate, or providing a context to .live() so you don't have to bubble to the top.
http://api.jquery.com/delegate/
If you want to do it manually, bind 'click' to the document, and use .closest() to find the closest matching selector:
http://api.jquery.com/closest/
It's all the same concept, event delegation as mentioned already.

Categories

Resources