I need to put up a pop up. It will be updated daily, so the pop up needs to show every day on page load if a user comes to the website, (new users and even users that have visited before) but if the user clicks the notice away, it needs to stay hidden for 24 hours, before resetting. I've written this code but can't get it to compare itself with the last time it was shown, using localStorage.
var modal = document.querySelector(".opening-modal");
var close = document.getElementById("pageDiv");
var element = document.getElementById("pageDiv");
function popupShown() {
if (!localStorage.getItem('showPopup')) { //check if popup has already been shown, if not then proceed
localStorage.setItem('showPopup', 'true'); // Set the flag in localStorage
element.classList.add("show-modal");
}
}
function closeModal() {
element.classList.add("hide-modal");
}
window.setTimeout(popupShown, 1500);
window.addEventListener("click", closeModal);
I'd give each modal an ID (ascending) and store the ID of the last modal the user dismissed. That way, if the modal doesn't change for 48 hours instead of 24, the user isn't shown the modal again.
var popupId = 42; // This is the number that changes when the content changes
if (+localStorage.dismissedPopup !== popupId) {
// Either the user has never dismissed one of these, or it's not the most recent one
window.setTimeout(popupShown, 1500);
}
function closeModal() {
element.classList.add("hide-modal");
// Remember the ID of the most recent modal the user dismissed
localStorage.dismissedPopup = popupId;
}
If you want to drive this from the HTML, the ID can come from a data-* attribute:
<div id="pageDiv" data-popup-id="42">An important update about...</div>
Then:
var popupId = +element.getAttribute("data-popup-id");
But if you want it to be time-based, store the time it was last dismissed:
if (!localStorage.lastPopupDismissed ||
(Date.now() - localStorage.lastPopupDismissed) > (24 * 60 * 60 * 1000))) {
window.setTimeout(popupShown, 1500);
}
function closeModal() {
element.classList.add("hide-modal");
// Remember the ID of the most recent modal the user dismissed
localStorage.lastPopupDismissed = Date.now();
}
Related
hi i have to disable forgot password button for 30 secs soon after the user has clicked it once & an alert should show him to 'Please try again after 30 seconds' This is to avoid multiple trigger of mails providing user a temporary password. after 30 secs the button should be enabled again
I have tried using setTimeout to disable button for 30 seconds after click.. i am confused on how to use it. Please help me on this
<button>
<a id="forgotPassword" class="cursorPointer loginlables">
Forgot Password?
</a>
</button>
User should be able to click forgot password button once and then error message should display if he tries to click button again within 30 seconds of first click.
You can set up a global variable which holds the time the user clicked the button and an action - like sending a reminder - has been initiated. Everytime you enter the callback for the button's click handler, you compare this time to the current time and if it's difference is smaller than 30 seconds show an alert dialog.
Javascript provides the Date object for time and date operations.
var lastCall = 0;
var timeToWait = 30;
function doAction() {
var timePassed = Date.now() - lastCall;
if (timePassed >= timeToWait * 1000) {
console.log("send email");
lastCall = Date.now();
} else {
alert("Please wait " + parseInt(timeToWait - (timePassed / 1000)) + " seconds");
}
}
document.getElementById("forgotPassword").addEventListener("click", doAction);
<button id="forgotPassword">
Forgot password
</button>
You can achieve this by setTimeout Function
document.getElementById("forgotPassword").addEventListener('click', function(){
alert("Button is disabled for 30sec")
document.getElementById("forgotPassword").disabled = true;
setTimeout(function(){document.getElementById("forgotPassword").disabled = false;},30000);
})
in your future posts, please add your code so we can help you better.
First of all, I've always been told using setTimeout isn't a good habit in JS, so keep in mind my solution probably isn't the best available, but that's one.
function myfunction() {
btn = document.getElementById('btn');
if (btn.innerHTML === 'Click me') {
console.log('Clicked !')
btn.innerHTML = 'Wait a bit plz';
setTimeout(() => {
btn.innerHTML = 'Click me';
}, 5000);
}
}
<button id='btn' onclick='myfunction()'>Click me</button>
Here i'm using the text of my button to decide if it can be clicked or not, but you can create a boolean or use a class, as you wish.
The idea still is the same, check if your button is clickable, if it is, make it unclickable for a given period (wich you can achieve by using setTimeout(() => {}, 5000);.
if(localStorage.getItem('popState') != 'shown'){
$(function () {
$('[data-toggle="popover"]').popover({
content : "....."
});
$('[data-toggle="popover"]').popover('show');
});
localStorage.setItem('popState','shown')
}
I am using the method above to display popup message to user during page load, and disable the popup message to be displayed after load for second time. How can i make it auto pop out to the user after certain period of time? e.g. after user close the popup message then it will be displayed automatically after an hour.
You can use an interval for this:
const showPopup = function showPopup() {
const lastShown = localStorage.getItem('popStateLastShown');
const hasOneHourPassed = lastShown ?
(Math.abs(new Date(lastShown) - new Date()) / 36e5) >= 1 :
false;
if (hasOneHourPassed || localStorage.getItem('popState') !== 'shown') {
// Show popup
localStorage.setItem('popState', 'shown');
localStorage.setItem('popStateLastShown', new Date());
}
};
// Run code immediately.
showPopup();
// Check again after an hour.
setInterval(showPopup, 36e5);
I'm creating a popup that will show when the user scrolls. However when the user clicks on the close button and refreshes the page and scrolls, I need to make a popup to show up after 10 minutes.
var popUp= document.getElementById("popup");
var closePopUp= document.getElementsByClassName('popup-close');
var halfScreen= document.body.offsetHeight/2;
var showOnce = true;
//show when scroll
window.onscroll = function(ev) {
if ((window.innerHeight+window.scrollY) >= halfScreen && showOnce) {
if(popUp.className === "hide"){
popUp.className = "";
}
showOnce = false;
}
};
//close button
for(var i = 0; i<closePopUp.length; i++){
closePopUp[i].addEventListener('click', function(event) {
if(popUp.className === ""){
popUp.className = "hide";
}
});
}
First you should detect whether the user has refreshed the page.You can achieve this using navigator object.Refer this question for implementation.
Secondly, once the user refreshes the page all the variables gets destroyed and initialized again.Hence you must use cookies or server side sessions to store whether user has already closed it once.But I always recommend you to setup sessions since cookies can be disabled by users.
To sum it up,setup an ajax request once the user refreshes the page,and if already he has closed the popup once, start a timeout for 10 minutes.
Adding a sample prototype for this :
var refreshed = false;
if (performance.navigation.type == 1) {
console.info( "This page is reloaded" );
refreshed = true;
} else {
console.info( "This page is not reloaded");
refreshed = false;
}
if(refreshed) {
//implement this ajax function yourself.
ajax('path/to/yourserver','method','data',function(response) {
if(response == "showed") {
var time = 10 * 60 * 1000;//10 minutes.
setTimeout(function() {
//show your popup.
},time);
}else {
//immediately show once scrolled.
}
});
}
You should use cookie for this and set cookie expiration time for 10 minutes take a look at this cookie plugin hope it helps
Set a cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
Get a cookie
alert( $.cookie("example") );
Delete the cookie
$.removeCookie("example");
Or there is an example which is given in this answer take a look at this also
I have a menu where I want the state open/close state to persist if the page reloads and when the user has clicked to be closed or open.
I'm using a cookie plugin and I'm almost there but I'm having trouble setting the close cookie to remember the close state, the open cookie still persists.
$(document).ready(function() {
// Open / Close Panel According to Cookie //
if ($.cookie('filtermenu') === 'open'){
$('.filter').show(); // Show on Page Load / Refresh without Animation
}
else {
}
if ($.cookie('filtermenu') === 'close' || $.cookie('filtermenu') === null){
$('.filter').hide(); // Show on Page Load / Refresh without Animation
}
else {
}
// Toggle Panel and Set Cookie //
$('#filter-menu').click(function(){
$('.filter').slideToggle('fast', function(){
if ($('#filter-menu').is(':hidden')) {
$.cookie('filtermenu', 'close', { expires: 30 });
} else {
$.cookie('filtermenu', 'open');
}
});
return false;
});
});
Can anyone please see what I'm doing wrong.
Thanks.
Update: Sorry, so now I have this, but it's still not staying closed, am I using the date object incorrectly?
Ok, so now I have this, but the menu still doesn't stay closed.
$(document).ready(function() {
// Open / Close Panel According to Cookie //
if ($.cookie('filtermenu') === 'open'){
$('.filter').show(); // Show on Page Load / Refresh without Animation
}
else {
}
if ($.cookie('filtermenu') === 'close' || $.cookie('filtermenu') === null){
$('.filter').hide(); // Show on Page Load / Refresh without Animation
}
else {
}
// Toggle Panel and Set Cookie //
$('#filter-menu').click(function(){
$('.filter').slideToggle('fast', function(){
var now = new Date();
var time = now.getTime();
time -= 60 * 1000;
now.setTime(time);
$.cookie('filtermenu', 'open', {expires: now});
if ($('#filter-menu').is(':hidden')) {
$.cookie('filtermenu', 'close', { expires: 30 });
} else {
$.cookie('filtermenu', 'open');
}
});
return false;
});
});
You are going to want to re-set the open cookie with an expiration date older than current time right before you set the close cookie. That way the open cookie will immediately expire and your closed cookie is what remains.
Update - Getting the time
You've inquired about getting the current time in JS, here is some sample code:
var now = new Date();
var time = now.getTime();
time -= 60 * 1000;
now.setTime(time);
This creates a new Date object called now and extracts the time from it with getTime(). We then subtract one minute of time (time is in milliseconds, so 60 * 1000), and then set the date back to that time. You can now use this Date object to set the expiration time of your cookie!
I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}