how to flash jquery dialog box - javascript

Is there any way to flash jquery dialog box on the browser to let user know something important needs to be done if he is on other window. Lets take the case for timeout popup where user needs to extend his session, so if we could flash the dialog then user is notified when he is on other page.
Actually its a timeout jquery popup for which I want user's attention, so that he can take appropriate action.

It's not exactly what you're talking about, but I think the UI effect you actually need is a
dynamic favicon change, as described in: Is it possible change favicon on site when users change themes?
Using that, you can swap the favicon back and forth with some kind of alert icon every second or so until the user returns to the window.

This is expanded version of my comment.
Say you have this JS cookie object:
var Cookie = {
set: function(name,value,seconds) {
var date = new Date;
date.setTime(date.getTime() + (typeof seconds != "undefined" ? seconds : 1) * 1000);
document.cookie = name + "=" + value + "; expires=" + date.toGMTString() + "; path=/; domain=." + vitalPage.getDomain();
},
get: function(name){
var re = new RegExp("(?:^| )" + name + "=([^;]*)", "i");
var matches = document.cookie.match(re);
return matches && matches.length == 2 ? matches[1] : null;
},
read: function(name){
var re = new RegExp("(?:^| )" + name + "=([^;]*)", "i");
var matches = document.cookie.match(re);
return matches && matches.length == 2 ? matches[1] : null;
},
unset: function(name){
this.set(name,'',-1);
}
}
On initial page load, do this:
var sess_expires = Cookie.get('sess_expires'),
sess_remaining,
show_dialog = function() {
$('#your_dialog_id').show();
}
if (sess_expires !== null) {
sess_remaining = sess_expires - new Date();
if (sess_remaining > 0) {
window.setTimeout(show_dialog, sess_remaining); // show dialog when session expires
}
else show_dialog(); // show dialog now - session expired
}
else {
Cookie.set('sess_expires', new Date() + 1800000);
window.setTimeout(show_dialog, 1800000); // show dialog when session expires
}

Related

Local Storage Not Working As Expected

I built an app that I then built with PhoneGap Build.THe purpose is for it to run a code (starts at var Quotes once per day when the app is loaded).
When debugging why it wasn't working I noticed that in console I was getting back my message "Local storage didn't work". This means that my initial localstorage.getItem which is supposed to make sure the local storage can be read is returning null. So my code never gets executed.
What am I doing wrong?
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if(localVal == null){
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
Initially, there will be no DateOpened item in local storage, so your code will follow the "did not work" branch, because getItem returns null for things that don't exist. That branch never sets anything in DateOpened, so...you'll always follow that branch.
The fix is not to skip over your code setting DateOpened if the device has local storage.
There's also an unrelated problem: Your var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear() does not produce a string, it produces a number formed by adding those values together, since they're all numbers. Your later localeCompare will fail because it's not a string. You also have the fields in the wrong order for a meaningful textual comparison — you need year first, then month, then day.
Here's a minimal fix, see comments:
function onDeviceReady() {
var tempd = new Date();
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDay();
var localVal = localStorage.getItem('DateOpened');
// If we have no stored value, or it's more than a day old by your definition,
// do your stuff and store the new date
if (localVal == null || localVal.localeCompare(str) < 0) {
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened', str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
I think this is help full for you.
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if (typeof(DateOpened) == "undefined")
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
var allRecords=JSON.parse(localStorage.getItem("DateOpened"));
if(allRecords == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}

Using JavaScript and cookies to create user authentication and a notes app

I'm trying to create a simple notepad app (basic CRUD) using just JavaScript and it has to have a login/signup function, I've managed to create code to get a cookie, if the cookie doesn't exist it sets one and then deletes one after an expiry date.
Here is my cookie code:
function getCookie(usersCookie){
if (document.cookie.length > 0){
begin = document.cookie.indexOf(usersCookie+"=")
if (begin != -1){
begin += usersCookie.length+1;
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end));
}
}
}
function setCookie(usersCookie, value, expiredays){
var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
document.cookie = usersCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires =" + ExpireDate.toGMTString());
}
function delCookie (usersCookie){
if (getCookie(usersCookie)){
document.cookie = usersCookie + "=" + "; expires=Thu, 14-Jan-15 00:00:01 GMT";
}
}
What I need to know now is how I save arrays to the cookie to access later since I can use this for the rest of the app, I'm replacing the DB with Cookies, I'm aware this is the worst way to do something like this, this is purely a self learning exercise to get used to using cookies.
Thanks in advance
you can use JSON.stringify
var arr = [1,2,3,4];
var output = JSON.stringify(arr)
outputs
"[1,2,3,4]"
save this value in cookie and while fetching back use JSON.parse
arr = JSON.parse( output );

How do cookies recognize name, expiration date, path

I am new to JavaScript and cookies, so I have this weird question as different websites had different format. So I had confusion on how the cookies read and access the different parts of it, i.e. how do cookies recognize names from path or expiration date? Do we always have to specify "username=...;path=/;" for it to recognize it or does it automatically find it based on the format?
And the main question that I am trying to figure is how I can add a value to the cookie creation code, such as a " document.cookie="username=John;visit=1;" and use that visit part to tell the hit count by adding 1 to it every time the page loads.
Thank you!
I use two functions (maybe the original code was from here or here) for getting and setting cookies, here are they:
function setCookie(cookieName, content, expires, path) {
var date = new Date();
date.setDate(date.getDate() + expires);
var cookie = escape(content) + (expires == null ? "" : "; expires=" + date.toUTCString()) + (path != null ? "; path=" + path : "");
document.cookie = cookieName + "=" + cookie;
return true;
}
function getCookie(cookieName) {
var cookie = document.cookie,
begin = cookie.indexOf(" " + cookieName + "=");
if (begin == -1) begin = cookie.indexOf(cookieName + "=");
if (begin == -1) cookie = null;
else {
begin = cookie.indexOf("=", begin) + 1;
var end = cookie.indexOf(";", begin);
if (end == -1) end = cookie.length;
cookie = unescape(cookie.substring(begin, end));
}
return cookie;
}
With them you can easily do what you want:
Handle the page loads (eg <body onload="pageLoad()">)
Add a script element to the head part of the page, and the two funtions above
Add the following function inside the script element:
function pageLoad() {
var cCont = getCookie('hitCount');
var count = 0;
if (cCont != null) count = parseInt(count + '');
setCookie('hitCount', (count + 1) + '', null, null);
}
If you want to get the hit count, you can use the count variable, or use the getCookie function again.
Your first question is not totally clear to me, but read this page, there are nice examples and code samples. This is another good presentation of cookies.

unable to read cookie first time in javascript

I am using Javascript to set the cookie and read the value from cookie.I am using the code available at http://www.w3schools.com/js/js_cookies.asp for creating and reading the value of cookie.when the page loads i am checking that whether that cookie exists or not .Every thing is working fine except it is not reading the cookie when i set it first time and try to read in next page load .it is setting the cookie but does not read only first time .
Here is my code :-
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
//To get the cookie:-
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
//to Delete the cookie:-
function cookieDelete(c_name) {
setCookie(c_name, "delete", -1);
}
And on page load i am using it like :-
$(document).ready(function () {
var aZ = getCookie("menuSave");
if (aZ) {
//do Some thing here
}
else {
setCookie("menuSave", "mysp", null);
}
});
You need to add a 'path' to your cookie. For example:
document.cookie = 'ppkcookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/';
The path represents the relative path in your website which the cookie will be readable.
path=/ means it'll be readable on your whole website.
path=/common/ means it'll be readable only in /common/ folder (and its subfolders)
This might not be the answer to your problem but yet a alternative easier solution, hope it helps!
save menu
localStorage.setItem("menusave","vale");
load value
localStorage.getItem("menusave");
Just trying to help!
Since you have marked the question as asp.net,
You can set the cookies as follows:
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
And read it back like:
if(Request.Cookies["lastVisit"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);
Refer MSDN Cookies overview
When you pass null for the expiration days it makes your cookie into a session cookie that will not persist very long.
Change this:
setCookie("menuSave", "mysp", null);
to this to give it an actual expiration date:
setCookie("menuSave", "mysp", 7);
If you want to retrieve the cookie from any page besides the exact same page that set it, you will also need to set a path value in the cookie that allows the cookie to be retrieved on more than just the exact page that set it.

Keeping a counter after page is refreshed?

I need to keep a counter for a game that I am making. Each time they win a game, I want to add one to the counter. However, each time they win, the page is refreshed to start a new game. Is there a way to keep this counter updated even if the page is reloaded?
You can use cookies, here's a very simple example with jQuery cookie plugin:
Code: https://github.com/carhartl/jquery-cookie
Usage examples: http://www.electrictoolbox.com/jquery-cookies/
Set cookie:
$.cookie("example", "foo", { expires: 7 });
Get cookie value:
alert( $.cookie("example") );
Very clean and compact :)
Store the value in a cookie or in localStorage if using compatible browser.
Put it in a cookie. Mmmm... cookies. Yummy.
https://developer.mozilla.org/en/DOM/document.cookie
w3school cookie gives a simple explanation for it.
Shortly, it's a way to save your browser data on local machine.
// So, you may try
setCookie("win_count",value,exdays); // to set some data to "win_count"
// and after the page was reloaded to restore the win counter with the help of:
getCookie("win_count");
Use cookies
jQuery:
$.cookie("example", "foo", { expires: 7 });
Pure JavaScript:
function getCookie(name) {
var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"))
return matches ? decodeURIComponent(matches[1]) : undefined
}
function setCookie(name, value, props) {
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp * 1000)
exp = props.expires = d
}
if (exp && exp.toUTCString) {
props.expires = exp.toUTCString()
}
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for (var propName in props) {
updatedCookie += "; " + propName
var propValue = props[propName]
if (propValue !== true) {
updatedCookie += "=" + propValue
}
}
document.cookie = updatedCookie
}
function deleteCookie(name) {
setCookie(name, null, {
expires: -1
})
}

Categories

Resources