if clicked arround element with jQuery - javascript

i just wanna ask if there's something like "if clicked arround" in jQuery, i mean, if clicked any element in the page except for one element, or if there a way to make that easily.

You can try this:
$(document).on("click", function(event) {
if($(event.target).parents().index(yourElement) == -1) {
// your code here
}
});

Yes you can use .not()
event.stoppropagation
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('#divID').not('#ElID').click(function(){
//* code here */
});
Or
:not()
$('#divID:not("#ElID")').click(function(){
//* code here */
});
Start Reading jQuery API Documentation and Learning
Updated After OP's comment.
Fiddle Demo
event.target and .is()
$('#divID').click(function (event) {
if (!$(event.target).is('#ElID')) {
alert('Work');
}
});
Fiddle Demo
Works on click anywhere except element with id ElID
$('html').click(function (event) {
if (!$(event.target).is('#ElID')) {
alert('Work');
}
});

Related

Capturing and bubbling events

I created the next jsfiddle:
http://jsfiddle.net/AHyN5/6/
This is my code:
var mainDiv = document.getElementsByClassName('mainDiv');
var div = mainDiv[0].getElementsByClassName('data');
mainDiv[0].addEventListener("click", function(e) {
alert('1');
});
$(mainDiv[0]).children('img').click(function (e) {
e.stopImmediatePropagation()
return false;
})
I want that click on the pink background will popup a message with value of 1(an alert message).
When clicking the yellow, I want nothing to happen.
I read this blog but with no success..
Any help appreciated!
I agree with the others stating to use jQuery or straight DOM calls.
Here is another shot at the jQuery solution - very similar to the one above. I went ahead and presented it because it targets the images directly - in case that's what you're really trying to accomplish.
$(function()
{ var mainDiv = $('div.pink:first'),
imgs = $('img');
mainDiv.click(function()
{ alert('1');
});
imgs.click(function(e)
{ e.stopImmediatePropagation();
});
});
You could add pointer-events: none; to the yellow class. That will cause those elements to not fire click events.
See here for more info https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
You have a mix of jQuery and DOM methods calls. Note also that for attaching event listeners, you should wait for all HTML document to be ready.
I'd recommend using either DOM methods ot jquery methods. Following is an example of jquery:
$(function(){
$('.pink:first').on("click", function(e) {
alert('1');
});
$('.yellow').on('click', function (e) {
e.stopPropagation();
});
})
See also this JSfiddle

Ignore click on div

I have set an "onmousedown" event handler for the body of my page. In this page there are some div elements, is it possible to ignore the clicks on these divs, and to just fire the onmousedown event handler of the body with the correct coordinates, as if the divs were not present?
If you want a click on a div to result in nothing, use this CSS declaration:
div {
pointer-events: none;
}
or use this to stop any event from firing by a click on a div:
$('div').click(function(e) {
e.stopPropagation();
});
Add a custom class to the div elements you want to ignore clicks (let's say, ignore-clicks):
div.ignore-clicks {
pointer-events: none;
}
Yes, add stopPropagation(); to your divs to stop the click event from bubbling.
$("div").click(function(e) {
e.stopPropagation();
});
Sample to avoid click on div
$("body :not(div)").click(function(){alert("Test")})
as u use jquery
$(document).ready(function() {
$('body').click(function(e) {
if (e.target == this) {
alert('Parent was clicked');
}
});
});
https://jsfiddle.net/1ox8akcx/1/
You can also use event.target to determine where the user has clicked. Just ad the following snippet inside your event-listener for the body:
if($(e.target).is('div')){
return false;
}
Demo
The .is() can of course be used with specific classed or other selectors.
Demo 2
Reference
.is()
Try this: http://jsfiddle.net/eaL53d62/1/
(function(){
$('#body').on('mousedown', ':not(.not-clickable)', function(e){
alert('clicked');
});
}());
Specifically, using the :not() selector will ignore specific elements

JQuery .on("click", function() ) doesn't work

I am trying to fire JQuery when I checkbox is checked. At first I realized my JQuery only works for static elements. I read through a couple posts and found out that I need .on("click, function()) in order to fire that same piece of javascript for dynamically added elements.
However, this method still doesn't work for me. Can anyone help? Thank you.
$(document).ready(function(){
$("input[name='todo']").on('click', function(){
var isChecked = this.checked
if (isChecked == true){
$(this).next().remove();
$(this).remove();
}
if (isChecked == false)
{
alert("checkbox is NOT checked");
}
});
});
My example app: http://jsfiddle.net/JSFoo/7sK7T/8/
You need delegation:
$('#ToDoList').on('click', "input[name='todo']", function() { ... });
http://jsfiddle.net/7sK7T/9/
Documentation: http://api.jquery.com/on/#direct-and-delegated-events
PS: the important note - you need to specify the element you're binding your handler to as close to the target elements as possible. In your case it's #ToDoList, not body or document as other answers advice.
For dynamic elements you would want to do something like this
$(document).ready(function () {
$(document).on('click', "input[name='todo']", function () {
var isChecked = this.checked
if (isChecked == true) {
$(this).next().remove();
$(this).remove();
}
if (isChecked == false) {
alert("checkbox is NOT checked");
}
});
});
if you use it like you were before on('click') is basically the same as click(); because you are still selecting the elements required and applying the event to those elements, the way the above example works is it is only applies the event to the document then checking the selector when the event is fired.
You can also change document to a close container of the elements to be clicked if you wish.
This is called Event Delegation
jQuery Learn Event Delegation
The below is what you needed. It is slightly different syntax
$(document).on('click', "input[name='todo']", function(){
You bind the elements on document ready, it's before they're created.
You have to bind AFTER their creation.
Alternatively you can bind their container on document.ready:
$("#containerDiv").on('click', "input[name='todo']", function(){
// .... your code
});
"containerDiv" should be the parent element of those checkboxes, it should be in the page on document ready!

jQuery on click on everything but a div and it's children

I want to do something when I click anywhere, except when I click a div and it's children. This is what I've tried so far, but it's not working (clicking on it's children still executes what is within the brackets.
$('body').on('click', '* :not(#calculator)', function(e){
I cannot use something like this:
jQuery - Select everything except a single elements and its children?
$("body > *").not("body > #elementtokeep").remove();
Because the .not function is not something I can put inside the .on() function.
How can I achieve this?
Use not with a comma to have both selectors: the element itself and the elements children
jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){
console.log(this);
e.stopPropagation();
});​​​​​​​
jsFiddle
You could check inside the function for the element in question:
$('body').click( function(e){
if (!$(e.target).is("#calculator") || $("#calculator").has(e.target).length ) {
// do your stuff
}
});
I don't have enough requirement to add commend, so I need to ask my question here to #epascarello. When I made few children, A and B still affected. I am not sure I am wrong or not, but I really want to get solution.
jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){
console.log(this);
e.stopPropagation();
alert('test');
});
Live Demo
Instead of
$('body').on('click', '* :not(#calculator)', function(e){
});​
You can use (this version is preferred as it is more performant)
$("body").on("click", ":not(#calculator, #calculator *)", function(e){
});​
or
$("body :not(#calculator, #calculator *)").on("click", function(e){
});​

jquerys' e.stopPropagation() cannot get required functionality

photoContainer below has children. This works okay, but if I click on any of its children the code execute, hides blackLayer and removes photoContainer. How can I prevent this from happening and yet execute when I click anywhere but on photoContainer children ?
Thanks.
$('div#photoContainer').live('click', function (e) {
e.stopPropagation();
var blackLayer = $('div#blackLayer');
if (blackLayer.length) {
blackLayer.fadeOut();
}
$(this).remove();
});
I believe the problem is that you are stopping the propagation of the event on the parent element, you want to stop the propagation of the event on the children of the #photoContainer element so it does not propagate up to the #phoeoContainer element:
$('#photoContainer').live('click', function (e) {
var blackLayer = $('div#blackLayer');
if (blackLayer.length) {
blackLayer.fadeOut();
}
$(this).remove();
});
$('#photoContainer > div').live('click', function (event) {
event.stopPropagation();
});
This will stop the propagation of the click event when it is triggered on a child div of the #photoContainer element.
Here is a demo: http://jsfiddle.net/J9dBS/2/ (notice that if you click on the "child" element that no alert is shown)
I would like to note that .live() is deprecidated as of jQuery 1.7. If you are using jQuery 1.7 or later then it's suggested to use .on() like this:
$(<root-element>).on(<event>, <selector>, <event-handler>)
Or if you are using jQuery 1.4.2 to jQuery 1.6.4 then it's suggested that you use .delegate():
$(<root-element>).delegate(<selector>, <event>, <event-handler>);

Categories

Resources