How to detect left click anywhere on the document using jQuery? - javascript

I have this right now:
$(document).click(function(e) { alert('clicked'); });
In Firefox, this event is firing when I left-click OR right-click. I only want it to fire when I left-click.
Does attaching a click handler to the document work differently than attaching it to other elements? For other elements, it only seems to fire on left clicks.
Is there a way to detect only left clicks besides looking at e.button, which is browser-dependent?
Thanks

Try
$(document).click(function(e) {
// Check for left button
if (e.button == 0) {
alert('clicked');
}
});
However, there seems to be some confusion as to whether IE returns 1 or 0 as left click, you may need to test this :)
Further reading here: jQuery Gotcha
EDIT: missed the bit where you asked not to use e.button. Sorry!
However, the example here returns the same ID regardless of looking at it in FF or IE, and uses e.button. could possibly have updated the jQuery framework? The other answer is that older versions of IE return a different value, which would be a pain. Unfortunately I only have IE 7/8 here to test against.

You could simply register for a "contextmenu" event like this:
$(document).bind("contextmenu",function(e){
return false;
});
Taken from: http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks

I've read that if you bind with "live" in jQuery 1.3, jQuery normalizes the click between browsers. I've not tested this.
However, this would indicate that it doesn't: http://abeautifulsite.net/notebook/99
Since you say click works correctly everywhere but on "document," have you tried a 100% div over the document to catch the click?

There is no not-browser-dependent way to detect only left-clicks. You can use this code that works under IE and non-IE browsers:
$("#element").live('click', function(e) {
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
// Left mouse button was clicked (all browsers)
}
});
Taken from: http://abeautifulsite.net/notebook/99

Related

Keyup to Manipulate div

Haven't post in quite a while.
Anyway I was searching about my subject and I got this.
$(window).keyup(function(e) {
if (e.which === 8) {
$('.ilol'). fadeOut();
}
});
It's working perfectly fine. But when I change the window to a class or id it doesn't respond anymore.
There's not a lot of detail about the type of element you are trying to attach this event handler to, but the jQuery documentation explains that form elements (e.g. input) are a safe bet because they are able to be focused across most browsers:
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus. Focusable elements can vary
between browsers, but form elements can always get focus so are
reasonable candidates for this event type.
http://api.jquery.com/keyup/
It may also be a selector issue. Make sure that your selector is working properly by pasting it in your browser's JavaScript console and see if it returns any elements.
Make sure you are binding event in ready function.
$(document).ready(function(){
$('.someClassName').keypress(function(e) {
if (e.keyCode === 8) {
$('.ilol'). fadeOut();
}
});
});
After some testing this is what worked best for me. The 40 key in this example is the down arrow key.
$(document).keydown(function(e)
{
if(e.keyCode == 40){
$('.ilol').fadeOut('fast');
}
});

Disable mouse middle click in Firefox

Anchor tag is opening in new window while we have clicked middle button of mouse. I want to disable this new window/tab. The belwo provided code is working in chrome.
$("a").on('click', function(e) {
if( e.which == 2 ) {
e.preventDefault();
}
});
Checked following links:
Triggering onclick event using middle click
Disable middle mouse button for modal dialog
According to some better is to change anchor tag to some other tabs, but I need the default behavior of anchor tab in left click, I need to disable middle and right clicks. Somebody help me to solve this.
Note: Many questions are asked regarding the same, but this exact issue is not yet asked.
This is not working in Firefox. I need to solve this issue in Firefox too.
fiddle
This is for blocking middle clicking entire document on firefox. You can check whatever element by e.target. Its need jQuery, but u could also use vanilla js
$(document).on('auxclick', function(e) {
if( e.button == 1 )
alert('Its blocked globally');
e.preventDefault();
return false;
}
})
Pure html solution, no javascript:
Click me

focusin event triggers in IE for floated and Inline Block element

The focusin event which is a part of form inputs and link tag, is getting applied for div and span tags. It happens for floated and inline-block element. The issue is spotted in IE (8 and 9).
Demo ==> http://jsfiddle.net/Agczq/
Is there a way to stop this?
Unlike you might expect focusin and focusout do bubble up, unlike the regular focus event. The two main ways of dealing with this are: Event delegation, or simply stopping the event from bubbling up.
Your fiddle is hard to make sense of (ie: don't know what you're trying to do). The first thing that comes to mind (after moving your JS code to the JavaScript field on jsfiddle) is that you're capturing a focus event in good browsers, and the bubbling focusin in crummy IE. This can be quite annoying, particularly since IE doesn't support actual event capturing. Nevertheless, here's a (simple, but tested and working) suggestion:
function mycb(evt)
{
evt = evt || window.event;//get event object
var from = evt.target || evt.srcElement;//get source
if (evt.stopPropagation)//stop event from bubbling
{
evt.stopPropagation();//shouldn't be necessary, but you never know
}
else
{
evt.cancelBubble = true;//stop propagation in IE-lingo
}
if (from.tagName === 'DIV' || from.tagName === 'SPAN')
{//if source was a tag that souldn't fire event, return false;
if (evt.preventDefault)
{
evt.preventDefault();
return false;
}
evt.returnValue = false;
return false;
}
alert("fired!!!");
}
var elem = document.getElementById("mybox");
if( elem.attachEvent )
{
elem.attachEvent("onfocusin", mycb);
}
else
{
elem.addEventListener("focus", mycb, true);
}
This code was tested in IE8, fiddle can be found here. It just so happens I read about this event today, here. A source worth mentioning, I reckon.
Hope this helps

Will this JavaScript code affect other keypress events too by disabling one key?

I'm using this to disable the 'scrolling' effect the spacebar has in a browser. Will this affect other keypress events too?
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
Could someone please explain what this is doing? I'm not sure if this code is bad, but it seems to disable other keypress related codes in my page, and I want to make sure this isn't the reason.
Thanks!
ASCII code 32 is the ASCII value that represents the spacebar key, and your code is essentially telling the browser to return false whenever that keycode is detected. Since false is returned, the scrollbar effect you speak of is in fact successfully disabled.
However, the unfortunate side effect of this convenient spacebar-scroll-disabling function is that it disables spacebar keypresses everywhere on the page.
Instead of returning false, if the keycode is detected, pass the current scrollTop value into a closure that returns a function to a setTimeout event. When the setTimeout fires, the scrollTop position is reset back to the value it was in when the setTimeout event was first registered.
window.onkeydown = function(e) {
if(event.keyCode == 32) { // alert($(document).scrollTop() );
setTimeout(
(function(scrollval) {
return function() {
$(document).scrollTop(scrollval);
};
})( $(document).scrollTop() ), 0);
}
};
Your users can still conveniently make use of spacebars in input textboxes and textareas, and at the same time, pressing the spacebar key while not focused on a text element will no longer result in the page scrolling.
Under the hood, the scroll is still taking place. It's just being reset at a rate fast enough to where the user doesn't notice.
If you increase this value to 100 or 1000, it will give you a better idea of what is going on under the hood. You'll actually see the page scroll and then get set back to the previous scroll position.
This was only tested in Chrome and Firefox 13! So you may have to adjust the setTimeout duration -- currently 0 -- to a different value in browsers like Internet Explorer. Be prepared to gracefully degrade -- by supporting this feature only in modern browsers -- if necessary.
UPDATE:
For reference, below is the method to use to make this compatible in the major browsers. It has been tested in Chrome, Firefox, IE8, IE9, and Safari.
While it does work in IE8/IE9, it isn't very smooth.
// put the eventhandler in a named function so it can be easily assigned
// to other events.
function noScrollEvent(e) {
e = e || window.event;
if(e.keyCode == 32) {
setTimeout(
(function(scrollval) {
return function() {
$(document).scrollTop(scrollval);
};
})( $(document).scrollTop() ), 0);
}
}
// Chrome and Firefox must use onkeydown
window.onkeydown = noScrollEvent;
// Internet Explorer 8 and 9 and Safari must use onkeypress
window.document.onkeypress = noScrollEvent;
If another element is bound to the keydown event it will not be effected by this code
See my fiddle and try adding and remove the textarea listening to the keydown event
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
document.getElementsByTagName("textarea")[0].onkeydown = function(e) {
alert("hi");
}
http://jsfiddle.net/HnD4Y/
The answer above with the setTimeout did not work for me at all on Chome with a delay of 0. With a delay bumped above 50ms, it began to work, but that caused a noticeable page jump. I believe that setTimeout was scrolling the page up too early, then Chrome moved it down later.
Below is my solution that is working well. It returns false on the keydown event to prevent the browser from doing a page-down. Then you make sure event you set up on your button etc. to use the keyup event instead.
$(mySelector).keyup(eventHandlerFunction);
[dom element].onkeydown = function(event) {
if (event.keyCode == 32) {return false;}
};
Note: input fields will not reflect spacebar key events if they or their parent are covered by this onkeydown handler

IE is randomly minimizing when a link is clicked

I have the bizarre problem. When I click on a link in IE7 the window minimizes. It seems to only be a subset of the links on the page. It also doesn't consistently happen with the same link and differs from computer to computer.
example link text:
<a hidefocus="on" href="#" tabindex="1"><span unselectable="on" id="extdd-102">Canadian Legislation</span></a>
Anyone seen this before or have any idea what might be causing it?
Finally figured it out. It was actually a custom JavaScript click handler that caused the problem.
My click handler was calling activeElement.blur(); on the current active element (so that events tied to blur fired when the elements were destroyed).
Problem is in IE, if you call blur on anything that isn't an INPUT, it minimizes the window.
I had the same issue on Internet Explorer 10.
Internet Explorer 10 tested behaviour:
This issue only happen when you invoke the blur() function on document.body element.
Issue can be reproduced simply executing document.body.blur() in your browser console.
Common scenario in which this issue happens:
document.activeElement.blur() function invocation is the most common scenario in which this issue occurs because after first invocation of document.activeElement.blur() the body element will become the activeElement and subsequent call to document.activeElement.blur() will invoke blur on body element.
Solution:
avoid document.body.blur() function invocation, if you have jquery you can introduce this simple logic
$(yourObj).is('body')
to check if your object is the body element, in order to avoid blur() function invocation on it
IE is buggy, so you can troubleshoot by removing "tabindex". If that doesn't work try removing "unelectable" then "hideonfocus". "Hideonfocus" sounds weird. Try removing that first. Do you have any third party programs or plugins that interact with IE? Does it work on a different computer?
This happened when I used the blur workaround to get the placeholder attribute to work on IE8.
In the workaround I should call blur() which caused the browser to blur (minimize to tray).
The solution is to use:
$.each($('[placeholder]'), function(i,item){ item.blur();});
which is only being specific what to call blur on.
The complete placeholder workaround is:
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() === '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$(window).on('load', function () {
if ( $('[placeholder]').length ){
$.each($('[placeholder]'), function(i, item){item.blur();});
}
});

Categories