Reputation: 43547
$('a').click(function(e){return false;});
It successfully disables links almost everywhere but does not work on the links found in the tooltip-popups on the topic tags on this site (SO). I looked at the DOM and they are indeed <a>
tags.
How come?
Is there a more robust way to force my user to stay on the current page? (This is for a bookmarklet where I graphically manipulate the DOM so I need to be able to click and drag everything, including links.)
I know that even if I can disable the regular click functionality on all anchors it won't do anything for any navigation triggered by other click callbacks on other tags.
Upvotes: 1
Views: 174
Reputation: 1092
A technique I've employed before is to place an invisible absolutely-positioned element over the entire document. This is actually employed by Firebug Lite to allow the Element Inspector to intercept any clicks.
All you need to worry about then is attaching your event listener to your absolutely-positioned element and figuring out what element was under the mouse when you clicked. Luckily, all modern browsers implement a method to discern this: document.elementFromPoint. There are a few differences between implementations; here's the method I usually use (unfortunately feature detection's a bit tricky for this, so I'm doing browser detection):
var scrollIsRelative = !($.browser.opera || $.browser.safari && $.browser.version < "532");
$.fromPoint = function(x, y) {
if(!document.elementFromPoint) return null;
if(scrollIsRelative)
{
x -= $(document).scrollLeft();
y -= $(document).scrollTop();
}
return document.elementFromPoint(x, y);
};
Attach a click event listener to your absolutely-positioned div and on click, hide your div and call this method to get the element, then show your div again. Example:
$('#hugeDiv').on('click', function(ev) {
var x = ev.pageX;
var y = ev.pageY;
$(this).hide();
var el = $.fromPoint(x, y);
$(this).show();
//do stuff with el
});
Upvotes: 1
Reputation: 1985
try with .on - in e.g. SO sites those links are created later then your event attached
$(document).on('click', 'a', function(e) {
return false;
});
Upvotes: 3
Reputation: 43547
It would appear the solution is
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
A right proper use of an event system if I would say so myself.
The original scope of the question was not wide enough. This solves the problem that led to my question.
Upvotes: 0