javascript ok/cancel dialog box appear once per session - javascript

I am trying to get this to work in my iweb page hosted not on MobileMe. With the code below I continue to get the alert box on each refresh of the page instead of once per session. I am a total newbie here so be kind please.
//Alert message once script- By JavaScript Kit
//Credit notice must stay intact for use
//Visit http://javascriptkit.com for this script
//specify message to alert
var answer=confirm("Click OK if you have been cleared Sutter's HR department to start
volunteering.")
if (answer)
alert ("Excellent!! Please select your dates directly within the scheduling calendar.")
else
alert ("Let's get to it then. Contact Ruth in HR at 576-4208 to schedule an appointment so you can get started.")
///No editing required beyond here/////
//answer only once per browser session (0=no, 1=yes)
var once_per_session=1
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset);
// set index of end of cookie value
if (end == -1)
end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function alertornot(){
if (get_cookie('alerted')==''){
loadalert()
document.cookie="alerted=yes"
}
}
function loadalert(){
alert(alertmessage)
}
if (once_per_session==0)
loadalert()
else
alertornot()
</script>

Your code calls this once per session:
alert(alertmessage)
but the code on top is called on each load of the script.
Moreover - I don't see where alertmessage is defined...
So You probably want to put the code from the top inside the loadalert function resulting in this:
function loadalert(){
var answer=confirm("Click OK if you have been cleared Sutter's HR department to start volunteering.")
if (answer)
alert ("Excellent!! Please select your dates directly within the scheduling calendar.")
else
alert ("Let's get to it then. Contact Ruth in HR at 576-4208 to schedule an appointment so you can get started.")
}
EDIT:
And BTW - start using curly braces. It helps in debug and in understanding where You are. :)

Related

Global Variable not affected in JQuery Ajax Success Function

I have a recursive function that populates a list until the bottom of the screen is reached, then stops.
Each time the recursive function is called, the "start" global variable increments by the limit (5). For example, after 3 times, the "start" variable should be 15. This shows up correctly in the console.
However, outside the recursive function, it seems the "start" variable is still at "0". I thought using "var start = 0" outside of the function makes it global and should be changed by the Ajax success function. The code is below:
//****************************************************************
// Loading questions and answers listings
//****************************************************************
var tag = '';//initialize as blank
var search = '';//initialize as blank
var limit = 5;//number of records to autoload each time
var start = 0;//start at record 0
var action = 'inactive';//initial status to get initial load
var autoscroll = 'false';//check box to engage auto scroll or keep manual load more
var checked = '';//check box value for autoscroll
function load_data(limit, start, search, tag){//recursive function for auto loading
search = $('#search').val();
var loads;
$.ajax({
url:"/modules/posts/questions_all_autoscroll_fetchdata.php",
method:"POST",
data:{limit:limit, start:start, search:search, tag:tag},
cache:false,
success:function(data){
$('#load_data_message').show();//bring loading button back once load successful.
//It is removed during tag click search to avoid glitchy appearance of button showing at top left briefly.
$('#load_data').append(data);
//checks if quantity "limit" amount loaded. If not, that means end of data reached.
//Each data piece has id="container", so counting them tells how many data pieces returned in "loads"
loads = $(data).find('.card-header').length;
if(loads<limit){button_name = 'End of Data';}else{button_name='Loading More <i class="fas fa-spinner fa-lg fa-spin"></i>';}
if(autoscroll == 'false'){button_name = 'Load More'};
//append data returned to bottom of existing data
$('#load_data_message').html("<div id='please_wait' class='form-row text-center'>\
<div class='col-12'><button type='button' class='btn btn-warning'>\
"+button_name+"</button>\
<label style='cursor:pointer;'><input id='autoscroll' type='checkbox' name='autoscroll' value='true' "+checked+"\
style='transform:scale(2.0);margin-left:10px;margin-top:15px;cursor:pointer;'> Autoscroll</label><br></div></div>");
action = "inactive";
//recursive part - keep loading data until bottom of screen reached, stop when reached, or when end of data
start = start + limit;
console.log(start);
if(loads>=limit){
if($("#load_data").height() < $(window).height()){load_data(limit,start,search,tag);}
}
}
});
}
I do an initial load of the listing on page load with:
//for initial loading of data to the bottom of page (through recursive load_data function
if(action == 'inactive') {
action = 'active';
load_data(limit, start,search, tag);
}
Then if I want to initiate an auto/infinite scroll, I click the checkbox which initiates the code below. However, the "start" value is "0", where it should have been affected by the Ajax recursive function previously, and start at "15" instead. I get a repeat of previously posted data, which is not wanted.
//auto scroll checkbox clicked, putting into autoload/autoscroll mode
$(document).on("change", "#autoscroll", function(){
autoscroll = this.checked;
if(autoscroll == true){checked = 'checked';}else{checked = '';}
console.log(start);
load_data(limit, start, search, tag);
});
Then auto/infinite scroll works as follows. The "start" variable is continually updated successfully, but probably within the loop, rather than the recursive Ajax part.
//autoload portion. when scrolling reaches bottom of screen, triggers another load of data
$(window).scroll(function(){
if(autoscroll == true){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive' && button_name != 'End of Data'){
action = 'active';
start = start + limit;
//load_data(limit, start, search, tag);
setTimeout(function(){
load_data(limit, start, search, tag);
}, 500);
console.log('scroll function called!');
}
}
});
Bottom line question - I would like to use the global variable "start" and have it changed by the recursive function's Ajax success function. How can this be achieved?
You have not mentioned what your 'data' response looks like in your ajax call.
I tried a response string that looked like this:
<div class='card-header'>hello</div>
<div class='card-header'>world</div>
<div class='card-header'>foo</div>
<div class='card-header'>bar</div>
<div class='card-header'>howdy</div>
In this case, loads = $(data).find('.card-header').length does not provide a length of 5. If loads is only what you loaded in that specific ajax call, then you need $(data).length. Then, the console log for start in the ajax call gets incremented.
Note: Jquery $.find works on a DOM tree. $(data) returns an array of individual nodes, and $(data).length will return the pieces of data returned.
The "loads = $(data).find('.card-header').length" does count the number of class='card-header' instances, contrary to what user2137480 has mentioned above, and everything does increment properly. The issue was that the "start" variable outside the Ajax success function was not being updated as the "load_data" function was called recursively.
Found a clumsy way to make this work. I used a session storage variable, "sessionStorage.start" that gets affected within the Ajax success function, even at recursive levels. Seems like session variables scopes are truly "global"! Then this sessionStorage.start variable is use elsewhere in the code to update the global "start" variable. This value is then maintained consistently throughout the code. Just have to remember that the session variables are text and must be converted to numbers (for this application anyways). See below if you are interested:
//****************************************************************
// Loading questions and answers listings
//****************************************************************
var limit = 5;//number of records to autoload each time
sessionStorage.start = 0;
var start = 0;//start at record 0
sessionStorage.start = start;
sessionStorage.scroll_function_enable = 'false';
var action = 'inactive';//initial status to get initial load
var autoscroll = 'false';//check box to engage auto scroll or keep manual load more
var checked = '';//check box value for autoscroll
function load_data(limit, start, search, tag){//recursive function for auto loading
console.log('load data begin');
console.log('recursive start: ' + start);
sessionStorage.scroll_function_enable = 'false';
search = $('#search').val();
var loads;
$.ajax({
url:"/modules/posts/questions_all_autoscroll_fetchdata.php",
method:"POST",
data:{limit:limit, start:start, search:search, tag:tag},
cache:false,
success:function(data){
$('#load_data_message').show();//bring loading button back once load successful.
//It is removed during tag click search to avoid glitchy appearance of button showing at top left briefly.
$('#load_data').append(data);
//checks if quantity "limit" amount loaded. If not, that means end of data reached.
//Each data piece has id="container", so counting them tells how many data pieces returned in "loads"
loads = $(data).find('.card-header').length;
//alert(loads);
if(loads<limit){button_name = 'End of Data';}else{button_name='Loading More <i class="fas fa-spinner fa-lg fa-spin"></i>';}
if(autoscroll == 'false'){button_name = 'Load More'};
//append data returned to bottom of existing data
$('#load_data_message').html("<div id='please_wait' class='form-row text-center'>\
<div class='col-12'><button id='load_button' type='button' class='btn btn-warning'>\
"+button_name+"</button>\
<label style='cursor:pointer;'><input id='autoscroll' type='checkbox' name='autoscroll' value='true' "+checked+"\
style='transform:scale(2.0);margin-left:10px;margin-top:15px;cursor:pointer;'> Autoscroll</label><br></div></div>");
action = "inactive";
//recursive part - keep loading data until bottom of screen reached, stop when reached, or when end of data
start = start + limit;
sessionStorage.start = start;//needed because recursive routine does not update the global "start" variable. Needed to pass value outside of recursive routine
console.log('recursive end: '+start);
if(loads>=limit){
if($("#load_data").height() < $(window).height())
{
load_data(limit,start,search,tag);
}else
sessionStorage.scroll_function_enable = 'true';
}
}
});
}
//for initial loading of data to the bottom of page (through recursive load_data function
if(action == 'inactive') {
action = 'active';
load_data(limit, start,search, tag);
start = Number(sessionStorage.start);//to get recursive value of start, otherwise will not retain its value
}
//auto scroll checkbox clicked, putting into autoload/autoscroll mode
$(document).on("change", "#autoscroll", function(){
autoscroll = this.checked;
if(autoscroll == true){checked = 'checked';}else{checked = '';}
start = Number(sessionStorage.start);//to get recursive value of start, otherwise will not retain its value
console.log('autoscroll start: ' + start);
load_data(limit, start, search, tag);
start = Number(sessionStorage.start);//to get recursive value of start, otherwise will not retain its value
});
//autoload portion. when scrolling reaches bottom of screen, triggers another load of data
$(window).scroll(function(){
if(autoscroll == true){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive' && button_name != 'End of Data' && sessionStorage.scroll_function_enable == 'true'){
action = 'active';
start = Number(sessionStorage.start);//to get number where other processes have left off
console.log('scroll start: ' + start);
//load_data(limit, start, search, tag);
setTimeout(function(){
load_data(limit, start, search, tag);
}, 500);
start = Number(sessionStorage.start);//to get recursive value of start, otherwise will not retain its value
}
}
});

I'm having problem on auto refreshing a content in a web page

I'm creating a webpage that will automatically refresh a content to always get the latest data in the database. This is my code in Javascript.
setInterval(function() {
$("#status").load('refresh.php');
},1000);
In my javascript, I'm automatically refreshing the #status with refresh.php every second.
But when I inspect the element of my webpage and click on the network. It is also requesting(spamming) the refresh.php every second which is I think a bad practice.
Can you help me how to fixed this? Or can you suggest better ajax code to auto refresh a content without requesting the php file too much?
You should probably use a websocket for this, get the latest status as data from the server and then change only that section of the page using javascript
This code will be request refresh.php later at timeouts.min every time when new (requested) value of #status is equal to current. If values are different, next timeout will be timeouts.min again.
var timeouts={
min:1000, // min await timeout = 1s
max:16000 // max await timeout = 16s
};
var currentTo = timeouts.min;
function setAutoRefresh( to ){
setTimeout( function() {
var current = $("#status").text();// or .html()
$("#status").load('refresh.php', function() {
// if we are load a new value
if( current !== $("#status").text()) {
currentTo = timeouts.min;
// if loaded value are same to current
} else {
currentTo += timeouts.min; // or currentTo *= 2; for example
if( currentTo > timeouts.max ){
currentTo = timeouts.max;
}
}
console.log('Next #status refresh after ' + currentTo + 'ms');
// Set a new timeout
setAutoRefresh( currentTo );
});
}, to);
}
// Set the first timeout
setAutoRefresh( timeouts.min );

Javascript style type

I would like to implement it in a way where when the user has visited my page for the first time.
They will have a pop up appearing like a forum message " Hi , you've just visited our forum "
So when the second time the same user visit , the pop up will disappear .
Here's my code I'm working on :
var beenherecookie = 'FE44been644';
var beenherebegin = document.cookie.indexOf(beenherecookie);
if (beenherebegin > -1){
//Want to implement the code of when user enter first time , "style="display:none;"
else{
function setTimeout("style="display:block;", 60000 * 10); ; //set to 1000 X number of desired delay seconds. So 2 minutes (120 seconds) is 120 X 1000 =
120000
WriteCookie("FE44been644","yes");}
Here's my HTML code for the style::
style="javascript:meh(the function of the style which changes)"
So here's the situation :
When the user visit the website for the first time,
The javascript function meh would be style="display:none"
If the user has entered the website previously
The javascript function meh would be style="display:block"
I need some favors thanks in advance
There are several ways you can implement the scenario..
declare your meh function
var meh = function(){}
if (beenherebegin > -1){
meh = function(){
document.getElementById('popupID').style.display='none';
}
}
else{
meh = function(){
document.getElementById('popupID').style.display='block';
}
}
EDIT
var isFirstTime = false;
var popupHandler = function(firstTime){
if(firstTime){
return "block";
}
else{
return "none";
}
}
if (beenherebegin > -1){
isFirstTime = false;
}
else{
isFirstTime = true;
}
document.getElementById('popupID').style.display= popupHandler(isFirstTime);
Hello,
Once you use the cookie profiling to identify if the user has visited before. You can use document.getElementById.show() and document.getElementById.hide() methods to achieve what you are trying to do. There would be a div element enclosing the popup code, so you can use that. Please tell me if this helps or not. Additionally you can also use jquery methods for show/hide.
Thank You

Disappearing Menu Commands After User Input in Tampermonkey

Tampermonkey is an extension for Google Chrome that attempts to emulate the functionality of Greasemonkey. To be clear, I got my script to work in Chrome and the default JavaScript changes to show up. I wanted to test the menu commands, however, and entered a 6-digit hex color code after clicking on the command in the Tampermonkey menu. I reloaded the page, and the commands disappeared from the menu! My script was still there (and the checkbox was ticked).
No matter what I did or what code I changed, I could never emulate this initial functionality after that user-defined input was set. This leads me to believe that there's some persistent data that I can't delete that's causing my script to fail prematurely. NOTE: This exact script works perfectly and without errors in Firefox.
This is obviously not a Tampermonkey forum, but people here seem very knowledgeable about cross-platform compatility. I didn't hear a single peep from the Chrome console after all of the changes below, and I'm really just out of ideas at this point. Here are some things I've tried (with no success). Any console errors are listed:
Changing jQuery version from 1.5.1 to 1.3.2
Calling localStorage.getItem('prevoColor') from console after page load (both values null)
Changing client-side storage from localStorage to get/setValue
Calling GM_getValue from the console = ReferenceError: GM_getValue is not defined
Deleting localStorage entries for veekun.com in Chrome options
Refreshing, Re-installing the script, and restarting the browser more times than I can count
Repeating all of the above commands using Firebug Lite (bookmarklet)
Here's the code I was using:
// ==UserScript==
// #name Veekun Comparison Highlighter
// #namespace tag://veekun
// #description Highlights moves exclusive to pre-evolutions on veekun.com's family comparison pages (user-defined colors available)
// #include http://veekun.com/dex/gadgets/*
// #author Matthew Ammann
// #version 1.0.3
// #date 3/11/11
// #require http://sizzlemctwizzle.com/updater.php?id=98824
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
/*
Goal: Change checkmark color & move name to user-specified color on family comparison pages if
[DONE] Baby poke has a LEVEL-UP move unlearned by any evolutions
[DONE] a) Make sure move is not a TM or tutor move
[DONE] Any other mid-evolution has a move unlearnable by a final evo (Caterpie, Weedle families)
[DONE] a) Make sure move is not a TM or tutor move
[DONE] Any pre-evo has a TUTOR move unlearned by any evo (Murkrow in HG/SS)
[] Implement auto-update after uploading to userscripts.org
Credits: Brock Adams, for helping with Chrome compatibility
Metalkid, for the jQuery consult
*/
var isLevelupMove = false;
var isTutorMove = false;
var isTM = false;
var TMhead = $('#moves\\:machine');
var hasSecondEvo = false;
var hasFinalEvo1 = false;
var hasFinalEvo2 = false;
var header = $('.header-row').eq(1);
var TMmoves = new Array();
//This section deals with the user-defined colors
GM_registerMenuCommand("Color for pre-evolutionary-only moves", prevoColorPrompt)
GM_registerMenuCommand("Color for first evolution-only moves", evoColorPrompt)
var prevoColor = GM_getValue('prevoColor', '#FF0000');
var evoColor = GM_getValue('evoColor', '#339900');
function prevoColorPrompt()
{
var input = prompt("Please enter a desired 6-digit hex color-code for pre-evolutionary pokemon:")
GM_setValue('prevoColor', '#'+input);
}
function evoColorPrompt()
{
var input = prompt("Please enter the desired 6-digit hex color-code for first-evolution pokemon:")
GM_setValue('evoColor', '#'+input);
}
//This loop tests each 'th' element in a sample header row, determining how many Evos are currently present in the chart.
$('.header-row').eq(1).find('th').each(function(index)
{
if($(this).find('a').length != 0)
{
switch(index)
{
case 2:
hasSecondEvo = true;
break;
case 3:
hasFinalEvo1 = true;
break;
case 4:
hasFinalEvo2 = true;
break;
}
}
});
//All 'tr' siblings are TM moves, since it's the last section on the page
//This array puts only the names of the available TMs into the TMmoves array
TMhead.nextAll().each(function(index)
{
TMmoves.push($(this).children(":first").find('a').eq(0).html());
});
$('tr').each(function(index)
{
var moveName = $(this).children(":first").find('a').eq(0).html();
moveName = $.trim(moveName);
switch($(this).attr('id'))
{
case 'moves:level-up':
isLevelupMove = true;
break;
case 'moves:egg':
isLevelupMove = false;
break;
case 'moves:tutor':
isTutorMove = true;
case 'moves:machine':
isTM = true;
}
if(isLevelupMove || isTutorMove)
{
var babyMoveCell = $(this).find('td').eq(0);
babyMoveText = $.trim(babyMoveCell.html());
secondEvoCell = babyMoveCell.next();
secondEvoText = $.trim(secondEvoCell.html());
finalEvo1Cell = secondEvoCell.next();
finalEvo1Text = $.trim(finalEvo1Cell.html());
finalEvo2Cell = finalEvo1Cell.next();
finalEvo2Text = $.trim(finalEvo2Cell.html());
//This checks if evolutions have checkmarks
if(babyMoveText.length > 0)
{
if(hasSecondEvo && secondEvoText.length == 0 || hasFinalEvo1 && finalEvo1Text.length == 0 ||
hasFinalEvo2 && finalEvo2Text.length == 0)
{
//See if the move is a TM before proceeding
var tm = tmCheck(moveName);
if(!tm)
{
if(secondEvoText.length > 0)
{
babyMoveCell.css("color", evoColor);
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor); //highlights move name
}
else
{
babyMoveCell.css("color", prevoColor);
babyMoveCell.prev().find('a').eq(0).css("color", prevoColor);
}
}
}
}
else if(secondEvoText.length > 0)
{
if(hasFinalEvo1 && finalEvo1Text.length == 0 || hasFinalEvo2 && finalEvo2Text.length == 0)
{
var tm = tmCheck(moveName);
if(!tm)
{
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor);
}
}
}
}
});
function tmCheck(input)
{
var isTM = false;
//Iterate through TMmoves array to see if the input matches any entries
for(var i = 0; i < TMmoves.length; i++)
{
if(input == TMmoves[i])
{
isTM = true;
break;
}
}
if(isTM == true)
return true;
else
return false;
}
//alert("evoColor: " + localStorage.getItem('evoColor') + ". prevoColor: " + localStorage.getItem('prevoColor'));
Any ideas as to why this is happening?
EDIT: I messaged sizzlemctwizzle about this problem, and this was his reply: "Tampermonkey’s #require implementation is incorrect. It downloads my updater far too often so I have banned it from using my updater via browser sniffing. My server just can’t handle the traffic it brings. The script it is downloading from my server shouldn’t have any actual code in it. Since it is causing errors with in your script I would guess Tampermonkey isn’t passing the User Agent header when it does these requests. I’m never tested my updater in Chrome so I have no idea why it breaks. Perhaps you could try and install NinjaKit instead."
What URL are you testing this on? I tested on http://veekun.com/dex/gadgets/stat_calculator.
Anyway, the script behavior, vis à vis the menu commands did seem erratic with Tampermonkey. I couldn't really tell / didn't really check if the rest of the script was working as it should.
The culprit seems to be the sizzlemctwizzle.com update check. Removing its // #require made the menu stable. Putting that directive back, broke the script again.
I've never been a fan of that update checker, so I'm not going to dive into why it appears to be breaking the Tampermonkey instance of this script. (That would be another question -- and one probably best directed at the 2 responsible developers.)
For now, suggest you just delete it. Your users will check for updates as needed :) .

Splash Page Video (jQuery Hide) Reveal Index Underneath Issue

I need to have a splash page, but I don't want to make it my index, so I am using this solution.
I am using this technique:
http://jsfiddle.net/JjvzT/
on this page:
http://www.kineticoriginsofrhythm.com/
But I cant get the "Enter" button to reveal the index page below. Any Suggestions? It just flickers and jumps back to the Video Splash Page.
Also whats the js cookie code that makes it only appear once per day?
Thank You Very Much.
Also, if you can save your "anti-Splash" debates for another time that would be great. Client "MUST HAVE" this splash page. Not my idea.
Change the href attribute for your "Enter" anchor to "#". Right now you are redirecting them to the same page after hiding the splash, which is forcing them to load the page in its initial state again.
EDIT: For the cookie,
jQuery(function(){
if(document.cookie.indexOf("firstvisit") != -1){
$("#splash").hide();
$("#container-index").show();
}
else{
$("#splash span").click(function() {
$("#splash").hide();
$("#container-index").show();
var expireDate = new Date();
/* sets expire date to current date + 1 day */
expireDate.setDate(expireDate.getDate() + 1);
var newCookie = "firstvisit=0;expires=" + expireDate.toUTCString();
document.cookie = newCookie;
});
}
});
Caveat: I haven't tested this. See here for more on JavaScript and cookies: http://www.w3schools.com/JS/js_cookies.asp
I took ZDYN's answer and created splash.js, which can simply be added to your splash page (not a hidden div) and to the page that you want to redirect from, ie. index.html or something.
Anyway, here's the commented, working code:
/*
1. Create a separate html page to be the splash page
2. Out a referrence to this script in the splash page
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
3. Put a reference to this script in every page that you want to have the splash page appear on
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
4. Set the "splashPageName" below to the file name of the splash page
5. Set the date variables below
*/
var splashPageName = "splash.html";
var endSplashDate = new Date("12/7/2011");
var expireCookieDate = new Date();
(function() {
var url = window.location.toString();
if (url.toLowerCase().indexOf(splashPageName) >= 0) {
/* sets expire date to date + 1 day */
expireCookieDate.setDate(expireCookieDate.getDate() + 1);
var newCookie = splashPageName + "=0;expires=" + expireCookieDate.toUTCString();
document.cookie = newCookie;
}
else {
if (document.cookie.indexOf(splashPageName) != -1) {
//stay here, they've already seen the splash page
}
else {
var today = new Date();
if (endSplashDate > today) {
window.location = splashPageName;
}
}
}
} ());
Try this
$(document).ready(function(){
$("#splash").click(function() {
$(this).hide();
$("#container-index").show();
});
});

Categories

Resources