Showing Alert Confirm Prompt Temp [duplicate] - javascript

I have this code that shows alert when it's 30 minutes before event in calendar but I want to show it only once when user comes to page (in that 30min). Now it shows on every page refresh and also on calendar refresh (in that 30min) because it is set to refresh events after period of time. How to display this alert just once?
var mili = event.start.getTime() - now.getTime();
if(mili < 1800000 && mili > 0){
$('.alert').dialog({
buttons: [{
text: "OK",
click: function() {
$( this ).dialog( "close" );
}
}]
});
}

You can use localStorage (not compatible with older browsers):
<script type="text/javascript">
var alerted = localStorage.getItem('alerted') || '';
if (alerted != 'yes') {
alert("My alert.");
localStorage.setItem('alerted','yes');
}
</script>
Or you can use cookies, give a look to this answer for a full example code:
https://stackoverflow.com/a/21567127/3625883

Set a cookie when you show the alert. Then, if the cookie is set, you will know not to show the alert again. If it is not set, you know that you haven't shown the alert yet and should do so now.
You can read about setting cookies in JavaScript here.

I know this is late but you definitely don't have to use local storage or cookies. I was disheartened by the answer here so I found my own solution.
Use a boolean and an embedded if statement.
var alerted = false;
if (x > y)
{
y = z;
if (alerted === false)
{
alert("show your message");
alerted = true;
}
}
You can then reset the alerted variable later on if you want to show the alert message again.

You have to use cookies or localStorage or sessionStorage to do this!
See the following link on localStorage:
http://www.w3schools.com/html/html5_webstorage.asp
or
http://www.webdesignerdepot.com/2013/04/how-to-use-local-storage-for-javascript/

Related

Can you use localStorage to store what a user puts in a div contenteditable and a set color?

I made a fairly basic "biomaker" website where the user can edit the card through several <div contenteditable="true">s, and it also uses a simple javascript to allow the user to cycle through several preset colors.
After receiving feedback from several users it seems that it would be better if the page could save the user's previous information upon closing/refreshing the tab.
I did a little research and I came upon the localStorage function but I'm not sure if it can be applied to the color changer and more importantly, the <div contenteditable="true". I'm wondering if 1) it's possible and 2) if so, how I can make it save the content, since what the user puts in the div doesn't affect the backend.
Thanks in advance for any help.
Disclaimer: I've seen a lot of people bashing others because they're asking for "free code". I'm not asking for that here, I'm just hoping people can 1) tell me if it's possible and 2) can point me in the right direction.
EDIT: Thanks for the help! I was able to find a solution.
Yes it is posssible.
You first should check whether localStorage is available in the user's browser, for what you can use this function that works in all browsers (i use it too on my website):
function storageAvailable(type) {
var storage;
try {
storage = window[type];
var x = "__storage_test__";
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch (e) {
return e instanceof DOMException && (e.code === 22 || e.code === 1014 || e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED") && (storage && storage.length !== 0);
}
}
Use it like this:
editableDiv = dopcument.getElementById("print"); // get the editable div
editableDiv.addEventListener("input", function() { // this function will be executed whenever the content of the editableDiv changes
if (storageAvailable("localStorage")) { // check for storage availability
divcontent = editableDiv.innerHTML; // get contents of the editableDiv
window.localStorage.setItem("divcontent", divcontent); // add them to the localStorage
} else { // if localStorage is not supported, notify the user about it
alert("Your browser does not support localStorage or you disabled it, the things you entered could not be saved !");
}
});
and when the user comes back, you can restore the contents:
editableDiv = document.getElementById("print"); // get the editable div
window.addEventListener("load", function() { // this function is executed whenever the page is loaded
if (storageAvailable("localStorage")) { // check for storage availability
divcontent = window.localStorage.getItem("divcontent"); // get the saved divcontent
if (divcontent === null) { // if the user never modified the divcontent before (or cleaned his localStorage), do nothing
} else {
editableDiv.innerHTML = divcontent; // write it into the editableDiv
}
} else { // if strorage not available, notify the user
alert("Your browser does not support localStorage or you disabled it, your previous work could not be restored !");
}
});
Feel free to modify this code to your needs, and notify me about any problems you have with it ! (couldn't test it, am busy right now)

Javascript confirmation cancel button issue [duplicate]

In my Rails 3 application I do:
render :js => "alert(\"Error!\\nEmpty message sent.\");" if ...
Sometimes, below this error message (in the same alert box) I see: "Prevent this page from creating additional dialogs" and a checkbox.
What does this mean ?
Is that possible not to display this additional text and checkbox ?
I use Firefox 4.
It's a browser feature to stop websites that show annoying alert boxes over and over again.
As a web developer, you can't disable it.
What does this mean ?
This is a security measure on the browser's end to prevent a page from freezing the browser (or the current page) by showing modal (alert / confirm) messages in an infinite loop. See e.g. here for Firefox.
You can not turn this off. The only way around it is to use custom dialogs like JQuery UI's dialogs.
You can create a custom alert box using java script, below code will override default alert function
window.alert = function(message) { $(document.createElement('div'))
.attr({
title: 'Alert',
'class': 'alert'
})
.html(message)
.dialog({
buttons: {
OK: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).remove();
},
modal: true,
resizable: false,
width: 'auto'
});
};
Using JQuery UI's dialogs is not always a solution. As far as I know alert and confirm is the only way to stop the execution of a script at a certain point. As a workaround we can provide a mechanism to let the user know that an application needs to call alert and confirm. This can be done like this for example (where showError uses a jQuery dialog or some other means to communicate with the user):
var f_confirm;
function setConfirm() {
f_confirm = confirm;
confirm = function(s) {
try {
return f_confirm(s);
} catch(e) {
showError("Please do not check 'Prevent this page from creating additional dialogs'");
}
return false;
};
};
I designed this function to hopefully circumvent the checkbox in my web apps.
It blocks all functionality on the page while executing (assuming fewer than three seconds has passed since the user closed the last dialog), but I prefer it to a recursive or setTimeout function since I don't have to code for the possibility of something else being clicked or triggered while waiting for the dialog to appear.
I require it most when displaying errors/prompts/confirms on reports that are already contained within Modalbox. I could add a div for additional dialogs, but that just seems too messy and unnecessary if built-in dialogs can be used.
Note that this would probably break if dom.successive_dialog_time_limit is changed to a value greater than 3, nor do I know if Chrome has the the same default as Firefox. But at least it's an option.
Also, if anyone can improve upon it, please do!
// note that these should not be in the global namespace
var dlgRslt,
lastTimeDialogClosed = 0;
function dialog(msg) {
var defaultValue,
lenIsThree,
type;
while (lastTimeDialogClosed && new Date() - lastTimeDialogClosed < 3001) {
// timer
}
lenIsThree = 3 === arguments.length;
type = lenIsThree ? arguments[2] : (arguments[1] || alert);
defaultValue = lenIsThree && type === prompt ? arguments[1] : '';
// store result of confirm() or prompt()
dlgRslt = type(msg, defaultValue);
lastTimeDialogClosed = new Date();
}
usage:
dialog('This is an alert.');
dialog( 'This is a prompt', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'Is this a prompt?', 'maybe', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'OK/Cancel?', confirm );
if (dlgRslt) {
// code if true
}
This is a browser feature.
If you could, try to employ http://bootboxjs.com/, whit this library you can do the same of
alert("Empty message sent");
by writing:
bootbox.alert("Empty message sent", function(result) {
// do something whit result
});
You'll get a nice user interface too!

not to pop up a form on second click using js

I have a pop up form on my site which pops up as soon as some one click on the link. but I want to make it such that it should not pop up for the second time for a same user.
how to do it, as I don't have user management system.
Even better Solution,Use one in Jquery
<a id="popup" >link1</a><br>
$('#popup').one('click',function(){
alert('open your popup here');
});
Here is you fiddle
You need to use cookies for it. At first click, generate a cookies when user clicks at first time and checks if it's available when user click on it.
So, as kind of solution u can use cookies. Example below.
This support function will help u get cookie using JS later
function getCookie(name) {
var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,'\\$1')+"=([^;]*)"));
var x = matches ? decodeURIComponent(matches[1]) : undefined;
return x;
}
And than in user click handler set cookie for browser like this
$(document).on('click','#someDivHere',function() {
if (getCookie('addShowed') === undefined) {
var date = new Date( new Date().getTime() - 2*24*60*60*1000 );
document.cookie="addShowed='true'; path=/; expires="+date.toUTCString();
}
});

Global variable isn't holding?

This should be a really easy "derp" question, but here it is:
I'm trying to set up a global variable in a JS file so that I can control when an action triggers. In my case, I want okBoxCall to only be called if firstTime is true. I have firstTime set to true initially, then I change it to false afterwards. My code is NOT working as it should however, as it still calls up okBoxCall more than once.
var Dialog;
var HUDWindow;
var smartPhone;
var firstTime = true;
$(document).ready(function(){
smartPhone = new SmartPhone();
initDialog();
initHUDWindow();
if(firstTime == true)
{
okBoxCall("Tutorial", "Welcome to McLarin Energy!");
firstTime = false;
}
});
What am I doing wrong? Obviously firstTime is not holding its change to false...
EDIT Forgot to mention that this is for a 3D game, not web pages. Cookies are not used.
I'm guessing you want to check whether this is the first time the user opens a page and open a tutorial if it is?
It is not possible the way you want to do it. Every time your page is loaded your script is evaluated again. So this means a variable firstTime is created and it is set to true. What you need is some persistent storage on the client to store whether it is the first time or not. You will need to set a cookie or call the localStorage API if you don't bother disregarding older browsers.
Your function should only be called once due to $(document).ready(...). So, I'm guessing you're reloading the page to get the alert to display again and again...
Maybe you should be looking at using cookies, not just a plain old JS variable..?
What is okBoxCall doing? If you have any error in okBoxCall firstTime = false will not be executed. Set the value before you call okBoxCall.
$(document).ready(function(){
smartPhone = new SmartPhone();
initDialog();
initHUDWindow();
if(firstTime == true)
{
firstTime = false;
okBoxCall("Tutorial", "Welcome to McLarin Energy!");
}
});

Catching A Browser Close Event

Hello Seniors (As I am new to Web Based Applications),
I was keen to implement or catching browser closing event.
Yes! I did it and successfully implemented it by using javascript{see code below}
but I have implemented it in a web page without MasterPage.
Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
Is there any technique or logic to detect whether I can differentiate between a Close browser button and a page's post back event.
Please guide me...as I have to implement in a project as soon as possible....
thank you.
Ankit Srivastava
<script type="text/javascript">
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
</script>
<script type="text/javascript">
var g_isPostBack = false;
window.onbeforeunload = check ()
function check()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogOff.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%# Session["loginId"] %>';
var returnCode = callAjax(webUrl, queryString);
}
</script>
There is no javascript event which differentiates between a browser being closed and the user navigating to another page (either via the back/forward button, or clicking a link, or any other navigation method). You can only tell when the current page is being unloaded. Having said that, I'm not sure why you'd even need to know the difference? Sounds like an XY problem to me.
The answer can be found on SO:
How to capture the browser window close event?
jQuery(window).bind("beforeunload", function(){return confirm("Do you really want to close?") })
and to prevent from confirming on submits:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
First step: add global JavaScript variable called "_buttonClicked" which is initially set to false.
Second step: have every button click assign _buttonClicked value to true.. with jQuery it's one line, pure JavaScript is also few lines only.
Third step: in your function check _buttonClicked and if it's true, don't do anything.
EDIT: After quick look in your code I see you already have steps #1 and #3, so all you need is the second step, assign g_isPostBack as true when any submit button is clicked. Let me know if you need help implementing the code and if you can have jQuery.
If one wants to catch Log out when the browser is closed (by clicking on the cross), we can take the help of window events.
Two events will be helpful: onunload and onbeforeunload.
But the problem arises that the code will also work if you are navigating from one page to another as well as also when one
refreshes the page. We don't want our sessions to be clear and inserting the record of logging out while refreshing.
So the solution is if we distinguish the difference between closing and refreshing or navigating.
I got the solution:
Write 'onbeforeunload ="loadOut();"' within the body tag on master page.
Add the following function inside script in head section of master page :-
function loadOut() {
if ((window.event.clientX < 0) || (window.event.clientY < 0))
{
// calling the code behind method for inserting the log out into database
}
}
And its done. It is working for IE, please check for other browsers. Similarly you can detect the event if the window is closed
by pressing the combination of keys ALT+F4.
window.unload fires when we navigate from one page to another as well as when we click on close button of our browser,So to detect only browser close button you need to use flag.
var inFormOrLink;
$("a,:button,:submit").click(function () { inFormOrLink = true; });
$(":text").keydown(function (e) {
if (e.keyCode == 13) {
inFormOrLink = true;
}
})/// Sometime we submit form on pressing enter
$(window).bind("unload", function () {
if (!inFormOrLink) {
$.ajax({
type: 'POST',
async: false,
url: '/Account/Update/'
});
}
})

Categories

Resources