Trigger event on click outside page - javascript

Is possible trigger an event if user click outside page? More specifically, in the browser title bar or tab bar?
Try this my jsFiddle example.
HTML
<div id="box">
<div id="menu">Click here</div>
<div id="show">Hello!</div>
</div>
JS
jQuery('div#menu').on('click', function(ev) {
jQuery('div#show').addClass('visible').css({
top: ev.clientY,
left: ev.clientX
});
return false;
});
jQuery(document).click(function() {
jQuery('div#show').removeClass('visible');
});
jQuery(window).blur(function() {
jQuery(document).click();
});
TESTS
First you click in "Click here" button. So...
Try to click in some document part: Ok
Try to click in some page part or unfocus browser window: Ok
Try to click in some other opened tab in your browser: Ok
Try to click in browser title bar or tab title: Fail
SO...
It's possible I solve this problem?
TEST RESULTS
Chrome: fail on last;
Firefox: fail on last;
IE10: fail on last;
Opera: fail on last;

I'm sorry to tell you this, but this isn't possible.
Reason? Well essentially, clicking the title bar/tab bar of a window doesn't actually make an element lose focus.
Try this example here:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onblur
You'll notice that clicking the title bar/tab bar doesn't make the textbox lose focus at all, which is the root of the issue.
I don't think this is a big deal for your project though. As far as the user's concerned, it'll look great as it currently is.

Related

Capture any prompt event with javascript?

From MDN:
Dialog boxes are modal windows — they prevent the user from accessing
the rest of the program's interface until the dialog box is closed.
I tried to capture the event when a dialog box appear on the screen using window.confirm
but it seems it doesn't exist on the window level.
My question:
Is there any way to mimic the click when a dialog box appears on screen?
The above code listen and print all the events made on the page, but when I click on the button nothing printed, and when I click "ok" or "cancel" it print "FocusEvent" - I guess that this is the focus on the clicked button.
document.querySelectorAll('button')[0].addEventListener('click', function(){
window.confirm('confirmation box','click');
});
for (var key in window) {
if (key.search('on') === 0) {
document.querySelectorAll('ol')[0].innerHTML += '<li>'+key.slice(2)+'</li>';
window.addEventListener(key.slice(2), function() {
document.querySelectorAll('ol')[1].innerHTML += '<li>'+key.slice(2)+'-'+this.event+'</li>';
document.querySelectorAll('ol')[1].scrollTop = document.querySelectorAll('ol')[1].scrollHeight;
});
};
};
<button>open dialog</button>
<ol style="display: none;"></ol>
<ol style="height: 200px; overflow-y: scroll"></ol>
This confirm box seems on higher level from the window(??)
I did search a lot online but the best (and only) clues lead to 404 pages:
DOMWillOpenModalDialog
DOMModalDialogClosed
Is it possible?

OnUnload Alert Error "NS_ERROR_NOT_AVAILABLE"

<html>
<body>
<button type="button" onclick="clickme()">Click Me</button>
<script>
var test = 0;
function clickme() {
test = 1;
console.log(test);
}
window.onunload = function() {
alert("test");
}
</script>
</body>
</html>
I'm using this simple code to test some things with onunload and onbeforeunload. For some reason whenever I refresh/leave the page and cause the onunload event I get no alert and an error in the Firebug console. If I use onbeforeunload this works and I get no error, but I hear onbeforeunload isn't very good cross-browser.
NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111
(NS_ERROR_NOT_AVAILABLE) [nsIDOMWindow.alert]
alert("test");
I am not trying to alert the test variable, just the text "test" before anyone tries to point that out.
If you want that to work, it will have to be in the onbeforeunload event, but instead of creating an alert/confirm pop-up, the onbeforeunload event has a built in pop-up. All you have to do is return a string and the pop-up will appear when the user tries to navigate away from the page. If there is no return variable, there will be no pop-up.
The great thing with this is that the pop-up message has 2 buttons: OK and Cancel.
If the user hits OK, the browser will continue to navigate away from the page
If the user hits Cancel, the browser will cancel the unload and will stay on the current page
The onbeforeunload event is the only pop-up that can cancel the onunload event
An example is below:
<script type="text/javascript">
window.onbeforeunload=before;
window.onunload=after;
function before(evt)
{
return "This will appear in the dialog box along with some other default text";
//If the return statement was not here, other code could be executed silently (with no pop-up)
}
function after(evt)
{
//This event fires too fast for the application to execute before the browser unloads
}
</script>
It seems like you are trying to do an alert in the onunload event. The issue here is that it's too late. The page is already unloading and there is no stopping it. You may be able to get an alert message to show, but it doesn't matter what the user clicks because the page is already unloading.
Your best bet is to go with the onbeforeunload event.

Popstate with Hashtags?

I have a site that uses AJAX to dynamically load content into a div.
The links to do so are anchors with href="#" and an onclick event to trigger the AJAX.
This leaves me without a history when I click back, so if I load one page, then another and click back, it does nothing.
A basic version of the code is this:
<script type="text/javascript">
function loadXMLDoc(url)
{
<!-- Load XML Script here. -->
}
</script>
</head>
<body>
<div id="myDiv">
<!-- Target div. -->
</div>
Click Me.
Click Me.
Click Me.
</body>
What I would like to know is, can I give each link a different "#" and then use a popstate handler to call the appropriate event, so if I click link 1, 2 and then 3 and then start hitting the back button, it'll go back to 2 and then 1 etc..
I was going to use history.js and start using pushstate in the loadXML script but I think the whole manipulating history thing is a bit dirty and unreliable.
Am I thinking on the right lines or is there a better way?
Currently all my links just use "#" so that it pops back to the top of the page when loading more content but I'd like to be able to go back if possible.
Any help would be great.
Browser saves hashtags to history properly. Just add hashtag #1 to this question page, hit enter, change it to #2, hit enter, change it to #3, hit enter. Now click back button, and you'll see hash changes from #3 to #2. I recommend to change only hash itself on link click and react on page hash change and page load events.
function react() {
var hash = window.location.hash.replace("#", "");
loadXMLDoc(hash + ".txt");
};
document.body.onload = function() {
react();
window.onhashchange = react;
};
Click me
Click me
Click me
Please note that onhashchange event does not supported by old IE. The only way to deal with it if you want is to define timer with setInterval and check hashes equality.
Try to use combination of LocalStorage and HistoryAPI.
When you load XMLDoc store it in LocatStorage, when back is pressed - load data from storage, not from web.
A bit code above.
/* Handling history.back added */
window.onpopstate = function(event) {
yourHandleBackFunction(event.state);
};
function yourHandleBackFunction(renderTs) {
/*Check TS and load from localStorage if needed*/
};

Support Middle Clicks on my Fancybox Lightbox

Suppose you have a lightbox, and you want to allow the user to middle-click, which would open a new tab, and the same content that shows-up in the lightbox on left-click is now on a standlone page (complete with header, sidebar, etc).
Anybody have a snippet or technique handy they can share?
Otherwise the technique I was going to try first was just to add a conventional href to the link, then add a click handler that cancels the default action on left click. I think this'll work but I'm not sure so honestly it was easier to pound out a question than to write it up and test it in the 14 browser/os combinations I have to support.
I finally found time to work this out and it was pretty easy:
This is how I made it work using jQuery & FancyBox:
Give your desired link a 'has-overlay' class and give it a custom attribute that will tell it what it should load in the overlay
Login
Be sure you have the overlay code available (this is standard FancyBox stuff)
<div class="hidden" id="loginform"> <!-- Form Goes Here --> </div>
And put this snippet in your on ready event:
$('.has-overlay').bind('click', function(e) {
var overlay = $(this).attr('overlay');
$('').fancybox().trigger('click');
return false;
})
When a user left-clicks, this 'click' handler will be called. It will load the overlay and then return 'false' so the browser won't follow the href in the link.
When a user middle-clicks or right-clicks, the click handler doesn't fire, and it works as a normal link would.

Alerts when navigating away from a web page

When I try to close my Google docs tab with unsaved changes, this is what I get in my browser (FF 3.5).
Are you sure you want to navigate away
from this page?
You have unsaved changes in this
document. Click Cancel now, then
'Save' to save them. Click OK now to
discard them.
Press OK to continue, or Cancel to
stay on the current page.
My question is whether such alerts are part of the web app (gdocs for eg.) or are they given out by the browser? If latter, how is this done?
By the browser. It's the beforeunload event handler that returns the customized text of the dialog, which is only the middle of the three paragraphs - the other two paragraphs as well as the text of the buttons cannot be customized or otherwise changed.
window.onbeforeunload = function(){ return 'Testing...' }
// OR
var unloadListener = function(){ return 'Testing...' };
window.addEventListener('beforeunload', unloadListener);
Will yield a dialog that says
Are you sure you want to navigate away from this page?
Testing...
Press OK to continue, or Cancel to stay on the current page.
You can nullify this by setting the handler to null
window.onbeforeunload = null;
// OR
window.removeEventListener('beforeunload', unloadListener);
The alerts are part of the web application. View the source code and look at the javascript.

Categories