jquery function call when clicking blank space - javascript

I need to know how to call the function if some one click in blank space in the jsp page.
I tried the following code but it's not working how I want.
Can any one tell me how to do this?
jQuery("*:not(select)").click(function(){
alert("clck");
//some code here
});
Here I tried whenever I click out side the select box the function will call.
If I click the select box it won't call, but this function is called all the time.
Why is this happening?

I'd probably do it something like this:
$(document).on("click", function(e) {
if (e.target === document || e.target.tagName === "BODY" || e.target.tagName === "HTML") {
// Clicked on blank space
}
});
That hooks the click event on document and then checks to see if the click originated on the document (or the body or html elements). If it did, the user clicked in "blank space" (e.g., not on some other element within the document).

Not sure will work in all browsers but in chrome.
$('body').click( function (e) {
if ( e.target == this )
alert('clck');
});

If you want a special item to be not included in the click try this
$('#itemtobeexcluded').on('click', function(e) {
e.stopPropagation();
});
Then for whole document:
$(document).on('click', function (e) {
// function body
});

may be this will work
$(document).on('click', function (e) {
alert('clck');
});

Related

EventListener not working with anchor tel:XXXXXXXXX

I have a tag with href="tel:XXXXXXXXX", and I need catch the click event.
I have tested the following code on chrome: $(document).on('click',console.log). If i click on this tag browser it calls the application, but does not trigger a click event.
$("a[href^='tel']").on('click', console.log);
This is working, but I my have a problem with content load by ajax. My code has loaded a page and after some time application added content by ajax. When i use $(document).on('click', ("a[href^='tel']", console.log), there is a problem.
$("a[href^='tel']").on("click", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
})
//or if you want to delegate your function
$(document).on('click', "a[href^='tel']", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
});
This will bind an event listener to all click on a tags with a href attribute and prevent the click itself. After click, you'll be able to use your console to see which element was click and what href was used.
Ok, i found resolve.
I use earlier event "mousedown" and change attr "href" to "only number" for disable action click.
Code:
const click2dial_Event = function(e) {
e.preventDefault();
let a = $(this), number;
if (a.attr('href') !== '#') {
number = a.attr('href');
number = number.substr(4);
a.attr('href', '#');
a.attr('data-dial', number)
a.addClass('click-to-dial');
} else {
number = a.attr('data-dial');
}
//...
};
$(document).on('mousedown', "a[href^='tel']", click2dial_Event);
$(document).on('mousedown', '.click-to-dial', click2dial_Event);
This would get the phone number from the a tag starting with a value of tel upon clicking it.
$("a[href^='tel']").on("click", function(e) {
var hrefText = this.getAttribute("href");
var str = hrefText;
var res = str.split(":");
alert(res[1]);
});
On Initial Load
I would first recommend that you wait for the initial DOM to be ready before binding any events to elements.
// DOM ready shorthand
$(function() {
$("a[href^='tel']").on('click', function(e) {
// Do work here
});
});
AJAX Content
If you are adding additional elements after the initial load you will have to bind events to those new elements as well.
You could also do something like adding a data attribute to the elements that you've bound click events to and only add to ones that don't yet have that data attribute - but that's additional unnecessary work.
Full Example Code
// DOM Ready Shorthand
$(function() {
// Click Handler
function clickEvent(e) {
// Do work here
}
// Bind click event to initial tels
$("a[href^='tel']").on('click', clickEvent);
// Arbitrary AJAX request for demonstration (wherever yours may be)
$.ajax('/newContent')
.done(function(html) {
// Adding our response HTML to the page within #someElement
$('#someElement').append(html);
// Bind click event to the new tel elements scoped to the returned html
$("a[href^='tel']", html).on('click', clickEvent);
});
});

How to make click handler handle when ANY "a" tag is clicked, regardless of what it's wrapped around?

Let's say I have this in my HTML page:
bar
<a href="/">
<div></div>
</a>
And I want to write a handler that handles when ANY "a" tag is clicked (with jQuery):
$(document).click((e) => {
const element = e.target;
if (element && element.nodeName === 'A') {
// Do something
e.preventDefault();
}
});
The above code only works for the top "a" tag, but not the bottom one. For the top "a" tag, element.nodeName equals A. For the bottom "a" tag, element.nodeName equals DIV.
How do I write a click handler that handles whenever ANY "a" tag is clicked, regardless of what it is wrapped around?
Capture delegated events in any parent element. Document will get all events if you don't call preventDefault before it arrives during the bubbling phase. Read about Event phases, it really pays off!
$(document).on("click", "a", function(event) {
// You have clicked an anchor
window.console.log ("You have clicked this anchor:", this," but you clicked maybe inside a div or a something inside the <a>", event.target);
});
https://jsfiddle.net/7ttm4y8k/4/
Note: As you are delegating the events to the document, this will work even for elements that were added after the handler's been set. This way you can setup your delegated anchor handler then maybe at a later time add anchors from an Ajax query without the need of setting handlers to every created anchor.
https://jsfiddle.net/82fpvwrL/
$("a").click(function(){
alert('WOO HOO! I was clicked.');
});
Apply it to every anchor.
document.getElementsByTagName('a').map(tag => tag.onClick = yourHandler);
Use something like this:
$(document).on("click","a", (e) => {
e.preventDefault();
const element = e.target;
// Do something
});
This is how I do it (w/o jQuery):
document.body.addEventListener('click', function(ev) {
var targetElement = ev.target;
while(targetElement !== null && targetElement.nodeName.toUpperCase() !== "A") {
targetElement = targetElement.parentElement;
}
// Proceed only if an A element was found in the ev.target's ancestry
if (targetElement !== null) {
ev.preventDefault();
// Your code here
}
}
This will catch the event at the body tag and is oblivious to a tags being added/removed in the document. It will work as long as the click event's propagation was not stopped by any elements in the DOM tree from the element to the body.

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.

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();
});

jquery priority execution

Can anyone help me with this:
$('#n').click(function() {
$(this).parent().append(' delete');
$(this).next().click(function() {
alert('clicked'); //this not working
});
$(this).blur(function() {
$(this).next().remove();
});
});
JS Fiddle demo; the problem is that the blur() event is executed before click() event.
You can use a timeout to postpone the removal for some milliseconds.
example : http://jsfiddle.net/vkun9/7/
$(this).blur(function() {
var _this = this;
setTimeout(function(){$(_this).next().remove();},100);
});
I also moved the blur attaching to be outside of the click handler, as it was adding an additional one each time the element was clicked, and changed the click handler to the focus to avoid multiple remove buttons from repeated clicking on the input, as #dheerosaur noted.
so
$('#n')
.focus(function() {
$(this).parent().append(' delete');
$(this).next().click(function() {
alert('clicked'); //this not working
});
})
.blur(function() {
var _this = this;
setTimeout(function(){$(_this).next().remove();},100);
});
What you experience, though, is not a problem. It is the normal behaviour, as the element need to lose focus (fires the blur) before another element can have it.
You should also match the label for attribute with the id of the input element.
Use the outside events plugin and you can do something like this:
$('.input_field input').focus(function() {
var div = $(this).parent();
var link = $('delete').click(function(e) {
e.preventDefault();
alert('clicked');
}).appendTo(div);
$(this).data('delete', link);
}).bind('focusoutside clickoutside', function(e) {
var link = $(this).data('delete');
if (link && e.target != link[0]) {
link.remove();
}
});
First switch to using the focus event rather than the click event on your input field, some people actually use the keyboard to navigate through form fields ;-).
Then its creating the delete link, adding it to the page and storing a reference to it in on the input field.
Then with the outside event plugin we can bind focusoutside and clickoutside which get triggered when the user tabs or clicks outside the input field. By checking of the target of the event was the delete link or not we can tell if we should remove the link.
Example: http://jsfiddle.net/petersendidit/vkun9/6/
you can try setting a very short timeout in the blur event. this worked for me.
$(this).blur(function() {
setTimeout(function(){$(this).next().remove();}, 1);
});
Rather than using blur() I put together a hover()-based approach, though it does have a slightly clunky if/else statement:
$('.input_field').hover(
function(){
if ($(this).find('.delete').length) {
return false;
}
else {
$('delete')
.appendTo($(this));
}
},
function(){
if ($('#n').is(':focus')){
return false;
}
else {
$(this).find('.delete').remove();
}
}
);
JS Fiddle demo.
This approach does, however, ensure that there's only one delete link appended to the input_field (rather than the multiple links appended if the input is clicked multiple times in your original demo).

Categories