jQuery Child Event Handling - javascript

I have a container element. The element may or may not have anchor tags in it. I want to listen for click events within that element. I want to handle each click only once, but I want to do something different if an anchor tag is clicked.
Issues that I've run into:
Listening at the container element level doesn't capture the anchor tag clicks: $('#ID').on('click', myFunction);
Listening to every child in the container ends up firing multiple events: $('#ID').find(*).on('click', myFunction);
How do I accomplish this?

This should work:
$('#ID').on('click', function(e) {
if ($(e.target).closest("a").length) {
anchorWasClicked();
} else {
somethingElseWasClicked();
}
});

You can check the target of the click. And as you seem to be trying to enable the click just once for every element within the container, you should then use .one():
$(function() {
$("#container").children().one("click", function(e) {
e.preventDefault(); // For testing purposes.
if ($(e.target).parents().is("a") || $(e.target).is("a")) {
// Anchor.
}
else {
// Others...
}
});
});
Demo
That's an improvement to the example I've posted in the comments previously.

Related

Fire event only when clicking on an element, and not on its children

If I bind a click handler to the body element, when I click anything on the page the event is triggered. I can check the event.target on every click:
$("body").on("click", function(event) {
if (event.target.tagName == "BODY") {
...
}
});
but that seem a bit overkill. Is there a way to trigger the event only when clicking the blank area of the body itself?
You can use the eventPhase property of event. A value of 2 means that the event is currently triggering the target element:
$("body").on("click", function(event) {
//Cancel if not at target
if (event.eventPhase != 2) return;
//Other Code Here
});
Fiddle Here: http://jsfiddle.net/o0yptmmp/
You should put an
event.stopPropagation()
on all children you want to not bubble up.
jQuery Docs: http://api.jquery.com/event.stoppropagation/.
You can do it if you check on every click if the element clicked has a body parent. If the condition is false, you are clicking the body:
$("body").on("click", function(event) {
if ($(this).parents('body').length == 0) {
//Do something
}
});
In my opinion it's not a good practice, but it depends on your code and project.

Detecting class on HTML element not working correctly

I have a button and when it is clicked it should add a class to the HTML element, but then when the .class is clicked, it isn't detected.
This is the use case:
Click button - "testerclass" will be added to HTML element
Click "testerclass" - removes that class from that element
The detection for when "testerclass" is clicked only seems to work when the class exists before the page load, not when I add the class manually after load. Is this something to do with the problem?
I have tried to recreate the problem on jsfiddle, but I can't recreate the use case where the class is already added to the HTML element, as I can't edit that on jsfiddle.
But here is jsfiddle one, In this one you can see that the buttonone adds a class to HTML, but the detection for clicks on .testerclass never come through.
And here is jsfiddle two. In this one, I have changed the .testerclass selector to html, and this shows that HTML clicks are bubbling through (which I was unsure of when I first hit this problem).
And offline I created a third testcase where the HTML element already had the testerclass, and it detected the clicks sent through to it.
$(document).ready(function() {
$('button.1').click(function() {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Edit: I also tried doing this with a slightly different method of:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
but that didn’t work either.
Since the testerclass is dynamic, you need to use event delegation to handle events based on that. Which will require us to register the event handler to the document object that causes another problem because the click event from the button will get propagated to the document object which will trigger the testerclass click handler as well. To prevent this from happening you can stop the event propagation from the button.
$(document).ready(function () {
$('button.1').click(function (e) {
e.stopPropagation();
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$(document).on('click', '.testerclass', function () {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Demo: Fiddle
You need to stop the propagation to the html so the other click handler does not pick it up.
$('button.1').on("click", function(evt) {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
evt.stopPropagation();
});
$(document).on("click", function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
Other option would be to add one event handler and use the event target to see if it is the button or not and change the content that way.
$(document).on("click", function (evt) {
var isButton = $(evt.target).is(".btn");
var message = isButton ? '<p>"testerclass" added to html</p>' : '<p>"testerclass" clicked and removed</p>'
$('html').toggleClass('testerclass', isButton);
$(".test").append(message);
});
JSFiddle: http://jsfiddle.net/69scv/
here's a neat way to do it
$('html').on('click', function(e) {
var state = !!$(e.target).closest('button.1').length;
var msg = state ? 'class added' : 'class removed';
$(this).toggleClass('testerclass', state);
$('.test').append(msg + '<br>');
});
FIDDLE
You add a class to html element, so when this class is clicked, it means the html element is click. Now the problem is when you click any where in page, it will remove this class away from html! Let try add this class to body element instead.
$(document).ready(function() {
$('button.1').click(function() {
$('body').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('body').removeClass('testerclass');
});
});
And now you can check it:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});

Stop propagation not working, avoid children click trigger other function

I write simple overlay for my page, kind of lightbox, but is going to do other stuff, anyway, My bigger problem in this tests... is I want when you click the overlay mask, the overlay close... But if you click in the children div, like the content div inside the overlay the overlay must remain open.. (which is not, that's the problem)
http://jsfiddle.net/7Cr2V/
How can I say in Javascript, if I click a child div of "overlayfull" please do not close or hide the overlayfull ... here is my code.. and above is the js fiddle if you want to check it cause my English is very bad.
$('div.vidreveal a').click(
function(event) {
event.stopPropagation();
$('div.videoquon').fadeToggle(300);
$('div.overlayfull').fadeToggle(300);
}
);
$('div.my-video-close').click(
function(event) {
event.stopPropagation();
$('div.videoquon').fadeToggle(300);
$('div.overlayfull').fadeToggle(300);
}
);
$('div.overlayfull').click(
function(event) {
event.stopPropagation();
$('div.videoquon').fadeToggle(300);
$('div.overlayfull').fadeToggle(300);
}
);
One solution is to add a click handler to the children, in which you stop propagation:
$('div.overlayfull').children().click(function(event){
event.stopPropagation();
});
stop propagation only works for parent elements it doesnt not stop the active element itself. you can encompass the text with a class and return false if clicked on that
<div id='my-video'></div>
<div class="message">CLIC HERE MUST NOT CLOSE THE OVERLAY</div>
</div>
if (event.target.className === 'message')
return false;
http://jsfiddle.net/59trN/
I think this is the simplest way to do it if I understand the question correctly. I just check within your handler to see if the div getting clicked on is the one you don't want to close the modal, and return from the function before the fadeout is triggered:
$('div.overlayfull').click(
function(event) {
if ($(event.target).hasClass('videoquon')){
return;
}
event.stopPropagation();
$('div.videoquon').fadeToggle(300);
$('div.overlayfull').fadeToggle(300);
}
);
Check out the fiddle http://jsfiddle.net/aRDKS/
Either have an event for the divs inside overloay div and stoppropagation on that. Inorder to stop the Propagation of event occurring on the children of a parent which has that particular event's handler, either check for the target from where the event generated in the paent handler or add a handler for the children and apply event.stopPropagation() to avoid the event bubbling up to the parent.
$('div.overlayfull div').click(function (e) {
e.stopPropagation()
});
or check for the target's id from which the event was generated:
function (event) {
if (event.target.id == 'overlayfull') { // Check here if the event originated from the intended div itself
$('div.videoquon').fadeToggle(300);
$(this).fadeToggle(300);
}
});
Fiddle

jquery not function miss element

I use a tool-tip to display error message on the page, I need it to be closed when I click elsewhere within the view. I use the below codes to control this action:
$(':not(.qtip)').click(function(){
$('.qtip').hide();
});
The ".qtip" is used for marking the tool-tip area. The tool-tip itself creates a new one when it comes out, what happened here is when I click on the tool-tip, it disappears.
But when I use a smaller scale of the selector instead of the whole body, it works fine, which is a little weird, for example:
$("#id").not('.qtip').click(function (){
$('.qtip').hide();
});
It would be advisable to just target document for handling the click outside of your tooltip; the selector for :not(.qtip) potentially returns a very big result set.
$(document).on('click', function() {
$('.qtip').hide();
}
On the tooltip itself you would need to prevent the click event from bubbling to document level, if you're not doing so yet:
$('.qtip').on('click', false);
Use event bubbling to your advantage
$(document).on("mouseup", function (e) {
var target = e.target || e.srcElement;
var container = $(".qtip");
if (container.not(target) && container.has(target).length === 0)
{
container.hide();
}
});
I suggest you to do two things:
$(document).click(function() {
$('.qtip').hide();
});
$('.qtip').click(function(e){
e.stopPropagation();
});
click of document to hide the .qtip
stop the event bubbling on click of .qtip, here click won't traverse up to the parent.
Try
$(document).on("click", function(e) {
var qtip = $(e.target).closest('.qtip');
if(!qtip.length)
$('.qtip').hide();
});

Bind to events inside dynamically created iframe

I need to bind to an event (say a click on an arbitrary <input>) inside an iframe that is created dynamically after the user performs a certain action. The code that appends the iframe AND the code inside the iframe is not mine and I cannot change it in any way (this is a CMS admin panel).
How can I listen to the events using jQuery 1.6 (again, this is not my choice, I'm stuck with it). I thought delegate() might be what I want:
$('body').delegate('iframe input', 'click', function(e) {
alert('bingo?');
});
But the above does not alert when an input is clicked. The below, however, works as expected:
$('body').delegate('input', 'click', function(e) {
alert('bingo?');
});
But this is outside the iframe.
The src of iframe points to the same domain, obviously.
Any help or just a prod in the right direction is greatly appreciated.
This 'iframe input' does not selects input elements inside the iframe.
You can bind the event like
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
I think You can also use something like
$('body iframe').contents().find('body').delegate('input','click',function(e) {
alert('bingo?');
});
To detect if the iframe has been fully loaded, use the method described in this answer
https://stackoverflow.com/a/5788723/344304
Add In the main/parent document:
function iframeLoaded() {
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
}
Add In the iframe document:
window.onload = function() {
parent.iframeLoaded();
}
Or use
$('body iframe').load(function(){
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
});

Categories