Run javascript once per session - javascript

I would like the code below to execute only once when the website first loads, as at the moment the script executes every time the index page loads and is therefore showing the div every time the user comes back to the index page from within the site.
NB. I only have the code on the index page.
It would be really helpful is somebody could show me the code I need to paste instead of this.
<script type="text/javascript">
function show(target) {
document.getElementById(target).style.display = 'block';
}
function hide(target) {
document.getElementById(target).style.display = 'none';
}
</script>

if ((typeof localStorage !== 'undefined') &&
(localStorage.getItem('yourCodeDescription') === null)) {
// Your code here
console.log('ok');
localStorage.setItem('yourCodeDescription', true);
}
Try something like this to make use of a localStorage.

Related

Unique jQuery popup issue

So I have to have a popup form display once per user session, the client wants it to popup after 10 seconds. If the user navigates to another page on the site, the form still needs to popup and not display after the user closes it on any other part of the site. Here is the jQuery I have written so far.
$(document).ready(function() {
sessionStorage.setItem('firstVisit', '1');
if (sessionStorage.getItem('firstVisit') === "1") {
setTimeout(function() {
$('.verif').fadeIn('fast');
}, 1000);
} else {
$('.verif').hide();
}
});
I have the form on each page and right now it just pops up all the time. Am I using the wrong method for the situation? All suggestions are welcome.
Note that the line 2 always sets firstVisit as '1' in session storage. This way, the expression for if will always be true and thus, user will always see the popup.
You need to get the item first, and check its value. Then if it doesn't exist, set it.
$(document).ready(function() {
var item = sessionStorage.getItem('firstVisit');
if (!item || item !== "1") {
setTimeout(function() {
$('.verif').fadeIn('fast');
}, 1000);
sessionStorage.setItem('firstVisit', '1');
} else {
$('.verif').hide();
}
});
Also, using sessionStorage is not a good idea as it is volatile across page refreshes. You, instead, may want to use localStorage for this as you mentioned that this needs to be done for any page.

Sometimes, jQuery only updates elements on first page load

I'm learning javascript by creating a program which requests an API and dispays various properties (price in this example) to html. I have a few questions about my code and some problems I've been facing.
1). I have a bunch of $.getJSON functions corresponding to each value that I want to retrieve. I put them all in a a single 2 min. timer. When the page FIRST loads, however, some of the html elements fail to load at all. But if I refresh the page, they sometimes do load. If I refresh again, they might not load at all again. Every time I refresh, there's like a 10% chance of that particular function not inserting the content in the element. If it does load and I leave the page open, it will correctly function (update its value and html element every 2 mins and add/remove the green and red classes). If it doesn't load and I leave the page open, it will correctly function in 2 mins when the 2nd api request is made. I have already tested that the variables have some value (are not null) before and after each $('#price').text('$' + price);.
Here's an example of a function that does that:
var tempPrice;
var myVar = setInterval(myTimer, 1200000);
myTimer();
function myTimer() {
$.getJSON(link, function (json) {
$.each(json, function (index, value) {
if (value.id == "price") {
var price = value.price_eur;
if (!tempPrice) {
$('#price').text('$' + price);
tempPrice = parseFloat(price);
}
if (parseFloat(price) !== tempPrice) {
$('#price').text('$' + price).removeClass();
if (parseFloat(price) > tempPrice) {
setTimeout(function () {
$('#price').addClass("green");
}, 1);
} else {
setTimeout(function () {
$('#price').addClass("red");
}, 1);
}
tempPrice = parseFloat(price);
}
}
});
});
// Many more $.getJSON functions below...
}
If I run this function alone on either jsfiddle or my dev server (flask), it works fine. It only breaks down when I use it in conjunction with more api requests. If I remember correctly, I didn't have this problem before when I used to have a separate timer for each $.getJSON function and put each in its own <script> tag directly in html.
2) I know I can loop through the json instead of using $.each. How else can I improve the code?
1
As for the problem you're having with the inconsistent behavior of the initial page loading, it's because you are executing JavaScript before giving the browser the time to load the page fully first. You can solve this simply by waiting for the page the load, and then executing your code.
Example in jQuery:
$(document).ready(function() {
// Page is loaded, execute code...
});
2
To help you improve the way you're handling the supplied JSON data, a sample of the data would be useful.

skip function if missing script

I am building within a content management system, so I have to get creative with load functions.
I have 2 scripts running on load. A random background image for the home page, and the navigation menu. I included both in a separate script that runs on load. The only page to get the background image is the home page. So on all the other pages that do not have the random home script linked, the script errors out and the menu does not load.
I would like the background image to execute first. A bad work around is to load the menu first, and let the random home script break on any sub pages but this is NOT ideal and I am hoping to find a solution.
I would like to load the image first, and then run the navigation script. And in the event that the image script is undefined, I would like it to skip, and execute the navigation script.
Here is my code:
function start() {
var randH = randomHome();
var undefined = false;
if (randH === undefined) {
loadNAV();
}
else {
randomHome();
loadNAV();
}
}
window.onload = start;
The 2 functions are linked in separate files and work just fine when listed like this:
function start() {
loadNAV();
randomHome();
}
window.onload = start;
But this leaves errors on sub pages that do not get the background image. So i am searching for a no error answer that loads the background image first, or skips it, and then the navigation.
Create an anonymous function that runs on load and checks for the existence of the start() function. If it exists, call it.
window.onload = function() {
if (start) {
start();
}
};
Remove the undefined = false line. undefined is a reserved keyword and already evaluates as "falsy" and what you've done will cause a lot of issues for anything else relying on the undefined keyword. Instead, change the if statement to use == instead of ===. == evaluates equality, === evaluates identity.
If you're trying to prevent the randomHome() script from running if it doesn't exist, the same code would be used inside the start() function.
function start() {
// only call randomHome function if it exists
if (randomHome) {
var home = randomHome();
// anything else to do with the homes goes here
}
// load the nav regardless of whether randomHome exists
loadNAV();
}
This is what ended up working. thanks all.
function start() {
if(window.randomHome == undefined )
{
loadNAV();
}
else {
randomHome();
loadNAV();
}
}
window.onload = start;

check json every second and refresh page when data changes

I want to refresh the whole page when javascript detects a change in json data.
Here is the code i am trying:
var previous = null;
var current = null;
setInterval(function(){
$.getJSON("https://www.mylivepolls.com/json.php?shortURL=0", function(json){
current = JSON.stringify(json);
if(previous && current && previous !== current){
console.log('refresh');
location.reload();
}
previous = current;
});
}, 1000);
When this code is executed, it does not refresh the page.
But when i try to open inspect element on that page, it refreshes!
please check if i am doing something wrong.
Possibly when your debugger has focus, 'location' is being scoped to the frame of the debugger. Try window.location.reload(), instead of simply location.reload().

How to make my function to be page specific or div id specific?

I am writing javascript to my web pages, but there is a number of functions and loops, that i think are running in all pages, so the first one is running and failing on the second page. Because of this, the javascript function on the second page is not running.
Can anyone give me an idea of how to create page-specific functions or check the availability of an id? I don't use any frameworks.
thanks in advance.
my javascript code is :
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num * 250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
alert("alert second page");
}
in this code, the alert message not working on second page. any idea?
If I understand you correctly, you have a javascript function, that you want to attach to an event from a specific div element in your page.
a) Include an event directly to you HTML page, something like this:
<div id="element" onclick="some_function();">Text is here</div>
b) Use a javascript function (add this code between <script> tag):
window.onload = function() {
document.getElementById("element").setAttribute("onclick", "some_function()")
}
The best way would be to only include those scripts on the pages which need them. Why waste time loading and parsing scripts you don't need?
If you must keep them on every page, put your functions in an if statement and check for something unique to the page that needs them (such as a form element or field ID).
Update
In response to your comment:
You have to code more defensively. You are attempting to make use of the magazine-brief and signup-link elements before you have made certain that they exist. Never trust that the proper element was returned - always check that it was before attempting to use that element.
I suggest checking your vars like so:
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined)
{
function animeYellowBar(num)
{
//...
}
}

Categories