A Zhang A Zhang - 5 months ago 26
Javascript Question

Javascript not working within HTML page

Hey so I have an HTML page with this part of javascript within it that updates local storage:

<script src="../../Website/json/modernizr.js" >
var button = document.getElementById("btnsave");

button.addEventListener("click", function(){
if (Modernizr.localstorage) {
// window.localStorage is available!
var drinksElement = document.getElementById("drinks");

for (var i = 0; i < drinksElement.length-1; i++) {
localStorage["box" + i] = drinksElement[i].value;
}
} else {
// no native support for HTML5 storage :(
}
});
</script>


But for some reason it's not doing what it's supposed to. The page loads up fine without any errors seen on the console. If I copy and paste this script into the developer console, then click the button to update local storage, local storage will update, but only once, then it seems to "forget" this javascript function. If I copy and paste this into console then type "button", It will show the button variable. I can keep typing "button" and it will keep showing the button variable until I click on the button and it updates the local storage. After that, calling button again returns a reference not defined error.

Thanks in advance, this has been troubling me for quite some time.

Answer

Your modernizr reference and the javascript code should be in different script tags.

<script src="../../Website/json/modernizr.js" ></script> 
<script> 
        var button = document.getElementById("btnsave");

        button.addEventListener("click", function(){
            if (Modernizr.localstorage) {
            // window.localStorage is available!
                var drinksElement = document.getElementById("drinks");

                for (var i = 0; i < drinksElement.length-1; i++) {
                    localStorage["box" + i] = drinksElement[i].value;
                }
            } else {
                // no native support for HTML5 storage :(
            }
        });        
</script> 

As per the spec - <script>,

If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.

Comments