How to show alert on browser back button click event using jquery - javascript

I want to show alert while clicking on the back button in the browser. it only works before clicking on the back button, when you click to somewhere else on the page, otherwise, it will go to the previous page without alert message.
I have added my code here. I want to go back when the page loads.
$(document).ready(function() {
if (window.history && window.history.pushState) {
//window.history.pushState('', null, './');
window.history.pushState(null, "", window.location.href);
$(window).on('popstate', function() {
alert('Warning! Your data will lose.');
document.location.href = 'www.redirecturl.com';
});
}
});
<html>
<head>
<title>Disable Browser Back Button Using JavaScript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js">
</script>
</head>
<body>
Click Here...
</body>
</html>
I am using JQuery here

You can achieve this using onbeforeunload event
using jquery
$(window).bind('beforeunload', function(){
myFunction();
return 'Are you sure you want to leave?';
});
function myFunction(){
// Write your business logic here
alert('Bye');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
Click here to go to w3schools.com
Using Javascript
window.onbeforeunload = s => "";
<body>
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
Click here to go to w3schools.com
</body>

Put It in your JS file and it will work .. when your press the browser back button it will alert you to leave or cancel.
$(window).bind('beforeunload', function(){
return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});

history.pushState(null, document.title, location.href);
window.addEventListener("popstate", function (event) {
$.confirm({
boxWidth: "30%",
title: "Alert",
model: true,
content: "The Changes made will be cleared",
buttons: {
Continue: function () {
history.back();
},
Cancel: function () {
history.pushState(null, document.title, location.href);
},
},
});
});

Related

How to assign default action to right click?

Don't know how to make it work, but I guess it's part of the learning process... Bellow is the code with two links, on that needs to be redirected, second one, regular... I want to make it that mouse actions on both links are identical (open on left click, open in new tab with middle click, properties on right click). Thank you all for your input.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a id="googlelink" href="https://www.google.com">Google</a>
<hr>
Google
<hr>
<script>
document.getElementById("googlelink").addEventListener("click", redirectToYahoo);
document.getElementById("googlelink").addEventListener("auxclick", redirectToYahooNewTab);
document.getElementById("googlelink").addEventListener("contextmenu", rightClick);
function redirectToYahoo() { // LEFT MOUSE CLICK
window.location.href = "https://www.yahoo.com";
}
function redirectToYahooNewTab() { // MIDDLE MOUSE CLICK
window.open('https://www.yahoo.com', '_blank');
}
function rightClick() { // RIGHT MOUSE CLICK
event.preventDefault();
};
</script>
</body>
Here is the snippet from #charlietfl that did the job.
var link = document.getElementById('googlelink');
link.addEventListener("auxclick",function(e){
if(e.button !==2){
window.open('https://www.yahoo.com', '_blank');
}else{
e.preventDefault()
}
});
link.addEventListener('click', function(e){
window.location.href = "https://www.yahoo.com";
});
link.addEventListener('contextmenu', function(e){
});
The problem is in your auxclick. Need to check which mouse button was used.
Not sure why you are using auxclick ... it has limited browser support.
A normal click listener won't trigger for right click. Also event name is contextmenu not oncontextmenu
var link = document.getElementById('test');
link.addEventListener("auxclick",function(e){
if(e.button !==2){
console.log('Aux normal');
e.preventDefault();
}else{
console.log('Aux right click')
}
});
link.addEventListener('click', function(e){
console.log('Normal click')// no log when right click
e.preventDefault() // just for demo
})
link.addEventListener('contextmenu', function(e){
console.log('Context menu')
e.preventDefault()
})
<a id="test" href="/questions">Stackoverflow Questions</a>
Not sure if this solves your auxclick issue, but it answers how to do the rightclick as per the title:
Change oncontextmenu to contextmenu. Then prevent the default event:
document.getElementById("googlelink").addEventListener("contextmenu", rightClick);
function rightClick() {
event.preventDefault();
alert("Right click disabled");
// do your stuff here
};
<button id="googlelink">googlelink</button>
I hope this can be helpful:
var link = document.getElementById("googlelink");
document.addEventListener('DOMContentLoaded', e => {
replace();
});
function replace() {
link.href = "https://www.yahoo.com";
}
<a id="googlelink" href="www.google.com"> GOOGLE LINK </a>

How to detect button value change in JQuery?

I've a sign up form which has submit button with value "GET INSTANT ACCESS!" :
<input type="submit" class="wf-button" name="submit" value="GET INSTANT ACCESS!">
After submit, the value gets change to 'Thank You!':
<input type="button" class="wf-button" value="Thank You!">
I need to detect the button value. If it becomes "Thanks You!" then I have to show a popup. And this value gets change by some Ajax (GetResponse form). There is no page refresh.
I've tried below code but it is only working in FireFox & not working in Chrome.
<script>
$(function() {
$(".modalbox").fancybox();
});
$(function() {
$('.wf-button').bind("DOMSubtreeModified",function(){
//if btn valu is 'Thank You! trigger popup'
$(".modalbox").trigger('click');
});
});
</script>
Live URL: http://www.idynbiz.com/web/html/gold_ira_vf/? (just to show how the button changes its value)
Can some one help how can I detect the button value and show my popup? The button change its value in real time (Ajax). There is not page refresh.
Is there any JQuery approach with bind() Or on() function to detect the value?
$(function() {
$('.btn1').on('change', function() {
alert('Do stuff...');
});
$('.lnk1').on('click', function() {
$('.btn1').val('Thank you!');
$('.btn1').trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" class="btn1" value="SUBSCRIBE" />
Change button value
OK ,
when button is clicked and form is submitted for saving. just write these code
$(document).ready(function ()
{
$('.wf-button').click(function ()
{
var valueofbutton = $(this).attr('value');
if(valueofbutton == 'Thank You!')
{
window.open(); //// whatever you want to open in popup
}
});
});
i m sure that this will work
You can use the following function in javascript which gets called after any > kind of postback, i.e. synchronous or asynchronous.
function pageLoad()
{
if($(".wf-button").val()=="Thank You!")
{
// show your popup
}
}
Hope it works....

block back button - ignore on click of button

I have a screen where I don't want the user to click on the back button. Now I am doing an ajax call to show that screen. There a button on it, when the click event is fired I want to redirect to the home page. Here its is.
$.post("<?php echo base_url();?>register/citizen", myobj2, function(data){
$("body").empty().append(data);
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";
window.onhashchange=function(){window.location.hash="no-back-button";}
window.onbeforeunload = function() {
return "If you leave this page you will have to register again.";
}
});
On the page that comes in I have
$(document).ready(function(){
$("#localfinal").unbind('click').on("click", function(){
//$().redirect('<?php //echo base_url();?>');
window.location(<?php echo base_url();?>);
});
});
When the user clicks the button, I get the message about leaving the page. Instead I just want to redirect to the base url (home);
Any ideas ?
Reset onbeforeunload handler, btw, i don't think you need to unbind() click handler:
$("#localfinal").on("click", function(){
window.onbeforeunload = $.noop;
window.location(<?php echo base_url();?>);
});
Try this
<SCRIPT type="text/javascript">
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
onpageshow="if (event.persisted) noBack();" onunload="">

Unable to get javascript to do button click from child iframe

I'm playing around with the Jquery UI dialog. I have a page with a gridview, a button that refreshes the gridview and a link. When you click a link, a dialog window popup up with the details of the record.
When I press save on the child page, I have the child page calling a javascript function from the parent page. In this function, it tried to do the button click event but it doesn't seem to be working.
If you look at the showThanks function below,
The alert works, the button text changes but the button click doesn't work.
Could this be a security feature? Both pages are on the same page right now.
hmm any clue?
Thanks
Edit - if you click the button manually, it changes the grid (in the button event handler). Yet, the jquery doesn't seem to be going in the button's event handler and the grid doesn't change.
Parent page html
<asp:GridView ID="gv" runat="server" />
<asp:Button ID="btnRefresh" runat="server" />
<a id="popoutUsers" href="popup.aspx?page=Bob" class="OpenNewLink">CLICK ME</a>
<script type="text/javascript">
$(function () {
$('.OpenNewLink').click(function () {
var url = $(this).attr('href');
var dialog = $('<div id="modal"></div>').appendTo('body')
$('<iframe id="site" src="' + url + '" />').dialog({
modal: true
, close: function (event, ui) {
// remove div with all data and events
dialog.remove();
}
});
return false;
});
showThanks = function () {
alert("Thanks");
var button = $("#btnRefresh");
button.val("hello"); //This works
button.click(); //Nothing seems to happen
// button.trigger("click"); (Tried trigger as well but no luck)
};
});
</script>
Child page
<div>
Why hello there
<asp:Button ID="btnBob" runat="server" Text="click me" />
</div>
<script type="text/javascript">
$(function () {
$('#btnBob').click(function (e) {
e.preventDefault();
window.parent.showThanks();
window.parent.$('.ui-dialog-content').filter(function () { return $(this).dialog('isOpen'); }).dialog('close');
return false;
});
});
</script>
So decided to do a new round of google searching and found this link Html Button that calls JQuery and does not post back
I changed my button to the following (added the UseSubmitBehavior)
and now it works. Hopefully I didn't waste people's time...

How to click a button through a shortcut with javascript without causing a page reload

I need some shortcuts in my web application, that will do the same as when a user clicks on a button, or presses the button with the accesskey.
I simplified my code to show you my problem:
<html>
<head><script src="jquery-1.4.2.js" type="text/javascript"></script></head>
<form>
<body>
<div id="myDiv">text</div>
<input name="cmdChangeText" type="submit" value="change text" onclick="document.getElementById('myDiv').innerText='text is changed'; return false;" />
<input name="cmdTestButton" type="submit" value="hello" onclick="alert('hello'); return false;" accesskey='z' />
</body>
</form>
<script type="text/javascript">
document.onkeydown = function() {
if (event.keyCode == 83) { //83 = 's'
window.$('[accesskey=z]').click();
}
}
</script>
</html>
The first button changes the text.
When you click the second button, or click it through accesskey (Alt + Z in IE), you get the alert, but the page does not reload: the text is still changed!
When I press some button, the S in this example, I do get the alert, but the page gets reloaded! Why is the return false; ignored this way, and what can I do about it?
I would get rid of the onclick="alert('hello'); return false" stuff and attach events using jQuery.
After that, you can try cancel the event bubbling:
$('#myInput2').click(
function() {
alert('hello')
return false
}
)
Just a hunch.
Give the buttons different names, in this example I have used 'test1' and 'test2' and add the following code.
$('input[name=test1]').click( function(e){
e.preventDefault();
$('#myDiv').innerText('text is changed');
});
$('input[name=test2]').click( function(e){
e.preventDefault();
alert('hello');
});
An input of type 'submit' will submit the page by default. Using 'preventDefault()' method on the event will, unsurprisingly prevent the default action. If you want the page to reload just remove this line.

Categories

Resources