Jquery Exit Popup meanwhile trigger a function - javascript

My goal is to trigger a pop up function meanwhile the user is going out from my website.
So I want to show a exit popup and in the background show my pop up at the same time.
I already have found different code on internet but no one works well.
Code :
<script type="text/javascript">
function PopUp() { return 'Do you wnat to leave my site?'; }
function UnPopIt() { /* no data */ }
$(document).ready(function() {
window.onbeforeunload = PopUp;
});
</script>
Is it possible to trigger a function like a pop up in the background ?
I am trying this code but it doesn't work :
function PopUp()
{
alert ('Do you wnat to leave my site?'); triggerpopup();
}

1,not very understand your needs,but i can't add a comment right now.
2,suppose you want a selfdefined pop(not another alert),then this goes well
function PopUp() {
triggerpopup();
return 'Do you?';
}
function triggerpopup() {
console.info('called with default pop')
}
$(document).ready(function() {
window.onbeforeunload = PopUp;
});

Related

JavaScript - close popup with back button

I have a custom popup functionality. What I want is for the browser back button to close this popup.
My ideal scenario would be to NOT show a hashtag in the URL bar.
I have tried putting window.history.pushState('forward', null, ''); in my showPopup() function and then doing the following:
$(window).on('popstate', function () {
closePopup();
});
This does work but the problem is when I manually close the popup I have to press the back button twice to navigate back to the previous page (obviously because a browser history entry was added when the popup was opened).
What is the best way of doing this? Can it be done without adding a browser history entry? Essentially what I am trying to do is replicate the behaviour of a mobile app. Press the back button in a mobile app will usually dismiss any open modals or context menus.
$('.popup-link').click(function() {
showPopup();
});
$('.popup-close').click(function() {
hidePopup();
});
function showPopup() {
$('.popup').addClass('active');
}
function hidePopup() {
$('.popup').removeClass('active');
}
.popup {
background-color: #ccc;
width: 300px;
height: 300px;
display: none;
}
.popup.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="popup-link">Click</button>
<div class="popup">
<button class="popup-close">x</button>
<!-- popup content here -->
</div>
It is not possible to do it without adding browser history entries since you cannot override the back button behaviour, see Intercepting call to the back button in my AJAX application: I don't want it to do anything
Sujumayas answer is a good option, you should introduce some additional variable though to avoid problems with the history when opening multiple popups (e.g. when clicking the button multiple times)
Here is some possible sample code:
let popupOpen = false;
$(".popup-link").click(function() {
showPopup();
});
$(".popup-close").click(function() {
window.history.back();
});
function showPopup() {
if (popupOpen) {
window.history.back();
}
popupOpen = true;
window.history.pushState("forward", null, "");
$(".popup").addClass("active");
}
function hidePopup() {
popupOpen = false;
$(".popup").removeClass("active");
}
$(window).on("popstate", function() {
hidePopup();
});
Additionally please note that you might have problems with Opera Mini: https://caniuse.com/#search=history
Altho I don't recommend to override regular browser history managment (back button) to use it as you please....
I think that the only thing you missed in your example is that the close button should not close the modal by itself, but instead just execute a backbutton event (which will eventually close the modal).
That simple fix and it will work as you wanted.
I am doing already something like this, and it works nicely with the browser back-button and by pushing the android back-button as well. I am also not showing a hashtag in the URL bar.
Here is the stub (I just tried to apply that to Your scenario):
function freezeHistory() {
window.history.pushState({}, window.document.title, window.location.href);
}
function goBack() {
/*
Custom history back actions: close panel, close popup, close drop-down menu
*/
var popupOpen = $(".popup.active").length > 0;
if(popupOpen) {
hidePopup();
return false;
}
window.history.back();
return true;
}
function showPopup() {
$('.popup').addClass('active');
freezeHistory();
}
function hidePopup() {
$('.popup').removeClass('active');
}
$(window).on("popstate", function(e) {
/*
Browsers tend to handle the popstate event differently on page load.
Chrome (prior to v34) and Safari always emit a popstate event on page load,
but Firefox doesn’t.
*/
goBack();
})
If this won't work for You out-of-the box, it is because IMHO You may need to clarify a little bit how do You expect to manage the page history. Feel free to add more detail to Your question if this isn't working as You'd expect now, but anyway, I strongly believe You got the idea and You are able to apply it inside the scenario of Your web-app.
Open popup and try going back and forth with the browser history buttons
$(document).ready(function () {
// manage popup state
var poped = false;
$('.popup-link').click(function () {
// prevent unwanted state changtes
if(!poped){
showPopup();
}
});
$('.popup-close').click(function () {
// prevent unwanted state changtes
if(poped){
hidePopup();
}
});
function showPopup() {
poped = true;
$('.popup').addClass('active');
// push a new state. Also note that this does not trigger onpopstate
window.history.pushState({'poped': poped}, null, '');
}
function hidePopup() {
poped = false;
// go back to previous state. Also note that this does not trigger onpopstate
history.back();
$('.popup').removeClass('active');
}
});
// triggers when browser history is changed via browser
window.onpopstate = function(event) {
// show/hide popup based on poped state
if(event.state && event.state.poped){
$('.popup').addClass('active');
} else {
$('.popup').removeClass('active');
}
};
.popup {
background-color: #ccc;
width: 300px;
height: 300px;
display: none;
}
.popup.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="popup-link">Click</button>
<div class="popup">
<button class="popup-close">x</button>
<!-- popup content here -->
</div>
You could add window.history.go(-2) to your popstate. That should take you back twice, which would be your original page before the modal as pushState added an entry to your history object.
Conversely, you could use history.back(2)
Use window.location.href to go 2 pages back and reload
Just run window.history.back(); when closing the popup.
$('.popup-close').click(function() {
hidePopup();
window.history.back();
});
You would have two options to implement this:
Option 1: Using the window.beforeunload event. reference
$('.popup-link').click(function() {
showPopup();
$(window).on("beforeunload", hidePopup);
});
$('.popup-close').click(hidePopup);
function hidePopup() {
$(window).off("beforeunload", hidePopup);
$('.popup').removeClass('active');
}
Demo
Option 2: Using the HTML5 History API. reference
$('.popup-link').click(function() {
showPopup();
window.history.pushState('popup-open', null, '');
$(window).on('popstate', hidePopup);
});
$('.popup-close').click(function() {
if(history.state == 'popup-open') {
window.history.back();
}
hidePopup();
});
function hidePopup() {
$(window).off('popstate', hidePopup);
$('.popup').removeClass('active');
}
Demo
Edit: sujumayas's idea is also pretty good one.
Demo
Further, I'ld recommend to register the popstate / beforeunload events only when necessary and unregister them, when you no longer need 'em in order to avoid overhead.
if anyone use bootstrap with any version you can use this
let popupOpen = false;
//show
$(".popup-link").on('click',(function() {
showPopup();
})
);
// hide
$(".popup-close").on('click',(function() {
window.history.back();
})
);
// on click back button
$(window).on("popstate", function() {
if (popupOpen) {
hidePopup();
}
});
// for bootstrap, if clicked outside the modal or close somehow
$(window).on('hidden.bs.modal', function(e) {
// Make sure is open and the same modal
if (e.target.id=='exampleModal' && popupOpen) {
popupOpen = false;
window.history.back();
}
});
function showPopup() {
// if open back
if (popupOpen) {
window.history.back();
}
popupOpen = true;
// push the browser history
window.history.pushState("forward", null, "#popup");
// you have to use the id
$("#exampleModal").modal('show');
}
function hidePopup() {
popupOpen = false
// you have to use the id to close the modal
$("#exampleModal").modal('hide');
}

how to unbind onbeforeunload event on javascript function call and page refresh

Please help me how to unbind onbeforeunload event on javascript function call .
Also I want to unbind onbeforeunload on page refresh.
Actually I want to give pop up alert on page exit .For this I have successfully unbinded onbeforeunload from form submit button and anchor tags. Kindly help me. The code I have used is
var jQuery = jQuery.noConflict();
jQuery(document).ready(function() {
jQuery(window).bind("onbeforeunload", function() {
return confirm("Do you really want to close?")
}
);
jQuery('a').on('click', function() {
jQuery(window).unbind('onbeforeunload')
});
jQuery("form").submit(function() {
jQuery(window).unbind('onbeforeunload')
});
});
Thanks
Do some minor change in your code, it will be work
jQuery(document).ready(function () {
window.onbeforeunload = function () {
return confirm("Do you really want to close?")
};
jQuery('a').on('click', function () {
jQuery(window).unbind('onbeforeunload')
});
jQuery("form").submit(function () {
jQuery(window).unbind('onbeforeunload')
});
});
Check this on jqfiddler, Message pop-up showing on refresh click here

setTimeout is not running only once

I want to hide signup popup and display login popup by clicking 'login' link on signup modal. Which is working fine BUT problem is that setTimeout is keep opening login popup after each 1 second whereas I want to have 1 second pause and simply execute it only once.
I've used clearTimeout(), it doesn't open login popup even one time.
Please guide me. Thanks in advance!
This is my script:
var Tid;
jQuery(document).ready(function ($) {
//trigger login link on signup popup
jQuery("#register-form #login-modal a").attr("href",
"javascript:void(0);");
jQuery("#register-form #login-modal").click(function () {
jQuery("#register-modal-wrap").find(".mfp-close").trigger("click");
openLoginModal();
});
function openLoginModal() {
Tid = setTimeout("jQuery('#login-modal a').trigger('click')", 1000);
//clearTimeout(Tid);
}
});
As #Thilo has pointed out that there is a recursive triggering of click event in your code which is causing the openLoginModal() function to be called, again and again, the only way to stop that is by making sure that openLoginModal() function is called only once. This should fix the issue.
var Tid;
jQuery(document).ready(function ($) {
//trigger login link on signup popup
jQuery("#register-form #login-modal a").attr("href",
"javascript:void(0);");
jQuery("#register-form #login-modal").click(function () {
jQuery("#register-modal-wrap").find(".mfp- close").trigger("click");
if (typeof Tid === 'undefined') {
Tid = setTimeout(openLoginModal, 1000);
}
});
function openLoginModal() {
clearTimeout(Tid);
jQuery('#login-modal a').trigger('click');
}
});

prevent function from running twice

I have a slideshow which runs automatically and you can skip to an image by clicking on a button.
It works fine if you click one of the buttons when the image is static, but if you click while the fade functions are running it will run the functions twice which creates some kind of loop which eventually grinds the browser to a stand still!
I know I need to add some kind of "isRunning" flag, but I don't know where.
Here's a link to a jsfiddle - http://jsfiddle.net/N6F55/8/
And code also below...
javascript:
$(document).ready(function() {
var images=new Array();
var locationToRevealCount=6;
var nextimage=2;
var t;
var doubleclick;
addIcons();
function addIcons() {
while (locationToRevealCount>0) {
$("#extraImageButtons").append('<img class="galleryButtons" src="http://www.steveszone.co.uk/images/button_sets/pink_square_button1n.png" alt="'+locationToRevealCount+'" />');
images[locationToRevealCount]='http://www.tombrennand.net/'+locationToRevealCount+'a.jpg';
locationToRevealCount--;
};
$('.homeLeadContent').prepend('<img class="backgroundImage" src="http://www.tombrennand.net/1a.jpg" />');
$("#extraImageButtons img.galleryButtons[alt*='1']").attr("src","http://www.steveszone.co.uk/images/button_sets/black_square_button1n.png");
runSlides();
}
function runSlides() {
clearTimeout(t);
t = setTimeout(doSlideshow,3000);
}
function doSlideshow() {
if($('.backgroundImage').length!=0)
$('.backgroundImage').fadeOut(500,function() {
$('.backgroundImage').remove();
slideshowFadeIn();
});
else
slideshowFadeIn();
}
function slideshowFadeIn() {
if(nextimage>=images.length)
nextimage=1;
$("#extraImageButtons img.galleryButtons").attr("src","http://www.steveszone.co.uk/images/button_sets/pink_square_button1n.png");
$("#extraImageButtons img.galleryButtons[alt*='"+nextimage+"']").attr("src","http://www.steveszone.co.uk/images/button_sets/black_square_button1n.png");
$('.homeLeadContent').prepend($('<img class="backgroundImage" src="'+images[nextimage]+'" style="display:none;">').fadeIn(500,function() {
nextimage++;
runSlides();
}));
}
$("#extraImageButtons img.galleryButtons").live('click', function() {
nextimage=$(this).attr("alt");
$("#extraImageButtons img.galleryButtons").attr("src","http://www.steveszone.co.uk/images/button_sets/pink_square_button1n.png");
$(this).attr("src","http://www.steveszone.co.uk/images/button_sets/black_square_button1n.png");
clearTimeout(t);
doSlideshow();
});
});
html:
<div class="homeLeadContent" style="width:965px;">
</div>
<div id="extraImageButtons"></div>
Two changes make it work better for me:
Down in the "extra image buttons" handler, you call "clearInterval()" but that should be changed to "clearTimeout()".
I added another call to "clearTimeout(t)" in the "runSlides()" function right before it sets up another timeout.
Clicking on the big "CLICK ME" button might still do weird things.
edit — well here is my fork of the original jsfiddle and I think it's doing the right thing. In addition to calling "clearTimeout()" properly, I also changed the code in "doSlideshow()" so that it empties out the content <div> before adding another image.

Using Jquery calling different functions with a singe link

I would like to use single a href link to call different functions .
On first click it should call first_function() and on second click it should call second_function. Like toggling between two functions using same link. Suggest the best way to be done.
Jquery Code :
$(function() {
var IntervalId;
function first_function() {
//code goes here
};
function second_function(){
//code goes here
}
$("#link2").click((function(){
second_function();
}));
$("#link1").click((function(){
first_function();
}));
});
Html Code :
Call function2
Call function1
"Like toggling between two functions using same link."
$("#link1").toggle(
function first_function() {
// Code goes here
},
function second_function(){
// Code goes here
}
);
From the jQuery docs on toggle(fn1, fn2, [fn3, [fn4, [...]]]):
Toggle among two or more function calls every other click.
Javascript:
$(document).ready(function() {
function first_function() {
// Code goes here
};
function second_function(){
// Code goes here
}
$("#link").toggle(first_function, second_function);
});
HTML:
<!-- I'm pretty sure that <a> isn't the right tag for this. -->
<button id="link">Toggle between the two functions.</button>
the easiest way would be
var performFirstAction = true;
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").click(function(){
if(performFirstAction) {
first_function(); performFirstAction = false; }
else {
second_function(); performFirstAction = true; }
});
});
or using toggle as Tomalak mention and well,
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").toggle(
first_function,
second_function
);
});

Categories

Resources