Sysadmin and coding ignoramus tries to make a simple job page. It has a simple javascript function:
function run(job){
var ok = confirm("Are you sure?");
if(ok == true){
location = 'job.php?op=' + job;
window.location.href = location;
} else {
window.location.reload();
}
}
Called by a simple button:
<button style="color: red" onclick="run('test1');">Test1</button>
Keyword here being simple, like my understanding.
This worked in Chrome, but the button does nothing in Firefox (current versions of both browsers).
In trying to debug the script I added a simple alert line before the .href so the script reads like so:
function run(job){
var ok = confirm("Are you sure?");
if(ok == true){
location = 'job.php?op=' + job;
alert(location);
window.location.href = location;
} else {
window.location.reload();
}
}
… and then the script also worked in Firefox. I could see the alert appear briefly but it redirected instantly and disappeared in a fraction of a second. But in Chrome the popup persists so it’s not a good workaround, and the behaviour in Firefox is weird which tells me I’m doing-it-wrong.
My question is, why does the script behave inconsistently, and how can I avoid this behaviour so it is consistent in both browsers, and doesn’t require an additional alert()?
I think the issue might be that
locationis equivalent towindow.locationin that context. As you’ve not madelocationa local variable it will be an implied global.Rename your
locationvariable to something else or change it to a local variable by using ‘var location’: