cosmichero 2025 cosmichero 2025 - 6 months ago 9
Javascript Question

Javascript function not being able to call when sessionStorage value is compared

I am currently creating a flash gallery and every time a new button is pressed to see a new flash I would like to see the page reload to display a new ad. I've troubleshooted the problem with console.logs and have identified that the the sessionStorage variables are being set correctly but when it comes time to call the back/rand/next() functions it just stops in its tracks. Any tips will be of great value.

(Edit) It gets to console.log('Rand button ses received!');

CODE

var flashcon, test, temp;
var back, rand, next;

back = document.getElementById('back');
rand = document.getElementById('rand');
next = document.getElementById('next');
flashcon = document.getElementById('flashcon');

function init() {
if (sessionStorage.getItem('ref') == 1) {
console.log('Back button ses received!');
back();
} else if (sessionStorage.getItem('ref') == 2) {
console.log('Rand button ses received!');
rand();
} else if (sessionStorage.getItem('ref') == 3) {
console.log('Next button ses received!');
next();
} else {
console.log('First time or a reset');
}

// Scripts for the buttons
back.onclick = function () {
console.log('Back button pressed');
sessionStorage.setItem('ref', 1);
location.reload();
};
rand.onclick = function () {
console.log('Rand button pressed');
sessionStorage.setItem('ref', 2);
location.reload();
};
next.onclick = function () {
console.log('Next button pressed');
sessionStorage.setItem('ref', 3);
location.reload();
};
}

// What switches the flashs
function back() {
console.log('Back function');
sessionStorage.clear();
if (c == 0) {
c = paths.length;
}
c--;
displayFiles();
download();
}

function rand() {
console.log('Rand function');
sessionStorage.clear();
if (c == paths.length - 1) {
c = -1;
}
c++;
displayFiles();
download();
}

function next() {
console.log('Next function');
sessionStorage.clear();
temp = c;
while (c == temp) {
c = Math.floor(Math.random() * paths.length);
}
displayFiles();
download();
}

Answer

You have variables and functions over-riding each others' names.

back, next, rand are all function statements which get hoisted above the ... = document.getElementById('...') for the corresponding variable names.

Change the function names or change the element object names and then try again.

So basically turn this:

var back, rand, next;

back = document.getElementById('back');
rand = document.getElementById('rand');
next = document.getElementById('next');

into this:

var $back, $rand, $next;

$back = document.getElementById('back');
$rand = document.getElementById('rand');
$next = document.getElementById('next');

and of course edit the matching places following in the code so they point to the right variable.

Comments