For my project, I need to catch all the click outside the browser in Javascript. Is there a way to do that ? For example by asking the user the right access ?
I need a function like "onclick" that works even outside the browser.
There are various approaches for detecting when the focus moves out of the current page which would be a side effect of clicking outside the window if the window currently has focus.
Explicitly detecting clicks outside the page is not possible. It would be a security problem if a web page could monitor how the user interacts with other applications.
To detect click outside element with JavaScript, we can use the element’s contains method.
For instance, we write
const specifiedElement = document.getElementById("a");
document.addEventListener("click", (event) => {
const isClickInside = specifiedElement.contains(event.target);
if (!isClickInside) {
// ...
}
});
to select the element we want to check with getElemebntById.
Then we add a click listener for the whole page with document.addEventListener.
In the callback, we call specifiedElement.contains with event.target to check if we clicked inside the a element.
If it’s false, then we clicked outside of it.
javascript detect click outside of element
var ignoreClickOnMeElement = document.getElementById('someElementID');
document.addEventListener('click', function(event) {
var isClickInsideElement = ignoreClickOnMeElement.contains(event.target);
if (!isClickInsideElement) {
//Do something click is outside specified element
}
});
click outside javascript
// Vanilla js
var ignoreMe = document.getElementById("ignoreMe");
window.addEventListener('mouseup', function(event){
if (event.target != ignoreMe && event.target.parentNode != ignoreMe){
// Place your output
}
});
https://www.codegrepper.com/code-examples/javascript/javascript+detect+click+outside+of+element
Related
I'm trying to create a userscript that causes the native popup blocker to apply to all popups, even those that were the result of user interaction.
I came up with the following idea:
window.addEventListener('click', function(e) {
console.log(e.isTrusted);
if (e.isTrusted) {
e.stopImmediatePropagation();
e.preventDefault();
e.target.dispatchEvent(new e.constructor(e.type, e));
}
}, true);
button.addEventListener('click', function(e) {
window.open('about:blank');
});
<button id="button">Test</button>
(In the snippet window.open won't work because of the iframe sandbox.)
Basically the idea is to add an event listener to the page that replaces any click event that is trusted with a copy of it that isn't trusted. However this doesn't work and the popup is still opened.
Is there any way to accomplish this?
Relevant specification here:
https://html.spec.whatwg.org/multipage/interaction.html#triggered-by-user-activation
This just answers the X part of this XY problem, because I see no real use for the Y.
If you wish to block all popups, then window.open = null; will already block all the ones made from this method, then you may also want to block the ones from anchor elements,
document.addEventListener('click', e => {
if(e.target.nodeName === 'A' && e.target.target === "_blank") {
e.preventDefault();
}
});
Now, you'll have to apply this in all the documents (i.e in iframes too) and you should be good.
But note that there are many legit reasons for pages to open popup windows, and disabling it will definitely break a lot of websites.
The pop-blocker's handling of event contexts seems to be complex. Even generating a setTimeout with an evaluated string does not break the context. In Firefox there is a period of one second after a click to perform a popup, later it is cosidered not to be triggered by a click.
However, I could get Firefox to block popups using setInterval. I did not test it yet in Chrome.
We overwrite the window.open method with a custom one:
window.open = (function()
{
const
openArgs = [],
fnOpen = window.open.bind(window)
;
setInterval( () => { for(let args; args = openArgs.pop(); fnOpen(args)); }, 100);
return function open(...args) { openArgs.push(args); }
})();
<button onclick="window.open('http://example.com');">button</button>
open
I'm currently stuck at the following problem:
I need to create a delay when dragover happens en then check if current dragover object is still the same. When it's the same object -> execute code.
This is my code:
var draggedId = null;
var triggered = false;
function allowDrop(ev) {
draggedId = ev.target.id;
setTimeout(function () {
if (draggedId == ev.target.id && ev.target.id != "" && !triggered) {
triggered = true;
draggedId = "";
ev.preventDefault();
}
}, 2000);
}
function drop(ev) {
ev.preventDefault();
}
function dragLeave(ev) {
draggedId == "";
triggered = false;
}
Allowdrop function is the dragover event.
ev.preventDefault() to allow the drop can't happen there because that function is assync.
Any idea's?
Thanks,
Mathias
Can you explain more about what you are trying to achieve and I can answer more fully ?
It's generally the case that you cannot always say for certain whether a drop will work, the best you can do is to setup drop zones on your page and have them cancel the dragover event based on what you can tell about the drop. If you want to make your application work with cross window dragging, then you cannot rely on a global variable to store information about what is being dragged, and you cannot actually see what is inside the drag - you can only know what kind of thing is being dragged. So if the drop might be acceptable you need to cancel the event. See this question
I think that maybe you are confused about how dragevents propagate which is the reason you think you need a timeout ? But blocking the event queue to figure out whether you accept a drop, or trying to cancel the drag event after it has already bubbled to the top and been handled in the default way by the browser (which is to not accept the drop) isn't going to work.
I have a script that reloads an iframe whenever the browser screen is clicked (works perfectly). I was wondering how I would go about disabling the javascript from running on certain links?
Here is my current script:
document.onclick= function(event) {
if (event===tichack) event= window.event;
var target= 'target' in event? event.target : event.srcElement;
document.getElementById("tichack").src = "http://link.com?"+(+new Date());
};
Example would be something like this i suppose? (obviously incorrect) but will give you a better idea of what I am trying to achieve, did allot of searching but have had no luck?:
onclick="javascript:disabled=true;"
Basically, you need to identify what the target of your click is and, if the target is equal to one of the links you don't want triggering this, return from the function without refreshing the iframe.
var links = /* a collection of elements you don't want triggering the iframe refresh */,
count = links.length,
i;
for (i = 0; i < count; i += 1) {
if (target === links[i]) {
return;
}
}
There's two ways:
in the document.onclick, check the target element if it's a certain link, and then don't do anything. I.e. if (target.id == '...') { return; }
make sure that the click never arrives at the document.onclick. Because of how the DOM Event model works, if you cancel an onclick event at a low level (i.e. at a link itself) it will not bubble up and arrive at the document.onclick. So the following code works:
<a href='...' onclick='return false;'>click here!</a>
See http://bitovi.com/blog/2010/10/a-crash-course-in-how-dom-events-work.html for more information on the DOM Event model!
You can do this:
document.onclick = function (event) {
event = event || window.event;
if (event.target.id != 'tichack') return;
document.getElementById("tichack").src = "http://link.com?" + (+new Date());
};
Here, the document click event will work for the tichack link only.
SIMPLE DEMO HERE
I am created a page that warns the user when they click on the (close x) button on the window. I did some reading and discovered that JavaScript had a function called onbeforeonload which can take of the job I was trying to achieve. I however found at after my implementation that, when a user clicks on anything in my window (example: save and enter) The dialog box reappears. I was wondering how I could only target the specific X button in the window.
window.onbeforeunload = function (evt) {
var message = 'Do you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
Right now the function is being called globally... this resource might help you achieve what you are looking for: http://randomdrake.com/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/
This is a "working as intended" behavior for IE. Anchor tag clicks, regardless of whether they navigate or not, will trigger the onbeforeunload event.
This is the workaround I used - I am not sure whether it is the best approach or not:
document.onmouseup = function () {
if (window.event.srcElement.tagName === 'A') {
// turn off your onbeforeunload handler
...
// some small time later, turn it back on
setTimeout(..., 200);
}
};
I want to detect whenever someone clicks in a div (essentially I want to know when a user is interacting with a section of text on my site, be that by selecting some text or clicking on a link), but I don't want to interfere with what the user is doing.
If I put a onmousedown or onclick event on the div it ends up breaking selection, links, etc. Is there any way to catch these events without causing any interference ?
Onmousedown or onclick shouldn't interfere with anything as long as it doesn't return false;.
You can do this:
document.getElementById("spy-on-me").onmousedown = function () {
console.log("User moused down");
return true; // Not needed, as long as you don't return false
};
If you have other scripts that are attaching behaviour via this method on the page, then to prevent overriding them you can do:
var spyElement = document.getElementById("spy-on-me");
var oldMousedown = spyElement.onmousedown;
spyElement.onmousedown = function () {
console.log("User moused down");
if(oldMousedown) oldMousedown();
};
Yes, I suspect you are currently returning false at the end of the event binding, just don't do that or any of the things in this binding:
$('a').click(function(e) {
e.stopPropagation();
e.preventDefault();
return false;
});
If you do not do any of these three things, jQuery will not stop the event from bubbling up to the browser.
Edit: Sorry didn't realise it was a plain JavaScript question.
you can use do it by adding a event listener as well
var myNode= document.querySelector('.imagegrid');
myNode.addEventListener("click",function(e){
alert(e.target+" clicked");
});
A similar example is demonstrated here
Can't you simply add a click event to the div?
<div id="secretDiv" (click)="secretDivClick()">
then on your component:
secretDivClick() {
console.log('clicked');
}