bootstrap modal show with cookie set for 30 min - javascript

I was following the steps in this topic here, and set up my cookie below to show my Modal once a day.
<script type="text/javascript">jQuery(document).ready(function($) {
$('#myModal').appendTo("body");
if ($.cookie("pop") == null) {
$("#myModal").modal("show");
$.cookie("pop", ’1′);
}
$('#myModal').modal({
keyboard: false,
backdrop:false
});});</script>
This works fine, but how do I set this up so that the cookie only last 30 minutes instead of one day?

you can pass in an object with expires as a key, the value of that will be the expire date of the cookie in days.
ie:
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
$.cookie("cookieName", "cookieValue", { expires: date });
this example would set the cookie to 30 minutes from the time of creation

Related

How to delete cookie when the page url is changed but not at time of refreshing in jquery?

I want to delete the cookie if my url is changed, as if i don;t do this some of the functionalities are not working properly. Like I want whenever my page reloads means it is opening first then my dropdown should have the value of default. I can do that easily but the main problem occurs when I changed the value of my dropdown i also want that time it should have the last selected option on the dropdown list. I only want the default value when my page is first opened or i change the page then I get back to my dropdown page url.
this is my cookie codes :
// create cookie
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
//delete cookie
function deleteCookie(name) {
setCookie(name,"",-1);
}
now I tried to unset my cookie in this way :
if(getCookie("myCookie") !== null && getCookie("myCookie") !== ""){
$('#formA').val(getCookie("myCookie")).trigger('change');
}
else {
goToDefault(); // this onload has the default value "Teacher"
}
$(window).on('beforeunload', function(){
setCookie("myCookie", $('#formA').val(), 12);
});
$(window).on('unload', function() {
if(window.location.pathname !== '/dropdown'){
deleteCookie("myCookie");
}
});
i tried under to use this function on$(window).on('beforeunload' but in vain. It always works whenver I submit something or page reloads. All I want is this behavior:
this is my dropdown:
Teacher => deafult value option
Student
Books
these are the option of my dropdwon, now if i select Student and then work on this option, my dropdown should have it's value as Student only that time untill I change it. But if I change the page, and then again enter on that page I should get default value Teacher.
How should I resolve this?
You can use window.onpopstate to detect changes in the url then delete your cookie. Here's an example below:
// create cookie
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
//delete cookie
function deleteCookie(name) {
setCookie(name,"",-1);
}
if(getCookie("myCookie") !== null && getCookie("myCookie") !== ""){
$('#formA').val(getCookie("myCookie")).trigger('change');
}
else {
goToDefault(); // this onload has the default value "Teacher"
}
window.onpopstate = () => {
deleteCookie("myCookie");
}
Hope this helps.
I'm guessing here, but I suppose this is a form you can submit and you want to:
get the default dropdown option if the page is opened for the first time or in a new page/tab of the browser
persist the selected option if the page is reloaded
reset the dropdown to the default option when you submit the form (and therefore probably change URL)
What you may want to look into is sessionStorage which similarly to cookies and localStorage allows you to save some data (in different ways).
Saving data to sessionStorage is as simple as:
sessionStorage.setItem('key', 'value');
What's important is that this could be the perfect solution for your problem because out of the box sessionStorage will clear the data you saved when the page session ends. As per the documentation (which I encourage you to check)
a page session lasts as long as the browser is open, and survives over page reloads and restores
To answer your question, you probably can:
save the selected option with sessionStorage.setItem('key', 'value') when it changes
use sessionStorage.getItem('key') to retrieve the value of the dropdown
use sessionStorage.removeItem('key') to remove the saved key when you submit the form
A new page or tab won't find any saved option cause the session will be a completely new one.
Hope this helps!

How do I write a monthly HTML alert that shows relative to the user's timezone

Show an alert in a browser on the whole 24 hour period of a set time frame and show it for the same 24 hour period of a set timezone no matter what the user's timezone is.
Then show the period relative to the user's timezone
I spent quite a bit of time figuring this out and wanted to post my results to help someone.
http://jsfiddle.net/y7uLtwno
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>
<script>
// Goal: Show a maintenance alert on a webpage that lasts for the 24 hour period relative to a set time zone and then show the alert with the maintenance period relative to the browser's timezone
// Variables: You must set the static timezone relative to where the maintenance is happening
// Scnario: Your server is in one timezone and scheduled maintenance happens every month, and you want to alert users worldwide in their timezone for the whole day
// Author: Joshua Wyss
//MUST use .ready to account for the way that Confluence loads the side-bar. Without it the sidebar loads after the alert and makes the sidebar overlap the header until the user scrolls.
function showHide() {
// Grab the alert div "s" and the text inside the div "h"
var s = document.getElementById(4);
var h = document.getElementById(5);
// *** SET THESE VARIABLES *** //
// Set location to ISO timezone
var location = 'America/Chicago';
// 24 hr format for start and end of maintnenace relative to above timezone. To use 12 hr format change variables t1 and t2 format to 'hh:mm a' the use the "hh:mm am/pm" see: http://momentjs.com/docs
var maintStart = '18:00';
var maintEnd = '20:00';
//For weekOfMonth # should be the number week of the month (starting at 1)
var weekOfMonth = 4;
//For dayOfWeek # is >> 0=Sun, 1=Mon, 2=Tue, 3=Wed, 4=Thu, 5=Fri, 6=Sat
var dayOfWeek = 1;
// *** SET THESE VARIABLES *** //
//set d to current time in United States Central Time
var d = moment(moment().utc().format()).tz(location);
// Get "location" day of month number (example: 22 or 01)
var centDateNum = d.format('DD').toString();
// Get "location" day of week number
var centDayOfWeek = d.format('e').toString();
// Check if "location" today matches weekOfMonth and dayOfWeek specified
if (Math.ceil(centDateNum / 7) == weekOfMonth && centDayOfWeek == dayOfWeek) {
// Show the HTML alert
s.style.display = (s.style.display == 'block') ? 'none' : 'block';
// Convert start time to local
var t1 = moment.tz(maintStart, 'HH:mm', location).local().toDate();
// Convert end time to local
var t2 = moment.tz(maintEnd, 'HH:mm', location).local().toDate();
// Add start and end time to the HTML alert. TO modify formatting see: http://momentjs.com/docs/#/displaying/format/
h.innerHTML += " " + moment(t1).format('dddd') + " " + moment(t1).format('HH:mm') + "-" + moment(t2).format('HH:mm');
}
}
</script>
<div id="4" style="display:none; background-color: linen; border: 3px solid darkred; margin: 2px; padding: 2px; font-weight: bold; text-align: center;">
<h3 id="5">Monthly maintenance scheduled this </h3>
</div>
<body onload="showHide()">

Datetime Picker schedule time to 8 hrs from current time

I'm using DateTimePicker jQuery plugin by XDSoft, please check below image
My requirement is that, if i selected current date,(9th Nov, 2015) then the time from time picker should show 6hrs add to current time...
I mean, in above image current Date is selected... and current time is 12.00 but i want that 12.00 & above time should be disable..
How can we do that..??
Based on XDSoft DateTimePicker documentation, here's what can be done:
var logic = function( currentDateTime ){
var d1 = new Date();
// Check that it's today, so we need to restrict time chooser
if (currentDateTime.getDate() == d1.getDate() && currentDateTime.getMonth() == d1.getMonth())
{
// Adding six hours
d1.setHours ( d1.getHours() + 6 );
// Creating 'HH:MM' string
var defaultTime = (d1.getHours() < 10 ? "0" : "") + d1.getHours() + ":" + (d1.getMinutes() < 10 ? "0" : "") + d1.getMinutes();
// Enforce time restriction
// ('this' is jquery datetimepicker object)
this.setOptions({
minTime : defaultTime,
defaultTime : defaultTime
});
}
else
{
// Lift time restriction if selected day is not today
this.setOptions({
minTime : false,
defaultTime : false
});
}
};
// Initiate datepicker with custom logic
$('#datetimepicker').datetimepicker({
onChangeDateTime:logic,
onShow:logic
});
Adding 6 hours solution based on: https://stackoverflow.com/a/13034220/2715393

jQuery cookie is not expring

I am using this jQuery cookie plugin for create & display cookie.
var date = new Date();
var minutes = 2;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie('the_cookie', 'the_value', { expires: date });
alert($.cookie('the_cookie'));
I set two minutes (for test, usually I will use one hour. Explained below.), but if I visit the page again after two minutes, it is still displaying cookie alert.
What I want to do
I want to display a message to my website for one hour timing. It means, when visitor open my website first time, visitor can see the message. When visitor clicks on other page, the message will not show. After one hour, the message will show again.
How can I set minutes, hours as well as days?
Here is my codes fiddle.
That's because you're showing the alert after you create/recreate the cookie. :)
If you move alert($.cookie('the_cookie')); to the start of your code snippet, your cookie will disappear in 2 minutes.
Just use Chrome's Resources > Cookies tab to verify. :)
Here's an updated test harness that will also show the cookie expiring:
http://jsfiddle.net/bvaughn/860rr2Ly/
if ($.cookie('temporaryCookie')) {
alert('Cookie still set');
} else if ($.cookie('longerCookie')) {
alert('Cookie expired at ' + $.cookie('longerCookie'));
} else {
alert('Cookie never set');
}
var expiresAt = new Date();
expiresAt.setTime(expiresAt.getTime() + 5000); // 5 secs
$.cookie('longerCookie', new Date());
$.cookie('temporaryCookie', true, { expires: expiresAt });
You can try
var thecookie = $.cookie('shown');
if (!thecookie) {
var date = new Date();
var delay = 20 * 1000;
date.setTime(date.getTime() + delay);
$.cookie('shown', 'true', {
expires: date
});
$('body').html('show the message')
}
Demo: Fiddle
If you're not worried about IE8 and earlier, you can just use max-age and straight javascript as a simpler solution:
if (document.cookie.indexOf('the_cookie') == -1) {
//show message
document.cookie = 'the_cookie;path=/;max-age=120;';
}
This shows the message and sets a 2 minute cookie if the cookie has not been set previously or has expired.

How do change javascript cookie from 15 day count to manually do a new cookie?

I'm implementing a script with Colorbox which shows a nice popup the first time a user visits a website. This script that I found is setting the cookie to last for 15 days - what I want is to manually be able to manage the "cookie-update" by my own. In my case I want to use this script to show the user that my website has been updated and using the Colorbox to show the changelog; just on the first visit. Something like this:
Update #1 -> New cookie tells there's a new update -> Show Colorbox 1 time -> Then no more, until...
Update #2 -> New cookie tells there's a new update -> Show Colorbox -> ...and so on...
Short version of the question: How do I change the script from a 15 day timer to manually be able to change it so I can decide when I want to show my Colorbox with a new changelog?
The original script is located here:
http://papermashup.com/automatic-jquery-site-subscription-lightbox/
You need to put a date in the site - Note JS months start at zero
DEMO
var latestUpdate=new Date(2012,11,10).getTime(); // 10th of December
var whatVersionSeen = parseInt($.cookie("visited"));
if (isNaN(whatVersionSeen)) whatVersionSeen = 0; // first time
if (whatVersionSeen < latestUpdate) { // whatever in the cookie < latest update
$.cookie('visited', latestUpdate, { expires: 365 });
$.colorbox({width:"580px", inline:true, href:"#subscribe_popup"});
}
the above code replaces
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"580px", inline:true, href:"#subscribe_popup"});
}
completely and expects to find $.cookie
There is Jquery Code in that Script.
$("document").ready(function (){
// load the overlay
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"580px", inline:true, href:"#subscribe_popup"});
}
$(".open_popup").colorbox({width:"580px", inline:true, href:"#subscribe_popup"});
});
if you want to change the days then change it here.
var fifteenDays = 1000*60*60*24*15;

Categories