Get clicked element in delegated event with jQuery - javascript

I have some elements that I add to the DOM after the page has been loaded. And I'd like to perform some actions when I click on them. I'm using the delegation with jQuery but I don't know how to get the clicked element when I'm in the fonction ($(this) refers in this case to the parent)
<div id="parent">
<div class="child">
<div class="hidden"></div>
</div>
<div class="child">
<div class="hidden"></div>
</div>
</div>
<script>
$('#parent').click('.child', function(){
$(this).find('.child').toggleClass("hidden displayed")
});
</script>
Let's say I want to toggle the inner div from "hidden" to "displayed" when I click on the "child" div. Currently when I click on the first "child" div, the two "hidden" div will be toggled, and I want to be toggled only the one in the div I clicked.

Use e.target to find out which element the event originated on.
$('#parent').on('click', '.child', function(e){
$(e.target).toggleClass("hidden displayed")
});
I also fixed the code a bit - you need to use .on for delegated events. (Mentioned by Barmar.)

You need to use .on() to delegate events. As the documentation says:
When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector.
So it should be:
$('#parent').on('click', '.child', function() {
$(this).toggleClass("hidden displayed");
};
Your use of .click('.child', function...) does not do delegation. It matches the function signature:
.click(eventData, handler)
described here. So it's just binding to the parent, not delegating to the child, that's why you get the wrong value in this.

Related

Stop click from propagating to a parent

When a particular element is clicked, I want to call a function. When any of its children are clicked, I do not want to call the function.
I am not using jQuery.
Example:
I created a modal:
<div class="fullscreen-overlay">
<div class="card">
...
</div>
</div>
I want to call my closeModal() function when ".fullscreen-overlay" is clicked, but not when ".card" or any of its content are clicked.
jsfiddle:
https://jsfiddle.net/5kuwmf9s/
Research:
I could've sworn there was a CSS attribute for this, but after Googling and searching on SO for it, I can't find it / might've been imagining it. "pointer-events" stops it on the target element, not bubbling.
Theres another answer that suggests attaching an event handler to ALL children that catches their events and stops propagation - which seems unnecessary. My children are dynamic, and this will get complicated to keep attaching handlers.
You might have compared event's target and currentTarget
They would be equal only if the current element is the one that was the initial source of the event:
function handleClick(e){
if (e.target === e.currentTarget) {
alert('clicked!');
}
}
References:
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
JSFiddle: https://jsfiddle.net/u78k4k6t/
try use an element and style it as your '.fullscreen-overlay' and bind event to this element
as the answer link shows
use event.target or event.srcElement

Remove all events binding inside a parent div using jquery

I have myclass div and inside that there are many childs with different event binding. On clicking "remove" below, I want to remove all events binding of all child in it. But following code is not working.
<div class="myclass">
<select class="selectable">
<option value="1">one</option>
<option value="2">two</option>
</select>
<!-- I have many more elements ~30 or so with events associated with them.... -->
<div id="askme">ask me</div>
</div>
<div class="xyz">i have event on this element too that should remain intact>/div>
<div id="remove">remove</div>
<script language="javascript">
$(document).on('ready page:load', function () {
$(document).on("change",".selectable", function(e) {
//something
});
$(document).on("click","#askme",function(e){
//something
});
//more events binding here.....
});
// Using http://api.jquery.com/off/
$("#remove").on('click', function (e) {
$(".myclass *").off(); //unbind event of all child under `myclass` parent div
});
</script>
When I click "remove", I want to remove all events associated with all elements inside myclass div.
I don't want to use .one for invoking events with child elements only once. So that is out of scope to solve this problem.
Note:
I have other dom elements in document, that should remain intact. SO I cannot unbind events on document level
This answer was from a previous post How to remove all event handlers for child elements of a parent element using JQuery
You can use unbind() if you used bind() to attach the events.
$('#foo').children().unbind();
$('#foo').children('.class').unbind(); //You can give selector for limiting clildren
or
Use off() if you used on() to bind events.
$('#foo').children().off();
$('#foo').children('class').off()
You have attached the events to the document, so you need to do the off in document element:
$(document).off();
DEMO
EDIT:
Then you need to unbind this way:
$("#remove").on('click', function (e) {
$(document).off("click","#askme");
$(document).off("change",".selectable");
});
DEMO2

Delegated events don't work in combination with :not() selector

I want to do something on all clicks except on a certain element.
I've created a very simple example which demonstrates the issue: http://jsfiddle.net/nhe6wk77/.
My code:
$('body').on('click', ':not(a)', function () {
// do stuff
});
I'd expect all click to on <a> to be ignored, but this is not the case.
Am I doing something wrong or is this a bug on jQuery's side?
There's a lot going on in that code that's not obvious. Most importantly, the click event is actually attached to the body element. Since that element isn't an anchor, you'll always get the alert. (Event delegation works because the click event bubbles up from the a through all its ancestors, including body, until it reaches document.)
What you want to do is check the event.target. That will tell you the element that was actually clicked on, but the actual click event is still bound to the body element:
$('body').on('click', function (e) { // e = event object
if ($(e.target).is(':not(a)')) {
alert('got a click');
}
});
http://jsfiddle.net/y3kx19z7/
No this is not a bug but rather intended behaviour.
The event bubbles all the way up. By clicking the a node, you are still triggering it's parents event from the div node.
Read more about event bubbling in the W3C DOM Specification. Just search for "bubble".
You need to stop the event propagation of the a nodes. i.e.:
$('body').on('click', ':not(a)', function () {
// do something effectively
alert('you should not see me when clicking a link');
});
$("a").click(function( event ) {
// do nothing effectively, but stop event bubbling
event.stopPropagation();
});
JSFiddle: http://jsfiddle.net/nhe6wk77/6/
It's working as intended, here's why!
Use of the :not() selector is honored in delegated events, but it's an uncommon practice because of how events bubble up the DOM tree potentially triggering the handler multiple times along the way.
The jQuery API Documentation states that:
jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Notice the phrase "and runs the handler for any elements along that path matching the selector".
In your example, jQuery is accurately not running the handler on the a element, but as the event bubbles up the tree, it runs the handler for any element that matches :not(a), which is every other element in the path.
Here is a clear example showing how this works: http://jsfiddle.net/gfullam/5mug7p2m/
$('body').on('click', ':not(a)', function (e) {
alert($(this).text());
});
<div class="outer">
<div class="inner">
Click once, trigger twice
</div>
</div>
<div class="outer">
<div class="inner">
<button type="button">Click once, trigger thrice</button>
</div>
</div>
Clicking on the link in the first block of nested divs, will start the event bubbling, but the clicked a element — a.k.a. the event target — doesn't trigger the handler because it doesn't match the :not(a) selector.
But as the event bubbles up through the DOM, each of its parents — a.k.a the event currentTarget — triggers the handler because they do match the :not(a) selector, causing the handler to run twice. Multiple triggering is something to be aware of since it may not be a desired result.
Likewise, clicking on the button in the second block of nested divs, will start the event bubbling, but this time the event target does match the :not(a) selector, so it triggers the handler immediately. Then as the event bubbles up, each of its parents matching the selector triggers the handler, too, causing the handler to run three times.
As others have suggested, you need to either bind an alternate handler that stops propagation on a click events or check the event target against the :not(a) selector inside your handler instead of the delegated selector.
$("body").click(function(e) {
if($(e.target).is('a')){
e.preventDefault();
return;
}
alert("woohoo!");
});
check the target of the click. this way you dont need to bind another event.
updated fiddle

How to add onclick to Div with a specific class name?

I have a few generated div's on my page listing events on a calender, they all have the same class "fc-event-inner". I would like to add a onclick to these div's but am struggling to get this right.
This is what iv tried, no onclick is added and no errors on page.
$(document).ready(function () {
$('.fc-event-inner').each(
function (element) {
Event.observe("click", element, EventClick);
}
);
function EventClick() {
alert("You clicked an event")
}
});
This is an example of a generated event div:
<div class="fc-event-inner">
<span class="fc-event-title">Requested<br>by Santa</span>
</div>
Use the delegate version of on
$(document).on("click", ".fc-event-inner", function(){
/// do your stuff here
});
This catches the click at the document level then applies the class filter to see if the item clicked is relevant.
Example JSFiddle: http://jsfiddle.net/BkRJ2/
In answer to comment:
You can access the clicked element via this inside the event function. e.g.
$(document).on("click", ".fc-event-inner", function(){
var id = this.id; // Get the DOM element id (if it has one)
var $this = $(this); // Convert DOM element into a jQuery object to do cool stuff
$this.css({'background-color': 'red'}); // e.g. Turn clicked element red
});
*Note: You should never have to run an Each in order to catch events on multiple items that have a common class.
You do not need each() to bind event to elements with specific class, just selector is enough. Use jQuery on() with event delegation it will bind event to those which are generted after the binding code.
$(document).on("click", ".fc-event-inner", function(){
alert("click");
});
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, jQuery doc.
<div class="fc-event-inner">
<span class="fc-event-title">Requested<br />by Santa</span>
</div>
Your JS:
<script>
$(document).ready(function () {
$('.fc-event-inner').on("click", EventClick);
function EventClick() {
alert("You clicked an event")
}
});
</script>
http://jsfiddle.net/UBhk9/
Some explanation:
Because you are using a class(it may be used multiple times, in contrast to an id) it will work for all the elements with this class name. The .on method will attach the event handler(in this example "click") to the selector(the class .fc-event-inner). If you want to remove events bounds you've to use the .off() method and if you only want to attach the event once you can use the .one() method.

Why is a jQuery function still called once the class or id used as the selector has been removed from the HTML?

http://jsfiddle.net/q98G6/
HTML
<p>[QUESTION]</p>
<div class="answer-notdone">
<p>[CONTENT_1]</p>
</div
<div class="answer-notdone">
<p>[CONTENT_2]</p>
</div
<div class="answer-notdone">
<p>[CONTENT_3]</p>
</div
JavaScript
$(".answer-notdone").click(function(){
markQuestion(this); //external function
$(".answer-notdone").addClass('answer-complete').removeClass('answer-notdone');
)};
The example above is for a multiple choice question in a quiz - the user should only be able to click the answer once, and then it should be 'unlinked' from that jQuery function.
But the problem is even after the class has been removed successfully, the jQuery function is still called when clicked. Why?
Here is a fiddle I made of a demo, if the code above was not clear: http://jsfiddle.net/q98G6/
The selector is only used to find the elements, once the element is found and the event handler is attached to it, the selector does not have any relevance because the handlers are attached to the element not to the selector.
One way to solve the problem is to make use event delegation. In event delegation the handlers are attached to an ancestor element and we pass a selector as a target element. In this method the target selector is evaluated lazily.
$(document).on('click', ".answer-notdone", function(){
markQuestion(this); //external function
$(".answer-notdone").addClass('answer-complete').removeClass('answer-notdone');
)};
The selector returns all the elements that match it at the time you bind the handler, and then it attaches the handler to all those elements. Changing an element's class later does not remove the event handlers that were already bound.
If you want your handler to be bound to dynamically changing elements, you should use delegation:
$(document).on('click', '.answer-notdone', function() {
...
});
Try this
$(document).on('click',".answer-notdone",function () {
//markQuestion(this);
$(".answer-notdone").addClass('answer-complete').removeClass('answer-notdone');
});
FIDDLE DEMO

Categories

Resources