How to hide Bootstrap modal with javascript? - 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();

Related

stop/pause video when modal closes/hides

I know this has been asked and answered, but I'm not having any luck with any of the options that I've found. I'm trying to have the video stop playback or pause the video when the modal closes. One problem I'm having is the ability to target the close button. I've put console.logs in the functions I've tried and they weren't registering in the console at all. Thanks for any insights able to be offered.
<div id="myModal<%= index + 1 %>" data-id='<%= list.video_id %>'class="modal fade videoModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content bmd-modalContent" >
<div class="modal-body modal-header">
<div class="close-button">
<button id='single' type="button" class="close fancybox-close" data-dismiss="modal" aria-label='Close' ><span aria-hidden="true">×</span></button>
</div>
<div class='embed-responsive embed-responsive-16by9'>
<iframe id='player' class='embed-responsive-item' src="https://youtube.com/embed/<%= list.video_id %>?rel=0&enablejsapi=1" allowFullScreen='true' frameborder="0"></iframe>
</div>
</div>
</div>
</div>
</div>
EDIT:
Sorry, I'had tried so much jQuery that I didn't have any in my app.js folder at the time. Here is what I'm working with now.
$('[id^=myModal]').on('hidden.bs.modal', function(event) {
console.log(player);
event.target.stopVideo();
});
Update the question with more details
Its really hard to tell what is the problem because you only posted html. You having problem with locating close button and your console.log doesnt trigger. Obviously your javascripe file has some errors above your console.log line.
To detect if modal is closed you can use this EVENT
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
I would not change id of modals when generating them, instead I would put data-attr on this element to have one .on('hidden.bs.modal') and to have control over every modal
UPDATE:
from youtube-api docs https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player
It has been said that if you embed in your html iframe with the youtube video then in the moment u make something like this in js:
function onYouTubeIframeAPIReady(){
var iframe = document.getElementById("my-video");
video = new YT.Player(iframe);
}
you dont have to define attributes of Player that you create, it will take it from the iframe.
fiddle: http://jsfiddle.net/ux86c7t3/2/
Well, you can simply remove the src of the iframe and then put back again like; so the iframe stops running.
<iframe id="videosContainers" class="yvideo" src="https://www.youtube.com/embed/kjsdaf ?>" w></iframe>
<span onclick="stopVideo(this.getAttribute('vdoId'))" vdoId ="yvideo" id="CloseModalButton" data-dismiss="modal"></span>
now the Jquery part
function stopVideo(id){
var src = $j('iframe.'+id).attr('src');
$j('iframe.'+id).attr('src','');
$j('iframe.'+id).attr('src',src);
}

Why does my click function execute when page is ready?

I have a button and a a jQuery function like:
$('#cadastro-confirmar').click(function(){
...
});
<button id="cadastro-confirmar" class=" col-25 button-cadastro confirmar">Confirmar</button>
but everytime the page is ready the .click() is executed like a .ready(). But why?
EDIT:
As you asked for I'm posting more code.
The button id="cadastrar" triggers a .fadeIn() of a modal which the <button id="cadastro-confirmar" class=" col-25 button-cadastro confirmar">Confirmar</button> is inside, like so:
var modal = document.getElementById('myModal');
var abrir_cadastro = document.getElementById("cadastrar");
<div id="myModal" class="modal">
...
<button id="cadastro-confirmar" class=" col-25 button-cadastro confirmar">Confirmar</button>
</div>
The problem is that the .click of the id="cadastro-confirmar" (the button inside the modal) is, for some reason, executing his function without being clicked AND even without the modal being activated first.
There is no important thing besides this <button> inside de modal and there is not another button, div or anything that calls that same function that could actually explain this behavior.
You can use This Fiddle and the Chrome Development Tools to DEBUG understand.
Change your JS code like this
$('#cadastro-confirmar').on("click", function(){
...
});

Appended Element Inside show.bs.modal didn't Get Overwritten by .html at Bootstrap Modal

The situation is after I click button that will show modal, it will run an on click event that has 2 jquery inside:
.html to modal-body class
('show.bs.modal') event which contains .append to modal-body class
HTML(button)
<button class="btn btn-default view_detail" data-toggle = "modal" data-target="#transactionDetailModal">Detail</button>
Same HTML(Modal)
<!-- Modal -->
<div class="modal fade" id="transactionDetailModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Selling Report</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
$(document).ready(function(){
$('.view_detail').on('click',function(event){
$('.modal-body').html('<p>.html element</p>');
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('.modal-body').append('<p>.append element</p>');
});
});
});
What happened is if I click the button once, it seems working fine(This is result that I wanted) :
First click
But after that first click, the appended element keep appearing eventhough I think it will get overwritten by .html
Second click
And it keep increasing
Third click
What I want is that the .append to got overwritten everytime the modal button is clicked(Just like the first click picture). If I put the .append outside the ('show.bs.modal') it will run fine without showing the previously appended element over and over again everytime I click the button.
JS
$(document).ready(function(){
$('.view_detail').on('click',function(event){
$('.modal-body').html('<p>.html element</p>');
//I moved this one out from show bs modal below
$('.modal-body').append('<p>.append element</p>');
$('#transactionDetailModal').on('show.bs.modal', function (event) {
});
});
});
The JS code above fixed the keep appearing appended element problem.
But why did that happened? I thought for sure that the appended element will get overwritten cause everytime I click the button it will run .html which means that all the elements inside of modal-body class will get overwritten.
('show.bs.modal') event will be triggered every time when the modal is shown. The function(given below) you have written earlier will be executed separately every time when the modal is shown and the html function over writes the code separately.
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('.modal-body').append('<p>.append element</p>');
});
This function will be triggered separately and not in the click of the ('.view_detail') button.
The ('show.bs.modal') event can be removed.
$(document).ready(function(){
$('.view_detail').on('click',function(event){
$('.modal-body').html('<p>.html element</p>');
$('.modal-body').append('<p>.append element</p>');
});
});
});
OR you can trigger that in single function as given below :
$(document).ready(function(){
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('.modal-body').html('<p>.html element</p>');
$('.modal-body').append('<p>.append element</p>');
});
});
Use any one function to eliminate the issue.
What you could do is:
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('#transactionDetailModal p').length ? $('.modal-body').append('<p>.append element</p>') : return;
});
Check for existence of the element and then if it doesn't exist, append it.
BTW, where are you clicking? If you're clicking on the detail button, then the reason why the appending happens cumulatively is because you're literally just appending to the previous markup, that already had one p tag appended.
A more complete solution would be to use Bootstrap's own functionality and destroy the modal once it's closed:
$("#transactionDetailModal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null);
});

Bootstrap $('#myModal').modal('show') is not working

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.
Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>
Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<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>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>
Try This without paramater
$('#myModal').modal();
it should be worked
are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Please also make sure that the modal div is nested inside your <body> element.
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.
Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz
Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Display modal form before user leaves page

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.

Categories

Resources