Reputation: 39
I have two buttons that are meant to activate my JavaScript functions when clicked, but they don't seem to work. However, when I move my JavaScript function content outside the functions, they work correctly. So the buttons are definitely the problem.
JavaScript:
$(document).ready(function()
{
function recordjourney()
{
var journey = JSON.parse(localStorage.getItem('journey'))||[];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
function resetjourney()
{
localStorage.clear()
}
});
HTML:
<p><button name="record" type="button" onclick="recordjourney()">Record Journey</button</p>
<p><button name="reset" type="button" onclick="resetjourney()">Reset Journey</button></p>
Upvotes: 1
Views: 6019
Reputation: 50009
The buttons aren't the problem, you have a scope issue since the functions you are calling don't exist on the same level as the buttons.
You can fix that and make your code a bit cleaner by binding to your buttons inside the ready call like so
$(document).ready(function() {
$('[name="record"]').click(recordjourney);
$('[name="reset"]').click(resetjourney);
});
function recordjourney() {
var journey = JSON.parse(localStorage.getItem('journey')) || [];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
function resetjourney() {
localStorage.clear()
}
<p><button name="record" type="button">Record Journey</button</p>
<p><button name="reset" type="button">Reset Journey</button></p>
Fiddle here - http://jsfiddle.net/7eYNn/
Upvotes: 3
Reputation: 3381
Yeah, that's right. If you define a function inside a function, it will be private to that function. You need to create a global var
var recordjourney;
$(document).ready(function(){
...
recordjourney = {
var journey =
... etc
Although, of course, given that you are using JQuery I'd do
$(document).ready(function(){
...
$( 'button[name=record]' ).bind( function(){
//put your function here
})
and remove the ugly onclick="recordjourney from the button tags.
Upvotes: 0
Reputation: 13421
initialize your functions out of $(document).ready()
.
$(document).ready(function()
{
});
function resetjourney()
{
localStorage.clear()
}
function recordjourney()
{
var journey = JSON.parse(localStorage.getItem('journey'))||[];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
Upvotes: 0