have a href as follows:
<a class="eLink" href="http:www.abc.com">chk here xyz</a></li>
and javascript for "eLink" is as follows:
$("a.eLink").click(function link(evt) {
url = evt.target.href;
if (url.toString().toLowerCase().indexOf(".gov") <= 0) {
var tk = "Do you really want to continue?";
if (confirm(tk)) {
window.open(url, 'newwin');
}else{
window.open(url,'_self');
}
}
else
{ window.open(url, 'newwin'); }
return false;
});
});
Now my issue is when i click the href and click 'cancel' in the confirm button, my page goes to "abc.com", but it shouldnt happen. My browser should remain the same. what script should i use in the else part so i remain the same page. thanks.
Just take the else out.
if (confirm(tk)) {
window.open(url, 'newwin');
}
Sidenote, IE8 and lower doesn't implement the indexOf function so you may want to patch it by writing your own implementation.
the default action should already be prevented by return false; (jQuery style)
the problem is that if you click cancel window.open(url,'_self'); is executed, just remove the else part of the confirm condition
check this fiddle
You have:
var tk = "Do you really want to continue?";
if (confirm(tk)) {
window.open(url, 'newwin');
}else{
window.open(url,'_self');
}
This means that if they click cancel, False will be returned, which will still open the link. You need to remove window.open in your else statement
if (confirm(tk)) {
window.open(url, 'newwin');
}
Related
I have made a JavaScript function which is attached to the cancel button on of a form. The issue I am finding is that when the cancel button is pressed the page/form reloads losing the data in the text fields.
function cancelConfirm(){
var confirmCancel = confirm("Are you sure you wish to cancel?");
if(confirmCancel==true)
{
alert("byebye");
}
else
{
return false;
}
};
I was just wondering how can you prevent the page from reloading after the cancel button on the confirm has been clicked? Thanks for any help you can give
you can just use a simple way
Delete
function cancelConfirm() {
var confirmCancel = confirm("Are you sure you wish to cancel?");
if (confirmCancel == true) {
alert("byebye");
return false;// to stop postback on ok cick of confirmation popup
}
else {
return false;
}
}
What you can do is to add an onClick event and pass the event object down to it.
{onClick(e) => {
e.preventDefault();
//do something here
}}
A simple e.preventDefault() is what you need.
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave the page. All data will be lost!';
if (typeof evt === 'undefined') {
evt = window.event;
}
if (evt && !($("#a_exit").click)) {
evt.returnValue = message;
}
return message;
};
I want user to leave the page clicking to the link (has id ="a_exit") only. In other circumstances such as refreshing the page, clicking another link, user will be prompted that if he/she wants to leave the page. I have tried to use the code above. It still asks me if I want to go away when I click the exit link.
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works for me
My quick example of the conditional prompt before leaving page:
window.onbeforeunload = confirmExit;
function confirmExit(event) {
var messageText = tinymce.get('mMessageBody').getContent();
messageText = messageText.trim();
// ... whatever you want
if (messageText != "")
return true;
else
return void (0);
};
It works under Chrome, FF.
You can return null when you do not want the prompt to show. Tested on Chrome 79.
window.onbeforeunload = () => {
if(shouldPrompt){
return true
}else{
return null
}
}
BTW modern browser no longer support custom onBeforeUnload promp text.
It will always prompt you if you want to leave the page. It's a security issue and cannot be worked-around.
Moreover, anything you return in the onbeforeunload event handler that is not void will be treated as the message for the prompt. Refer to this article: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
This worked for me.
window.onbeforeunload = function(){
if(someBoolean) {
return 'message'
}else{
window.onbeforeunload = null;
}
}
You could just remove window.onbeforeunload in the click handler.
How about a variable to decide, if the link was clicked?
var exitClicked = false;
$("#a_exit").click(function() {
exitClicked = true;
});
window.onbeforeunload = function(evt) {
//...
if(evt && !exitClicked) {
evt.returnValue = message;
}
//...
};
You only set exitClicked = true when the link was really clicked and afterwards, before unloading you can simply check this variable.
This is quite old but I wanted just to change the code given that .live is no longer working in Jquery. So, the updated version would be:
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').on("click", function(){
$(window).unbind('beforeunload');
});
I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code
function unloadPage(){
return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;
This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it.
But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way.
Is there a way to catch the refresh or browser cosing so that can use it.
Note that in your code, you're using onbeforeclose, but the event name is beforeunload, so property is onbeforeunload, not onbeforeclose.
I just want to work this code only for browser refreshing and closing. Is there a way to catch the refresh or browser cosing so that can use it.
No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload handler not to return a string, or removing your onbeforeunload handler (probably the flag is cleaner).
For example:
var warnBeforeClose = true;
function unloadPage(){
if (warnBeforeClose) {
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn
warnBeforeClose = false;
// ...but if we're still on the page a second later, set the flag again
setTimeout(function() {
warnBeforeClose = true;
}, 1000);
}
Or without setTimeout (but still with a timeout):
var warningSuppressionTime = 0;
function unloadPage(){
if (+new Date() - warningSuppressionTime > 1000) { // More than a second
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn for the next second
warningSuppressionTime = +new Date();
}
Update in 2017: Also note that as of at least a couple of years ago, browsers don't show the message you return; they just use the fact you returned something other than null as a flag to show their own, built-in message instead.
One of the simple solutions to your problem is to have a flag and then call your function only if the flag is valid. In this case , you can bind the anchor tags, F5 key and form submit button click to events that set the flag as false. So your alert bar will be visible only if the above cases don't happen :)
Here's the script:
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
alert("bye");
}
function wireUpEvents() {
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();
});
Check this link
It gives you information on how to handle onbeforeunload event.
The idea is to have a global flag on the page. When any change is done to the fields, this flag is set to true. When clicked on save button, then this flag needs to be set to false.
In the onbeforeunload event, check whether the flag is true, then show the message accordingly.
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (needToConfirm)
{
// check on the elements whether any change has been done on the fields.
// If any change has been done, then set message here.
}
}
function saveClicked()
{
needToConfirm = false;
}
DEMO
(Run or refresh the fiddle to see the alert onbeforeunload() event message and click on the link "kk" ,it wont show onbeforeunload() event message. Try it in your webpage)
I have a solution for you, you don have to add onclick event to each tags and all.
Just add this to any where on your pages .
<input type="hidden" value="true" id="chk"/>
and add this code to your document head tag
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(document.getElementById("chk").value=="true")
{
return "Your changes will not be saved.";
}
}
document.onclick = myClickHandler;
function myClickHandler() {
document.getElementById("chk").value="false";
}
<script>
Hope this helps
Thank you
In my application when user logs out the browser is closed. And on browser close I am throwing an alert. Now what I want is if I directly close the browser window alert should come but if window is closed through logout alert should not come as I have shown another confirm message of logout.
function closeEditorWarning(){
for (var i=0;i<childWindow.length;i++) {
if (childWindow[i] && !childWindow[i].closed) childWindow[i].close();
if(i==0) {
alert("This will close all open e-App applications");
}
}
window.close();
}
window.onbeforeunload = closeEditorWarning;
And this is my logout code
$('#'+id).click(function(event){
event.preventDefault();
$('#centerContent').load('<%=request.getContextPath()%>/'+target);
});
} else {
$('#'+id).click(function(event){
event.preventDefault();
var r=confirm("logout");
if (r==true)
{
flag=true;
for (var i=0;i<childWindow.length;i++) {
if (childWindow[i] && !childWindow[i].closed) childWindow[i].close();
}
window.close();
} else { }
});
}
Use a flag. Set the flag when log OFF is clicked.
Check the flag before showing the alert
set a hidden field with user logon status and on close check:
if($('#isUserLogIn').text()=='true')
{
//show alert
}
var showPop = true;
function exitIt(){
if (showPop){
showPop = false;
return 'blah blah';
}
}
This is a little exit pop up. If the user chooses to "stay on the page", I need it to redirect to the proper URL. How can I do this?
Just because you can implement something, doesn't mean that you should. Exit popups are arguably the most annoying thing ever!
or document.location = "http://www.example.com/";
if (confirm('Move to another page?')){
window.location = "http://blah.com/";
}
$("a#myleavinglink").click(function() {
var answer = confirm("Are you sure you should leave? Its so sweet thougH!");
if (answer) {
return true;
} else {
return false;
}
}
You could also do a very similar thing with jQuery and if the user decides to leave the page, or back up, or type in their own address.
BTW, by returning true from a click function in jQuery will allow standard operations, but returning false will override the standard functionality and only provide the functionality you have choosen. Hence, if the user wants to leave, it returns true, else it returns false
$("a").live("click", function() {
var id = $(this).attr("id");
if (id == approvedClicks) {
return true;
} else {
return false;
}
});
that would prevent any links being clicked to be removed, whether at page load, or added in with JS.