Display modal form before user leaves page - javascript

I've used window.onbeforeunload to display a custom message when a user attempts to leave a site.
Example:
window.onbeforeunload = function(){
if(some_condition){
return "Are you sure you want to navigate away from this page?\nAll unsaved changes will be lost.";
}
};
+--------------------------------------------------------+
| Are you sure you want to navigate away from this page? |
| All unsaved changes will be lost. |
| |
| [ Yes ] [ Cancel ] |
+--------------------------------------------------------+
However, I'd like to enhance this a bit. If possible, I'd like to use a custom modal form instead of the generic popup.
Is there a way to do this?

Binding to a html has worked very well for me instead of unload. The reason is well explained in another answer here.
$("html").bind("mouseleave", function () {
$('#emailSignupModal').modal(); \\or any modal
$("html").unbind("mouseleave");
});
If you want to show the modal only once in a day or on any other particular condition match then you can use cookies.

The unload event will fire when a user tries to navigate away. However, if you use a DIV as a pop-up the browser will navigate away before the user has a chance to read it.
To keep them there you'd have to use a alert/prompt/confirm dialog boxes. (as far as I know)

Is there a way to do this?
Nope.
You are stuck with the prompt the browser gives you.

another alternative I see sites use for this functionality is creating an action when the user scrolls off the page like when they scroll to the address bar like this site does http://www.diamondcandles.com/ this can be done using mouseleave event on the body element. For example:
$( document ).ready(function() {
$("body").bind("mouseenter",function(){
/* optional */
}).bind("mouseleave",function(){
if(!$.cookie('promo_popup')) {
/* do somthing (ex. init modal) */
/* set cookie so this does not repeat */
$.cookie('promo_popup', '1', { path: '/' });
}
});
});

If they click the back button or something similar, I believe the alert/prompt/confirm boxes are your only option.
However, you can probably listen for specific keypress events, like ctrl/cmd + w/r, and interrupt those with a dialog.

Hey this will help you to show a popup model or window when a user leaving your website.
Before using this code please try Run code snippet
<!DOCTYPE html>
<html lang="en">
<head>
<title>show popup when user leaves website</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Show popup when user leaves your website</h2>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Hey! wait for free __________</h4>
</div>
<div class="modal-body">
<p>Get this code for free</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("html").bind("mouseleave", function () {
$('#myModal').modal();
$("html").unbind("mouseleave");
});
});
</script>
</body>
</html>

var confirmOnPageExit = function (e) {
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = "Are you sure you want to navigate away from this page? All unsaved changes will be lost.";
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
window.onbeforeunload = confirmOnPageExit;

I've just had to do this for a project.
I set rel="external" on all external links then used JS/Jquery to detect if the link has this attribute, and if it does - prevent the default behavior and instead fire a modal.
$('a').on('click', function(e){
// Grab the url to pump into the modal 'continue' button.
var thisHref = $(this).attr('href');
// Grab the attr so we can check if its external
var attr = $(this).attr('rel');
// Check if link has rel="external"
if (typeof attr !== typeof undefined && attr !== false) {
// prevent link from actually working first.
e.preventDefault();
// insert code for firing your modal here!
// get the link and put it in your modal's 'continue button'
$('.your-continue-button').attr('href', thisHref);
}
});
Hope this helps.

Related

How to make click only on modal exterior and not on dialog/content?

So I'm making an extension for Google Chrome with my friend, and for most of the features (i.e. calendar, settings, etc.) we open a modal so we don't have to redirect to another page. We are trying to get the modal to close when you click outside of the content. Here's a little markup screenshot to give you an idea of what I'm talking about.
I want to be able to close the modal by clicking outside the white area. Currently it closes even when I click inside the white area. I have tried pretty much everything, including stopPropagation(), pointer-events:none;, and jquery disabling. None of them work for reasons unknown to me. Something weird about Chrome Extensions, I guess.
Here's some of my code so far:
function calendar() {
document.getElementById("calendmodal").style.display = "block";
}
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("calendicon").addEventListener("click", calendar);
document.getElementById("calendmodal").addEventListener("click", closeModal);
document.getElementById("calendmodal").addEventListener("click", function(event) {
event.stopPropagation();
});
});
And HTML:
<div class="icons" id="icons_calendar">
<img src='https://preview.ibb.co/jE76Bm/calendar.png' alt="calendar" border="0" id="calendicon"/>
</div>
<div id=calendmodal class="generalmodal">
<div class="modal-content" id="calendcontent">
<iframe src="https://calendar.google.com/calendar/embed?src=googleapps.wrdsb.ca_ptpdj55efmhg1nb89ruc15fi3k%40group.calendar.google.com&ctz=America%2FToronto" style="border: 0" width="800" height="600" frameborder="0" scrolling="no" visibility="hidden" id="calendiframe"></iframe>
<p id=infostuff>For a more extensive calendar and<br>more school tools, visit The SJAM Website.</p>
</div>
</div>
Not really sure what I'm doing wrong, I don't know how to do this in an extension.
I don't know exactly how you show your modal dialog, but my approach for this issue is like this (you may be able to adapt it ot your particular case):
I have a transparent <div> as container that takes up the whole screen, and inside it, using CSS, I position the modal dialog. Something like:
<div id="container" style="position:fixed;top:0;bottom:0;left:0;right:0;display:none">
<div id="myModal" style="position:absolute;width:300px;height:200px;left:100px;top:100px">
<!-- Here goes my content -->
</div>
</div>
With this approach, to display the dialog I do something like:
function openModal(){
document.getElementById("container").style.display = "block";
}
And to close it when clicked on the transparent background but not on the dialog I have:
document.getElementById("container").onclick = function(event) {
if (event.target === this) {
this.style.display = "none";
}
};
In your earlier attempts, where did you execute event.stopPropagation()? It's not included in your code example.
What you need to do is prevent a click event on #calendmodal from bubbling up the DOM and triggering a click event on the body (or another container element) whose event handler closes your modal dialog.
You can do so like this:
document.getElementById("calendmodal").addEventListener("click", function(event) {
event.stopPropagation();
});

javascript click event not working in div onclick

I have this div in my page that is showing X at top of modal, I like to by clicking this user redirect to homepage. I tried this but the even is not firing at all.
<div class="modal-content">
<div class="close" onclick="redirecttologin()">x</div>
......
</div
this is java script but even the alert is not showing
function redirecttologin() {
alert("test");
document.location.href = "/";
};
I am sure that it has the reference to java script file as other things are working in page.
*problem was class="close".
Your code should work properly, the only issue is that you should use window.location instead of document.location. They are both the same, but as documentation says, the document.location is read only property.
Also notice, that your closing <div> tag is missing >. That might be a problem as well.
function redirecttologin() {
alert("test");
window.location.href = "/";
};
<div class="modal-content">
<div class="close" onclick="redirecttologin()">x</div>
</div>
You must use
window.location.href = "/"

How to make both href and jquery click event work

I have a reporting function answerCardInnerLinkReportingCall which gets invoked on click on <a> tag inside a specific div. I use event.preventDefault(); to override the default click behavior.
Currently I am redirecting the user to the target url in the reporting function after sending all the reporting parameters using window.open('http://stackoverflow.com/', '_blank'); method.
jQuery(document).on('click','#answerCard a', function(event) {
event.preventDefault();
answerCardInnerLinkReportingCall(this);
});
If I use onclick function in the tag I would have returned true and it would make href work without me redirecting the user manually but is it possible to do the same in click handler? I can't use onclick since I dont have control over the html data.
I wanted to check if there is a better way of implementing this?
Edit1: Adding sample HTML
<div class="answer" style="display: block;">
<div class="well">
<div id="answerCard" answercardid="check_phone_acard">
<h3 id="answerTitle">check your phone</h3>
<div><ol class="answerSteps"><li>Go to <a title="Link opens in a new window" href="https://test.com" target="_blank">Check phone</a>. If prompted, log in.</li></ol></div>
<label id="seeMoreAnswer">Displaying 1 of 1 steps. </label></div>
<!-- Utility Section -->
<div class="util">
<span class="pull-left"><a id="viewFull" href="/test.jsp?sid=52345">View full article ?</a></span>
<span class="pull-right">
</div>
</div>
</div>
</div>
I guess you dont need to use any 'event.preventDefault();' if you want to use links native functionality after the script executed.
try like this
jQuery(document).on('click','#answerCard a', function(event) {
//event.preventDefault();
alert('script running');
answerCardInnerLinkReportingCall(this);
});
also created JS Fiddle. check it out.
You can use javascript's:
window.location.href = 'http://url.here.com';
To tell the browser to navigate to a page. Hope it helps.
Other way can be of returning true or false from answerCardInnerLinkReportingCall and depending on that call or dont call event.PreventDefault();
Try something like this:
$('#answerCard a').click(function(event) {
var loc = $(this).attr('href');
event.preventDefault();
answerCardInnerLinkReportingCall(loc, this);
});
function answerCardInnerLinkReportingCall(loc, that){
// your code to do stuff here
window.open(loc, '_blank');
}
See this demo fiddle

How to hide Bootstrap modal with javascript?

I've read the posts here, the Bootstrap site, and Googled like mad - but can't find what I'm sure is an easy answer...
I have a Bootstrap modal that I open from a link_to helper like this:
<%= link_to "New Contact", new_contact_path, {remote: true, 'data-toggle' => 'modal', 'data-target' => "#myModal", class: "btn btn-primary"} %>
In my ContactsController.create action, I have code that creates Contact then passes off to create.js.erb. In create.js.erb, I have some error handling code (a mix of ruby and javascript). If everything goes well, I want to close the modal.
This is where I'm having trouble. I can't seem to dismiss the modal when all goes well.
I've tried $('#myModal').modal('hide'); and this has no effect. I've also tried $('#myModal').hide(); which causes the modal to dismiss but leaves the backdrop.
Any guidance on how to close the modal and/or dismiss the backdrop from within create.js.erb?
Edit
Here's the markup for myModal:
<div class="modal hide" id="myModal" >
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Add Contact</h3>
<div id="errors_notification">
</div>
</div>
<div class="modal-body">
<%= form_for :contact, url: contacts_path, remote: true do |f| %>
<%= f.text_field :first_name, placeholder: "first name" %>
<%= f.text_field :last_name, placeholder: "last name" %>
<br>
<%= f.submit "Save", name: 'save', class: "btn btn-primary" %>
<a class="close btn" data-dismiss="modal">Cancel</a>
<% end %>
</div>
<div class="modal-footer">
</div>
</div>
With the modal open in the browser window, use the browser's console to try
$('#myModal').modal('hide');
If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.
If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?
Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.
to close bootstrap modal you can pass 'hide' as option to modal method as follow
$('#modal').modal('hide');
Please take a look at working fiddle here
bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation
If non of the above method work, give a id to your close button and trigger click on close button.
The Best form to hide and show a modal with bootstrap it's
// SHOW
$('#ModalForm').modal('show');
// HIDE
$('#ModalForm').modal('hide');
I use Bootstrap 3.4
For me this does not work
$('#myModal').modal('hide')
In desperation,I did this:
$('#myModal').hide();
$('.modal-backdrop').hide();
Maybe it's not elegant, but it works
I was experiencing with that same error and this line of code really helps me.
$("[data-dismiss=modal]").trigger({ type: "click" });
I found the correct solution you can use this code
$('.close').click();
$('#modal').modal('hide');
//hide the modal
$('body').removeClass('modal-open');
//modal-open class is added on body so it has to be removed
$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class
I ran into what I believe was a similar issue. The $('#myModal').modal('hide'); is likely running through that function and hits the line
if (!this.isShown || e.isDefaultPrevented()) return
The issue is that the value isShown may be undefined even if the modal is displayed and the value should be true. I've modified the bootstrap code slightly to the following
if (!(typeof this.isShown == 'undefined') && (!this.isShown || e.isDefaultPrevented())) return
This seemed to resolve the issue for the most part. If the backdrop still remains you could always add a call to manually remove it after the hide call $('.modal-backdrop').remove();. Not ideal at all but does work.
(Referring to Bootstrap 3), To hide the modal use: $('#modal').modal('hide'). But the reason the backdrop hung around (for me) was because I was destroying the DOM for the modal before 'hide' finished.
To resolve this, I chained the hidden event with the DOM removal. In my case: this.render()
var $modal = $('#modal');
//when hidden
$modal.on('hidden.bs.modal', function(e) {
return this.render(); //DOM destroyer
});
$modal.modal('hide'); //start hiding
I had better luck making the call after the "shown" callback occurred:
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
This ensured the modal was done loading before the hide() call was made.
What we found was that there was just a slight delay between the call to our server code and the return to the success call back. If we wrapped the call to the server in the $("#myModal").on('hidden.bs.modal', function (e) handler and then called the $("#myModal").modal("hide"); method, the browser would hide the modal and then invoke the server side code.
Again, not elegant but functional.
function myFunc(){
$("#myModal").on('hidden.bs.modal', function (e) {
// Invoke your server side code here.
});
$("#myModal").modal("hide");
};
As you can see, when myFunc is invoked, it will hide the modal and then invoke the server side code.
Hiding modal backdrop works but then any subsequent opening of the modal and the backdrop doesn't hide like it should. I found this works consistently:
// SHOW
$('#myModal').modal('show')
$('.modal-backdrop').show();
// HIDE
$('#myModal').modal('hide');
$('.modal-backdrop').hide();
I used this simple code:
$("#MyModal .close").click();
I was experiencing the same problem, and after a bit of experimentation I found a solution. In my click handler, I needed to stop the event from bubbling up, like so:
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Here is the doc:
http://getbootstrap.com/javascript/#modals-methods
Here is the method:
$('#myModal').modal('hide')
If you need to open several times the modal with different content, I suggest to add (in you main js):
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
So you will clean the content for the next opening and avoid a kind of caching
$('.modal-backdrop').hide(); // for black background
$('body').removeClass('modal-open'); // For scroll run
$('#modal').modal('hide');
$('#modal').modal('hide'); and its variants did not work for me unless I had data-dismiss="modal" as an attribute on the Cancel button. Like you, my needs were to possibly close / possibly-not close based on some additional logic so clicking a link with data-dismiss="modal" outright would not do. I ended up having a hidden button with data-dismiss="modal" that I could programmatically invoke the click handler from, so
<a id="hidden-cancel" class="hide" data-dismiss="modal"></a>
<a class="close btn">Cancel</a>
and then inside the click handlers for cancel when you need to close the modal you can have
$('#hidden-cancel').click();
Even I have the same kind of issues. This helped me a lot
$("[data-dismiss=modal]").trigger({ type: "click" });
We need to take care of event bubbling. Need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
I realize this is an old question, but I found that none of these were really what I was looking for exactly. It seems to be caused by trying to close the modal before it's finished showing.
My solution was based on #schoonie23's answer but I had to change a few things.
First, I declared a global variable at the top of my script:
<script>
var closeModal = false;
...Other Code...
Then in my modal code:
$('#myModal').on('show.bs.modal', function (event) {
...Some Code...
if (someReasonToHideModal) {
closeModal = true;
return;
}
...Other Code...
Then this: (Note the name 'shown.bs.modal' indicating that the modal has shown completely as opposed to 'show' that triggers when the show event is called. (I originally tried just 'shown' but it did not work.)
$('#myModal').on('shown.bs.modal', function (event) {
if (closeEditModal) {
$('#myModal').modal('hide');
closeModal = false;
}
});
Hope this saves someone the extra research some day. I spent a bit looking for a solution before I came up with this.
In my case I was apparently trying to close the dialog too fast after showing it. So in my close modal function I used this:
setTimeout(() => {
$('#loadingModal').modal('hide');
}, 300);
document.getElementById('closeButton').click(); // add a data-dismiss="modal" attribute to an element in the modal and give it this id
I used this code -
Hide modal with smooth effect using Fade Out.
$('#myModal').fadeOut();
$('.modal-backdrop').fadeOut();
$('.modal-open').css({'overflow': 'visible'});
If you're using the close class in your modals, the following will work. Depending on your use case, I generally recommend filtering to only the visible modal if there are more than one modals with the close class.
$('.close:visible').click();
I was facing a similar problem where my custom modal would show via js but I could not hide it (there was no close button).
For me the solution was to add the content into a modal-dialog.
<div class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="loading">
<div class="modal-dialog">
loading
</div>
</div>
Without the modal-dialog it would happily show the modal, but it was impossible to hide it without the manual solutions in some of the answers here, some of which prevent you then being able to show the modal again.
This is the bad practice but you can use this technique to close modal by calling close button in javascript.
This will close modal after 3 seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
window.onload=function()
{
setInterval(function(){
$("#closemodal").click();
}, 3000);
}
</script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="closemodal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Some times
$('#myModal').modal('hide');
$('#myModal').hide();
does not get the job done so you need to add this to footer of your modal:
<button type="button" id="close_cred_modal" class="btn btn-secondary" data-dismiss="modal">Close</button>
and than add this line to close the modal
$('#close_cred_modal').click();

multiple external link buttons with jquery simpleModal box

I learned how to pass the argument with a simpler javascript confirm box, but now I'm working with this SimpleModal script, and I'm a bit lost.
I have a page with several buttons that will link to different external pages. When I click any button, the confirm box will pop up and when user clicks ok, then they are taken to that specific external link. Right now, it's hard coded for one link, but I'm not sure how to set the link for each button.
The link is currently set on this line:
window.location.href = 'https://www.sandbox.paypal.com/xxx';
The function:
$(document).ready(function () {
$('#confirm-dialog input.confirm, #confirm-dialog a.confirm').click(function (e) {
e.preventDefault();
// example of calling the confirm function
// you must use a callback function to perform the "yes" action
confirm("<h3 class='register'>Please read and understand the Terms of these lessons before purchasing...this is important.<br /><br />By purchasing these lessons, you agree that:</h2><ul class='popup'><li class='lessonslist'><img class='imgpad' src='/images/bullet.png' alt='bullet' />You may reteach any material you have learned here, but you may NOT use the materials provided in the lessons to do so. In other words, you can do the lessons, learn the material, and teach your friend. You CAN NOT print out the transcriptions or download the videos and give them to a friend.</li><li class='lessonslist'><img class='imgpad' src='/images/bullet.png' alt='bullet' />Derivative works are ok to produce, but you can not directly copy the musical examples and profit off them without the written consent of Joel Laviolette.</li></ul>", function () {
window.location.href = 'https://www.sandbox.paypal.com/xxx';
});
});
});
function confirm(message, callback) {
$('#confirm').modal({
closeHTML:"<a href='#' title='Close' class='modal-close'>x</a>",
position: ["20%",],
overlayId:'confirm-overlay',
containerId:'confirm-container',
onShow: function (dialog) {
$('.message', dialog.data[0]).append(message);
// if the user clicks "yes"
$('.yes', dialog.data[0]).click(function () {
// call the callback
if ($.isFunction(callback)) {
callback.apply();
}
// close the dialog
$.modal.close();
});
}
});
}
html:
<div id='confirm-dialog'><h2>Confirm Override</h2>
<p>A modal dialog override of the JavaScript confirm function. Demonstrates the use of <code>onShow</code> as well as how to display a modal dialog confirmation instead of the default JavaScript confirm dialog.</p>
<input type='button' name='confirm' class='confirm' value='Demo'/>
</form>
</div>
<div id='confirm'>
<div class='header'><span>Confirm</span></div>
<p class='message'></p>
<div class='buttons'>
<div class='no simplemodal-close'>No</div><div class='yes'>OK
</div>
</div>
</div>
There is also the jquery.simplemodal.js which is probably too big to post here.
So... you want to attach confirm popup for every link?
${"selector that returns all external links").click(function(e){
e.preventDefault();
confirm("Do you want to leave?", function () {
window.location.href = (e.target).attr('href');
});
});
${"selector that returns all external links")
Is not a real selector. You need to write correct one inside ${} in order to find buttons you are looking for.
Simple ready to run sample (save in html file and open) =>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type='text/javascript' src='http://www.ericmmartin.com/wordpress/wp-content/themes/emm-v3/scripts/jquery.simplemodal.js?ver=1.3.3'></script>
</head>
<body>
<a class="external-link" href="http://www.google.com">google</a>
<a class="external-link" href="http://www.bing.com">bing</a>
<a class="external-link" href="http://www.yahoo.com">yahoo</a>
<div id='modal' style='display: none; background: Silver;'>
<a href="#" class='simplemodal-close' id='yes'>leave</a>
<a href="#" class='simplemodal-close' id='no'>don't leave</a>
</div>
<script type='text/javascript'>
$(".external-link").click(function(e){ //on external link click
e.preventDefault(); //cancel immediate redirect of link
$("#modal") //selecting modal window div
.data('href', $(this).attr('href')) //saving href to modal window itself
.modal(); //showing modal window
});
$("#yes").click(function(){window.location=$("#modal").data('href')}); //if user clicks yes, redirect
</script>
</body>
</html>

Categories

Resources