I using the Javascript library D3 and I have the ability to select multiple nodes by using shift + left mouse click. When I do this in Firefox (as my nodes have images appended) it opens the image in a new window/tab. I don't really want this happening.
How do I stop this event from firing ?
with jquery:
jQuery(document).keydown(function(e){
if(e.which === 16) {
e.preventDefault();
return;
}
});
update:
How about instead of disabling shift, you try to disable the click. you might stop it if you attach a click event and use an event.preventDefault() on it
This is how in d3 you completely disable clicks
d3.select("#prevent_link").on("click", function() {
var e = d3.event;
if(e.shiftKey) {
// CANCEL THE EVENT, WHICH WILL PREVENT ANY LINKING FROM OCCURING
e.preventDefault()
}
});
If you still want the link to work — but open in current window instead of new window — you can do this:
d3.select("#prevent_window").on("click", function() {
var e = d3.event;
if(e.shiftKey) {
e.preventDefault()
// Get the href of the <a> tag that was clicked
var href = d3.select(this).attr("href");
window.location = href;
}
});
Here's a jsFiddle. The last example doesn't work because jsFiddle doesn't let you save scripts that contain window.location, so I didn't include the last line (window.location = href;) in the fiddle.
Related
I have a Javascript function with following code.
function NodeClickActions(sender, eventArgs) {
event.preventDefault();
//Get whether user clicked CTRL key or not
var bCtrlPressed = eventArgs.get_browserEvent().ctrlKey;
//URL of the actions page
var URL = "../Actions.aspx";
//If CTRL key was pressed
if (bCtrlPressed) {
parent.MainPage.location.href = URL + "?PackageId=00000000-0000-0000-0000-000000000000&All=" + bCtrlPressed;
}
else {
parent.MainPage.location.href = URL;
}
}
I need to stop the page being opened in a new tab. Please note, event.PreventDefault(); won't do the trick unfortunately.
I understand this is due to browser behaviour rather than the code.
Any suggestion is welcome. Regards!
Here is the most simpliest way for that, preventing click on url is much smarter then preventing pressing of CTRL/CMD buttons because functionality like CTRL/CMD + CLICK is browser functionality and cannot be overwritten (or at least I didn't have success with it)...
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
window.location.href = $(this).attr("href");
});
});
depend on case where you will use you need to apply something similar for form submiting... because that is also affected with this browser functionality
Important: OS X users using Command + Click, never forget that
Addition:
Because you want to disable open in new tab/window functionality under binding "click" just do preventDefaults for contextmenu (right mouse button)
$("a").contextmenu(function(e){
e.preventDefault();
});
Detect key of ctrl press or not .Use Jquery For event handling easly
var ctrl=false;
$(document).on('keydown',function(e){
console.log(e.ctrlKey)
}).on('click','a[href]',function(e){
if(!ctrl){
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
one
You need to add listener directly on anchor tag instead of using event delegation and adding on parent element. Working example here.
HTML
Click Me
JS:
$(document).ready(function ()
{
$("a").on('click',function(event)
{debugger;
event = event || window.event;
event.preventDefault();
event.stopPropagation();
return false;
});
});
In the content script of my Firefox Addon I have the following code:
window.addEventListener('click', function(event) {
event.preventDefault();
var t = event.target;
var nearestATag = t.nodeName === 'A'
? t
: findParentByTagName(t, 'A');
if (nearestATag !== undefined) {
self.port.emit('click-link', nearestATag.getAttribute('href'));
}
});
I want to prevent the URL from opening in the panel where the script is running and open it in the new browser's tab instead.
It works perfectly in case of a left mouse click, but doesn't work as expected in case of mousewheel click -- URL opens twice, so it seems that preventDefault doesn't do anything here.
Adding event.stopPropagation(); after event.stopPropagation(); works but I don't really understand why.
So can you help me understand why?
I know how to display an alert to the user if they attempt to navigate away from the current page asking them if they are sure they wish to do so but I was wondering if there is a way to display this alert ONLY when the window / tab is being closed?
I'd like to only have the confirmation display when the window or tab is being closed, not when the user clicks a link.
Not possible.
the only thing close is the onbeforeunload event, but there isn't a difference (to javascript) between a closed window/tab or a navigation to another page.
Follow-up:
I suppose you could attach a click handler to every anchor on the page and use a "dirty" flag, but that's really hack-ish. something like (forgive me, but using jquery for simplicity):
(function(){
var closingWindow = true;
$('a').on('click', function(){
if (this.href == /* on-domain link */){
closingWindow = false;
}
});
$(window).on('beforeunload',function(){
if (closingWindow){
// your alert
}
});
})();
but that's about as close as you're going to get. note: this isn't going to help if another javascript function uses window.location, etc.
You cannot differentiate between the two.
window.onbeforeunload is triggered immediately before the browser unloads its resources. You do not know the reason for the unload, only that it's about to occur:
From the MDN:
An event that fires when a window is about to unload its resources.
The document is still visible and the event is still cancelable.
How about doing something like this?
Have a global variable set to false (i.e. var hasCLickedLink = false;)
On all your links (<a>), attach an event handler that sets the variable to true
On onbeforeunload, check the value of the variable to see if a link has been clicked or not. If it is still false, then they haven't clicked a link so give them the alert.
You need to explicitly specify events for which you don't want to show confirmation dialogue box.
var validNavigation = 0;
function bindDOMEvents() {
// Attach the event keypress to exclude the F5 refresh
$(document).keydown(function(e)
{
var key = e.which || e.keyCode;
if (key == 116)
{
validNavigation = 1;
};
});
// Attach the event click for all links in the page
$("a").bind("click", function()
{
validNavigation = 1;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function()
{
validNavigation = 1;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function()
{
validNavigation = 1;
});
};
$(document).ready(function()
{
bindDOMEvents();
window.onbeforeunload = function () {
console.log(validNavigation);
if (validNavigation == '1')
{
console.log("No Alert.. Continue");
}
else
{
return false;
}
};
});
This solution worked for me in Firefox with Violentmonkey.
It is used like most of all window.onbeforeunload and check if left mouse button was pressed. So if pressed, this mean, click at free space or link opens - not closing tab.
function DetectBrowserExit()
{
if (butpres == 0) {
//your action before closing tab, alert not showing
}
}
window.onbeforeunload = function(){ DetectBrowserExit(); }
// the key is pressed, then when window.onbeforeunload - link is opening, so, tab not closing
document.addEventListener('mousedown',function(e){
if (e.which == 1) { //1-lbutton 2-mb 3-rb
//e.preventDefault();
butpres = 1
setTimeout(function() {
butpres = 0 //if after 3 seconds the script still works then the link has not been clicked, clear the click and continue to catch new clicks
//alert(butpres);
}, 3000); //Two seconds will elapse and Code will execute.
//alert(butpres);
//command_lock();
}
},false);
Here is demo: http://jsfiddle.net/qh7Sq/
I want to be able edit span inside link, actually I could by some part of preventing bubbling propagation blocks caret change action.
Please don't suggest different markup, only javascript.
I don't think there's going to be a nice way of doing this without making the whole link editable:
$('a').prop("contentEditable", "true");
Demo: http://jsfiddle.net/qh7Sq/1/
This is how i do it:
prevent click-default inside contenteditables
and for firefox, remove and add href-attribute to prevent placing the cursor at the start of the contenteditable-element
https://jsfiddle.net/e15j8oq9/1/
// if contenteditable inside a link
document.addEventListener('click', e=>{
if (e.button !== 0) return;
if (e.target.isContentEditable) {
e.preventDefault();
}
if (e.explicitOriginalTarget && e.explicitOriginalTarget.isContentEditable) { // keyboard click firefox
e.preventDefault();
}
});
// prevent (Firefox) placing cursor incorrectly
document.addEventListener('mousedown', e=>{
if (!e.target.isContentEditable) return;
var link = e.target.closest('a');
if (link) {
const href = link.getAttribute('href')
link.removeAttribute('href');
setTimeout(()=>link.setAttribute('href', href))
}
});
I have created a clickable div element that has a few links inside it. When I click anywhere on the div the page will go to the mail link but I want to be able to go to all the other links inside that div. I have managed to do this by calling the e.stopPropagation(); method. This works very good. You can see it in action here:
http://jsfiddle.net/nfZ3y/1/
The problem is, when hold the ctrl key and click on the link (to open it on a new tab), the link will not work and the page will go to the default link (instead of the one that I just clicked on). How can I achive all of the functionalities of the child links and add a default link for my div?
As people pointed out, it seems stopPropagation works differently in Firefox from the other browsers. My only suggestion is handling the click yourself:
$('.first').click(function (e) {
var title = $(this).children('.main-link');
var href = title.attr('href');
if ( e.ctrlKey )
window.open(href,"_blank");
else
window.location = href;
return false;
});
$('.first a').click(function (e) {
var title = $(this);
var href = title.attr('href');
if ( e.ctrlKey )
window.open(href,"_blank");
else
window.location = href;
return false;
});
Working example on jsFiddle.
Update: for less redundancy, substitute the first handler for this:
$('.first').click(function (e) {
$(this).children('.main-link').click();
return false;
});