First click is being ignored after page load - javascript

This webpage has a simple event listener, when I right click it blocks opening the context menu. simple enough.
But when I refresh the page or on initial load of the page, if I start with right mouse clicking the page, it shows the context menu, then blocks it ever time I right mouse click after that. I tried it in Chrome, FireFox and IE. Same results.
I experience the same thing with mouse down, keydown, or touch events, etc. It is like the first click is ignored. I am looking for JavaScript solution (not jquery). What am I missing?
<html>
<head>
<title>test</title>
<script type="text/javascript">
window.onload = function () {
window.addEventListener("contextmenu", mouseright);
}
function mouseright() {
document.oncontextmenu = function(e) {
var e = e || window.event;
alert("right");
e.preventDefault();
}
}
</script>
</head>
<body>
hello world
</body>
</html>
I even tried adding this before the event listener (as in this post keydown not detected until window is clicked), had no luck with document.onload and did see that it could be a possible browser focus on page load setting. Any thoughts or other ideas I didn't try in JavaScript?
if (document.hasFocus() == true) {
} else {
window.focus();
}

You're unnecessarily assigning the event twice (as both window.contextmenu and document.oncontextmenu). Removing the extra wrapper seems to work:
window.onload = function () {
window.addEventListener("contextmenu", mouseright);
}
function mouseright(e) {
var e = e || window.event;
alert("right");
e.preventDefault();
}
(The window.onload may also be unneeded, depending on where you place the addEventListener in the document.)

Related

How can I detect browser tab refresh or close using javascript [duplicate]

This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 7 years ago.
I have one problem, I have a javascript function which I want to use when the browser is closed, How can I detect that a browser is being closed?
I have made some research on that I got solution like onunload or beforeunload but both the functions are being executed when I am reloading the page, Is there any solution that I can differentiate reload and browser/tab close.
No, you can't know that, the HTML page isn't the "owner" of the browser, you have only limited access to information, and this info isn't inside it.
You can know when the user leaves your page, but you can't know why, as it's none of your business...
gdoron is correct in that you cannot determine why/how the user is 'leaving the page'.
On the extremes you can perhaps determine on mousedown events if the browser's CLOSE button was clicked and let that fire of an alert.
But this would probably require tracking the X and Y of the mousedown event and that isn't a very nice way of doing things. And i do not think you would be able to accurately determine if a tab is closed.
answer is,
</head>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
</head>
<body>
<h1>Eureka!</h1>
Google
Yahoo
</body>
</html>

How to access JavaScript href event that triggered beforeunload

I would like to access the event that caused a beforeunload event. Specifically, if I click on a link to another page, I would like to know what the link was in the beforeunload event handler.
In this way, I would be perform different actions in the beforeunload event handler according to what the URL was.
Eg 'http:' or 'https:' warn user about losing unsaved changes; 'mailto:' or 'skype:' don't warn user because page is not actually going to be unloaded.
I am trying to build a good solution to a problem like this:
mailto link (in chrome) is triggering window.onbeforeunload - can i prevent this?
I was all prepared to tell you this was impossible because the onbeforeunload event only reports to have been triggered by the window when you check out event.target, event.originaltarget, etc. If you override window.onclick, however, we can modify that method to register which element was last clicked on the page. Then, by providing code for window.onbeforeunload, we can specify new behavior that will check for the href of the element which was clicked last. Hooray, beer!
Here's code that will give you exactly the information you want though, in pure javascript and with no cruft to add inside your anchor tags. I've also thrown in the preventDefault() which will pop up the "This page is asking you to confirm that you want to leave - data you have entered may not be saved." confirm box. Hope this helps - you can figure out what to do from here.
<!DOCTYPE html>
<html lang="en">
<head>
<title>12065389</title>
<meta charset="utf-8">
<script type="text/javascript">
var last_clicked;
window.onclick = function(e) {
last_clicked = e.target;
return true;
}
window.onbeforeunload = function(e) {
var e = e || window.event;
if (last_clicked.href) {
alert(last_clicked.href);
e.preventDefault();
}
}
</script>
</head>
<body>
google
</body>
</html>
I would probably attach the event to all links on the page, rather than the beforeunload event.
Something like:
$("a").click(function(evt) {
if($(this).attr('href').indexOf('http') == 0) {
if(confirm("Are you sure?")) {
//continue
} else {
evt.preventDefault();
}
}
}

Closing a pop up window when it loses focus

I am wondering if it is possible to create a pop up window with javascript, and then close that window when it loses focus.
Here is my code:
var theWindow;
function launchWindow() {
theWindow=window.open('www.domain.com');
theWindow.onblur = function() {
this.close();
};
}
But that doesn't work at all. Any suggestions?
EDIT: I have discovered a solution that works for me, hopefully it will work for someone else:
var theWindow;
var windows = [];
function launchWindow() {
theWindow=window.open('www.domain.com');
windows.push(theWindow);
window.onfocus = function() {
for (x in windows) {
windows[x].close();
}
};
}
It's not an exact solution to my original problem (It doesn't close the window when it loses focus, but rather it closes it when the main window regains focus) but it works for me.
Is the URL of the popup window from the same domain as the parent? If not, you will likely not be able to attach an event to the new window's onblur event.
Run this from your browser console while viewing StackOverflow to see that it does in fact work when the popup is on the same domain as the originating window:
var theWindow = window.open ("http://www.stackoverflow.com","theWindow");
theWindow.onblur = function() { this.close(); };
window does not have the onblur event
Try to call it's closing by focusing on the <body> of the main window
The problem you may be having is that you are binding the onblur handler before the window has begun loading the page. Once the page is loaded, your onblur handler is gone. You'll need to defer binding long enough to give the page a chance to start loading before binding your event handler:
function launchWindow() {
var theWindow = window.open('www.domain.com');
setTimeout(function() {
theWindow.onblur = function() {
this.close();
};
}, 2000);
}
If you are loading a page in a different domain, you won't be able to bind the onblur handler at all. You'll need to stick to your solution using onfocus.

how to identify onbeforeunload was caused by clicking close button

How do I determine if onbeforeunload was caused by clicking the close button or a page refresh or generally what event caused onbeforeunload?
here is a snippet:
window.onbeforeunload = function( e ){
if( !e ) e = window.event;
// insert code to determine which is the source of the event
}
Please help me.
Referring to various articles and doing some trial and errors, finally developed this idea which works perfectly for me just the way i wanted it to happen. The logic was quiet simpler it implement as well The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the Close('X') button.
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
The ConfirmLeave function will give the pop up default message, it case there is any need to customize the message, return the text to be displayed instead of empty string
See if this helps, :)
As far as I know, there is no way of determining what caused the onbeforeunload. The event is triggered when window is about to close whether closing the browser or some other way.
If the close button was pressed the value of e.clientY is negative. For the other possible sources i doubt there is a solution.
window.onbeforeunload = function() {
var e = window.event;
alert(e.clientX + " / " + e.clientY);
}
I searched for something similar but ended up empty handed.
So I tried doing the opposit
We can identify all the events but browser events.
Refer below (Untested) snippet.
var target = $( e.target );
if(!target.is("a, :button, :submit, :input, .btn, .bulkFormButton")){
//Your code for browser events)
}
$("form").submit(function () {
//Your code for browser events)
});
This worked for me but there are still some events that are not handled.
I am in search of those.
If anyone have idea about them please share.

how to reverse e.preventDefault() from the body?

I have this:
function dontMove(event) {
// Prevent page from elastic scrolling
event.preventDefault();
}
&
<body ontouchmove="dontMove(event);">
This, on the ipad, stops it from being draggable and does not allow that grey background the ipad has when you drag a whole page around to show up.
I have seen on another website that its possible to reverse that in another div, so that div is completely draggable again.
Does anyone know how to reverse it?
I have also tried using this to prevent it (in the document.ready):
document.ontouchmove = function(e){
e.preventDefault();
}
& this to enable it:
function doTouchMove(state) {
document.ontouchmove = function(e){
return state;
}
}
Then I put this to activate it.
<img ontouchmove="doTouchMove(state);" src="../jpeg/pages/01.jpg" class="touch"/>
This didn't seem to work
Is there anything wrong with this?
Or any other way that might work?
This is exactly why bubbles is slightly better(at least in my opinion).
bubbles is cross browser, so you should be able to replace.
e.preventDefault()
with
e.bubbles = false;
and then latter in your code, you could potentially reset bubbles to true.
If the above isn't an option then just ignore. :D
An alternative(if you are just working with an iPad) is to just reverse how the DOM works.
document.addEventListener('click', function(){}, true );
This will force the event to work in the other direction.
Document click execute
|
|
v
Element click execute
try this post, HTML with event.preventDefault and erase ontouchmove from body tag.
Mine looks like this
<script>
// Get touch move enevt from IOS
document.ontouchmove = function (event) {
if (!event.elementIsEnabled)
event.preventDefault();
};
// Get touch move enevt from IOS
function enableOnTouchMove(event) {
event.elementIsEnabled = true;
};
</script>
then enable ontouchmove on every tag you want. ie:
<div ontouchmove="enableOnTouchMove(event)" id="listing">
I managed to solve it with
$('#form1').unbind('submit').submit();
You can solve it by preventing the event only if it comes from the body:
document.ontouchmove = function(event){
if(event.target.tagName == "BODY"){
event.preventDefault();
}
}

Categories

Resources