I'm trying to implement a popup (bootstrap modal style) that would be triggered as web visitor leaves my site.
I tried different alternatives of:
$(window).bind('beforeunload', function(){
$("#sModal").modal('show');
return 'Take our survey before you leave.';
});
However, it didn't work in FF while worked fine in IE. I had another problem also, that the "Do you want to leave or stay" alert was being displayed on any link click on my website itself, across all browser types, as the whole page was being loaded.
I got around this by looping through all my anchor tags and adding a click listener to remove the beforeunload listener using:
window.onload = function () {
var allLinks = document.getElementsByTagName('a');
for (var i = 0; i < allLinks.length; i++) {
allLinks[i].addEventListener("click", removeBeforeUnload, false);
}
};
The removeBeforeUnload function just used the
$(window).unbind('beforeunload');
Getting back to actually make the popoup/modal appear on all browsers, i used the code from this stackoverflow answer after my document completes loading:
window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?
This solution works great across all browsers, however now I cannot unbind this event on any of my local clicked links! I tried everything
window.removeEventlistener('beforeunload',null,false);
window.removeEventlistener('onbeforeunload',null,false);
window.removeBeforeUnload();
window.onbeforeunload = null;
I hope you can point me in the right direction and explain why I cannot unbind this event, that I used from stackoverflow answer.Thanks!
One thought is use a global variable flag and don't do anything in the unload event handler when flag isn't truthy. Set this flag to null or false in link click handlers
Then you don't really need to remove the listener
var doUnload = true;
$('a').click(function(){
doUnload = false;
});
function unloadhandler(){
if(doUnload){
// show modal , return message etc
}else{
// do nothing , don't return anything
}
}
Probably jQuery is adding a 2nd beforeunload event listener, which you can't remove via the DOM API the same way as the one added to the Window by default.
What should work for you is:
var allLinks = $('a');
for (var i = 0; i < allLinks.length; i++) {
$(allLinks[i]).on('click', () => {
$(window).off('beforeunload');
// now add any custom code you want for handling this event
$("#sModal").modal('show');
)};
}
Related
I have a simple div that I dynamically append buttons to, now all the the button click events fire except for the last element in the list, which sometimes it does fire sometimes it doesn't. If I click on the left or right icon in the button it works just fine, if I click on the text or middle of the button sometimes it fires sometimes it doesn't.
<div id="btn-list"></div>
on page load after my dom is loaded I append a random number of buttons and I add the on click event listener to the buttons.
$( function () {
for (var i=0;i<arr.length;i++) {
var item = arr[i];
var btn = $(document.createElement('button'));
btn.text(item['description']);
btn.attr('id', i);
$("#btn-list").append(btn);
}
$('#btn-list').on('click', 'button', function (e) {
e.preventDefault();
e.stopPropagation();
window.location.replace('blah.html');
});
}
I'm using jQuery 2.0.
Without extra code, this snippet shouldn't fail. Have in mind that a reference to the last button added is kept in btn, thus if at some other part of the code the element or its events are modified it will alter the expected behavior.
Have you added some debug output to confirm the click event is not fired? http://jsfiddle.net/AstDerek/gKJNe/
$('#btn-list').on('click', 'button', function (e) {
e.preventDefault();
e.stopPropagation();
alert('blah.html');
})
Added a simple test, it doesn't fail at the browser I tested, maybe its limited to your browser? http://jsfiddle.net/AstDerek/gKJNe/1/
Now, what happens if you encapsulate the button creation into its own function?
function create_button (index,properties) {
var btn = $(document.createElement('button'));
btn.text(properties.description);
btn.attr('id',index);
$("#btn-list").append(btn);
return btn;
}
for (var i=0;i<arr.length;i++) {
create_button(i,arr[i]);
}
Finally, just as a workaround, why not add a hidden button as last step?
for (var i=0;i<arr.length;i++) {
create_button(i,arr[i]);
}
create_button(-1,{description:''}).hide();
okay, if I have six buttons in a list, under the li tag (each on is rel to a part of an array), how can I disable a button while it's doing it's thing? (In this case playing a video)I know it's a little vague (i haven't supplied code or anything of the sort), but that's because I don't know how to go about it. If I could at least get pointed in the right direction, that would be helpful, so that even if I can't figure it out, at least I can be specific with my problem... thanks...EDIT this is what I've now done
<li rel='1' id="first">
<div style="top:0px;">
<img src="graphics/filler.png" alt="" width="280" height="128" onClick="asess"/>
</div>
</li>
and then added the corresponding function
function asess() {
document.getElementById("first").disabled = true;
}
I'm not to concerned with adding the function back just yet, because first I'd like to make this part work.EDIT I've got this, which should work, but I guess it's not "talking" to the button?
$("li, .thumbs").bind("touchstart click", function() {
var $this = $(this);
if (!document.getElementById("first").disabled) {
document.getElementById("first").disabled = true }
else {document.getElementById("first").disabled = false};
});
I know it will only talk to the button with that id (first one) but as long as I can make it work for one, I can do the rest. So, what am I doing wrong?
Each button will have an onclick event handler. To prevent the onclick handler from doing anything the JavaScript method attached to the handler should return false. If you are doing this with jQuery return false; is the same as calling e.preventDefault (or event.preventDefault for IE).
When the normal event handler initiates the action associated with the button it should add the event handler that disables the onclick action.
You will probably need to apply a new CSS style to the button as well so the user knows it's disabled.
When the action completes you need to remove event handler that disables the onclick action and use the normal one again.
You could always just use a flag to say an action is in progress and set this on and off with the actions. If the flag is on then the event handler method returns false.
By using the event handler you could also show an alert to the user when they try and click the button before you return false.
EDIT:
Here is the sort of JavaScript you'll need, the first click starts the process which will stop itself after five seconds using setTimeout('stopAction()', 5000);. If you click the item again during that time you get the wait message.
I would recommend you look at using jQuery to develop a robust cross browser solution.
var inProgress = false;
function asess() {
if(inProgress) {
alert('Please wait ...');
return false;
} else {
startAction();
}
}
function startAction() {
inProgress = true;
alert('Starting');
document.getElementById("first").style.backgroundColor = '#333333';
setTimeout('stopAction()', 5000);
}
function stopAction() {
inProgress = false;
alert('Stopping');
document.getElementById("first").style.backgroundColor = '#FFFFFF';
}
document.getElementById("my_button").disabled = true;
and when you're done.
document.getElementById("my_button").disabled = false;
You could "disable" the element within the click handler and re-enable it when the callback is executed successfully.
Click handler binding to elements with disabled="disabled" attribute is not guaranteed to be consistently implemented across browsers (i.e. the event could/would still fire) and is not allowed except on form elements anyway. I'd just add class="disabled" which gives me additional powers to style the disabled element state by, say, greying it out.
Oh, and jQuery. Naturally, this logic could be reproduced in "normal" javascript but is so tidier with library usage, fiddle:
$('#my-button').click(function() {
var $this = $(this); //cache the reference
if (!$this.hasClass('disabled')) {
$this.addClass('disabled');
alert('hello world!');
setTimeout(function($btn) {
$btn.removeClass('disabled');
}, 5000, $this);
} else {
return false;
}
});
I want to disable all href links in my page. i am using the below code and it is working fine only in IE.
var elems = document.getElementsByTagName("*");
var len = elems.length;
for (i=0; i<len; i++) {
if(elems[i].tagName.toLowerCase() == 'a'){
elems[i].disabled = true;
}
}
but i want work it on all browsers.
can somebody please help me how to overcome this issue.
Thanks in advance.
If you don't want to change the href of the links, one could do this too:
window.onload = function() {
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].onclick = function() {return false;};
}
};
Working demo here: http://jsfiddle.net/jfriend00/9YkJQ/.
This is a very old thread but just in case someone else comes to this page, the disabled attribute can be set by using:
element.setAttribute('disabled', 'disabled');
This is recognized in all browsers and will disable the link. However, firing events on a disabled link is handled differently in different browsers & versions. FF & Chrome will still fire the onclick event where IE8+, not in compatibility mode, will not fire events. This is not necessary if there is no onclick event handler wired to the anchor, a normal href will not fire once the disabled attribute has been set. To stop the firing of the click event, the above code would work. The parens are not required and personally, I don't use them in this case as I assume parens are for grouping or for a function. Seems unnecessary in the solution provided before.
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 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.