What I'm trying to accomplish is the following.
I have a link on my website, however I want to change that link after every 5 visits or "page refreshes" by the user and have this loop.
So for example you visit my site and the download button links to a site called "www.site1.com". You refresh my site 5 times and the download button link changes to "www.site2.com". If you refresh it for a 6th time it goes back to the original.
I have not been able to find anything searching through forums that shows what i'm trying to accomplish here. I was just experimenting with a window.onload and setInterval function that changes the link every 5 seconds. Anyway to easily transition this from every 5 seconds to every 5 page visits?
window.onload = function() {
function changeURL(){
document.getElementById("link").href = "www.site1.com";
}
setInterval(changeURL, 5000);
}
You probably want to use JavaScript localStorage or sessionStorage for this. Below is an example of your code using localStorage
Example
window.onload = function()
{
if (localStorage.visits)
{
//If the value is in local storage increase it's value
localStorage.visits = Number(localStorage.visits) + 1;
}
else
{
//If the value isn't in local storage set it to 0
localStorage.visits = 0;
}
//Check if the number of visits is greater than 5 and set the link accordingly
if(localStorage.visits > 5)
{
document.getElementById("link").href = "www.site2.com";
}
else
{
document.getElementById("link").href = "www.site1.com";
}
}
This will only work if their browser supports localStorage. One thing to note as well, the value will not reset if they close the browser page. If you want it to reset when the page is closed, that's what sessionStorage is for.
One more thing to note: The user can clear localStorage by clearing the browser data. If you wanted something that would be even more persistent I don't believe there's a JavaScript only solution (feel free to correct me if I'm wrong about this!)
Related
I'm trying to calculate time when user is out of current tab.
if user is changes tab for more than 3 times, page should navigate to another page. OR if user changes tab for more than 10 seconds, page should navigate to another page.
So far i got this only:
$(window).blur(function() {
alert("You are navigating to other tabs or window. this is your first warning. Doing this again may cancel your current examination.");
});
i need something like this:
if (user changes tab){
//display warning
}
if(user changes tab for more than 3 times){
//navigate to another page
}
if(user changes tab for more than 10 seconds){
//navigate to another page
}
Answer originally came from: https://stackoverflow.com/a/1760268/680578
His code snippet can be found here: http://jsfiddle.net/meehanman/40edh944/
You are able to keep track of active/inactive tabs using jQuery's focus and blur. You should be able to use a global variable to keep track of the amount of times the user did not have their focus on your tab. Displaying your warning at the first time, and your second warning after 3 times.
Whether it has been 10 seconds can be done using a setInterval countdown for example. Which you can clear as soon as your user comes back to your tab.
var counter = 0;
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});
I created a little script to keep the PHP session active even if the user does not refresh the page.
Here is the Javascript I'm using via PHP to keep the session alive:
echo 'setInterval(function(){$.post(\'/refreshTheSession.php\');},90000);';
It works fine, but I've noticed that it will keep calling the refreshTheSession.php script even if the page is not in focus, which I don't want because it means someone can leave a tab open with that page and keep the session alive indefinitely even if they are on a different tab doing something else.
I only want the session to stay alive if the user is still actively on the page in question.
Is it possible to do that? If so, how can I modify my code above to do that?
You don't tell me what "did not work" exactly, but the second link I commented, the Page Visibility API, will definitely do what you're asking for, as can be seen in this working example:
function isDocumentVisible() {
return !(document.hidden || document.webkitHidden || document.msHidden);
}
// this is what you'd output via PHP:
setInterval(function(){
if (isDocumentVisible()) {
$.post('/refreshTheSession.php');}
}
, 90000);
// for the sake of demonstrating that this example is indeed working:
window.setInterval(function() {
console.log(isDocumentVisible() ? "document is visible, refresh session" : "document is not visible, don't refresh session");
}, 1000);
Update: Using document.setFocus(), it would look like this:
// this is what you'd output via PHP:
setInterval(function(){
if (document.hasFocus()) {
$.post('/refreshTheSession.php');}
}
, 90000);
// for the sake of demonstrating that this example is indeed working:
window.setInterval(function() {
console.log(document.hasFocus() ? "document has focus, refresh session" : "document does not have focus, don't refresh session");
}, 1000);
Click into and out of the result iframe to see the focus change.
My index.html page has a fancy animation to begin with it is essentially this code below...
$(document).ready(function() {
setTimeout(function() {
$("#loader-wrapper .loader-section, #textbit, #logo, #wrapper").hide("slow");
$("#wrapper").unwrap();
}, 11000);
});
..... so once this code has run its 11 seconds it all gets unwrapped and thats great... Problem is I have an a tag to get back to the index page at any time and I don't want people to have to wait for the intro animation to run before getting to the homepage every time....
I will not accept any answer that says .."do the animation on a seperate page" - the code has to be on the index page itself.
I was hoping there was some sort of jquery that will remove the code until the browser page has been refreshed, something like that.. Really appreciate any help here.
EDIT -- Getting some initial feedback that this is unclear ... in step for ...
User goes to index.html
the above code begins and lasts for 11 seconds.
then it gets unwrapped and disappears.
Seperatly while the user is enjoying the site they click on the "home" logo.
this takes people back to the index.html page
Unfortunately they have an 11 seconds wait every time and i want this to stop unless they refresh the browser or something.
You could use something like localStorage or cookies on your server side to manage this.
Here's the local storage example:
$(document).ready(function() {
if( !window.localStorage || !window.localStorage.getItem('hpAnim') ) {
setTimeout(function() {
$("#loader-wrapper .loader-section, #textbit, #logo, #wrapper").hide("slow");
$("#wrapper").unwrap();
}, 11000);
if( window.localStorage ) {
window.localStorage.setItem('hpAnim', true)
}
}
} );
So now (in IE8+) the second and future pageloads will not run the animation.
On the other hand if you've got a single page JavaScript app and you want it to re-run only after page refresh (as per comments on question), then you can skip local storage and simply set a global variable on window:
window.hasSeenAnimation = true
And then check that condition before running the animation again. After a page refresh that variable will be gone.
Set a cookie the 1st time that the users waits 11 secs
Can use https://github.com/carhartl/jquery-cookie or with native javascript code.
As well you can use a localstore var or url query
$(document).ready(function() {
if ($.cookie("index_viewed") == 1) {
return;
} else {
setTimeout(function() {
$("#loader-wrapper .loader-section, #textbit, #logo, #wrapper").hide("slow");
$("#wrapper").unwrap();
$.cookie("index_viewed", 1);
}, 11000);
}
});
You can set a $_GET variable and then check for this. If it's there, it must be an internal link so don't load the animation:
Home
<?php
if (!isset($_GET['noAnim']))
{
?>
<script>
// your animation script goes here....
</script>
<?php
}
?>
Assuming that you only want that animation to run at "startup" (when directly pointed) you could check the tab history count:
history.length
This will return a value higher than 1 only if any navigation took place on the tab (going to index from any other page).
This is not a perfect solution though:
Cross browser issues (some return 0, others 1)
Every navigation on this tab will produce history, hence, if you navigate to your website after checking any other page, history will return a value higher than the initial. (you can also check the document.referrer to ease this issue)
If you can't afford to skip the animation on those conditions you must persist the fact that the animation had already ran, and you should aim for Local Storage, for example (as mentioned earlier) http://www.w3schools.com/html/html5_webstorage.asp
My js app is an advent calendar where users can open a 'door' on or before today's so the div background image changes.
I would like to set up a cookie so when they return the following day the divs still have the background image in place.
I have set up the cookie and door open code but I'm not sure how to integrate the cookie into the door open function. Any help would be appreciated, many thanks.
Link to App: http://p3.katecooperuk.com
Door Open - select Random background image from Array:
$('.doors').click(function () {
if (today.getMonth() !== 11) {
return;
}
// Check if the date is tomorrow or later
if (+($(this).attr('id').split('dec')[1]) > day) {
// Show image telling user to come back
$(this).css('background-image', 'url(/images/come_back.png)');
return;
}
// Otherwise it is today or earlier
// Select Random Image
var doorImage = getRandomImage(calendarImg);
// Change background image of door that was clicked
$(this).css('background-image', doorImage);
});
Cookie
//on document ready, checks if the cookie is set, and if so, sets the background with it's value
$(function(){
if($.cookie('background-image') != null){
$(this).css('background-image', $.cookie('background-image'));
}
});
// Set cookie
$(function() {
$(this).css('background-image', doorImage);
$.cookie('background-image', doorImage);
});
W3Schools have a great newbie tutorial on cookies here
Basically, what you want to do is set the cookie value to the date it was created and whatever other parameters you want to set when the user comes back (such as the id's of the background images.) Then when the user enters your site you check to see if they have a cookie. If they do, check its date parameter. If it's not today (this is really easy to check with JavaScript) then use your extra parameters to set whatever background you want.
Make sure that whenever they change their backgrounds you reset your cookie data to the current backgrounds.
Hope this helps!
*
From you code, I'm having a hard time understanding exactly what it is you're trying to achieve. Also, I'm looking at your site and I don't see any saved cookies.. Try starting with a simple example, 1 door and 1 cookie. Then do a simple check to see if your cookie is working, for example, set a specific background when a cookie is detected and another if not. Once you successfully manage your cookie you can start making it more complex with more data in it.
I have a problem, what i cant solve yet. I have a popup page with a menu, and tabs, and there is a settings tab. On settings tab, i save some item to localstorage, one of them is notification_time for a desktop notification.
Note: i have no options page!
My extension has this popup window and a background page, its function is to alert user with a desktop notification. I show notification in every 5,10,30 minutes, 1,2 hours etc. And this time should be chooseable on popup pages's options menu. The problem is, if 5 minutes is saved, and when i update to 10 minutes for example, than background.html is not updating himself! I rewrited code almost 20 times, but couldnt find solution. Heres a code sample,and a printscreen to get clear about my problem.
popup:
$("#save_settings").click(function(){
var bgp = chrome.extension.getBackgroundPage();
localStorage.setItem("notifynumber",$("#notifynumber").val());
if($("#notify").attr('checked')){
localStorage.setItem('chbox','true');
} else {
localStorage.setItem('chbox','false');
}
if($("#notif_time_select :selected").val()!="default"){
bgp.setTime(parseInt($("#notif_time_select :selected").val()));
}
if($("#org_select :selected").val()!="default"){
localStorage.setItem('org',$("#org_select :selected").val().replace(/%20/g," "));
}
});
Note: save_settings is a button, on the tab there is a checkbox (if checked then notifications are allowed, else diabled). There are two html select tags, one for choosing some data (org = organisation), and one, for selecting time. "#notif_time_select" is the html select tag, where i choose 5,10,30 minutes etc...
So, whenever i click save button, i save checkbox state to localstorage,and i call one function from background page, to save time.
:bgp.setTime(parseInt($("#notif_time_select :selected").val()));
background page:
for saving time i use function setTime:
var time = 300000; // default
function setTime(time){
this.time=time;
console.log("time set to: "+this.time);
}
after, i use setInterval to show notification periodically
setInterval(function(){
howmanyOnline("notify",function(data){
if(data>localStorage.getItem("notifynumber")){
if (!window.webkitNotifications) { // check browser support
alert('Sorry , your browser does not support desktop notifications.');
}
notifyUser(data); // create the notification
}
if(localStorage.getItem('tweet')=='true'){
if(data>localStorage.getItem("notifynumber")){
sendTweet(data,localStorage.getItem('org'),localStorage.getItem('ck'),localStorage.getItem('cs'),localStorage.getItem('at'),localStorage.getItem('ats'));
}
}
});
},time);
The code inside setInterval works fine, the only problem is,that
},time);
is not updating well. If i change settings to show notifications in every 10 minutes, it stays on 5 minute. The only way is to restart the whole extension. How could i update setInterval's frequency without restarting the whole extension? Thanks Jim
What if i save notif_time to localStorage too, and in background, i set up a listener, to listen for localStorage changes. Is there a way to listen for a particular localStorage item changes?!
Right now, setInterval only runs once, when your application loads. If you want intervals to fire at a new time interval, you should use clearInterval and then make a new call to setInterval.
// set a new time, wipe out the old interval, and set a new interval
function setTime(t) {
window.time = t;
clearInterval(notifInterval);
notifInterval = setInterval(makeNotification, time);
}
// set first interval
notifInterval = setInterval(makeNotification, time);
function makeNotification() {
// do what you need to make a notification
}
Here, notifInterval is a reference to the interval, returned by setInterval, that is used to clear it.
The source code in your question is not completed, but I guess you called setInterval() and then modified window.time in the background page.
Your window.time is not an object but a number value, and setInterval() can't "see" changes of window.time after invocation.
Try this:
function onTimeout() {
// do your notification.
setTimeout(onTimeout, time);
}
setTimeout(onTimeout, time);