ReferanceError while executing script

1

The code below changes the innerHTML of a DIV and when I run the function item.Footer(); the javascript console tells me "ReferanceError 'item is not defined?"

 (function() {var item ={
	Name: "site-info"
	Html: "Powered by <a target='_blank' href='https://www.twitter.com/FRNathan13'></a>"
	Footer: function(){
		document.getElementById(item.Name).innerHTML=item.Html;
	}
 }
}
<div id="site-info"><button onclick="item.Footer();">MUDAR DIV!</button></div>
    
asked by anonymous 27.04.2015 / 17:02

1 answer

5

You are defining this object within a function. This makes the variable / object not accessible in the global scope in which the HTML runs. To solve this you can use window.item = {} but in this case you lose the reason to use (function(){...})(); ...

jsFIddle: link

It would be best to add an event dropper within that function instead of having onclick in HTML. Something like:

(function () {
    var item = {
        Name: "site-info",
        Html: "Powered by <a target='_blank' href='https://www.twitter.com/FRNathan13'></a>",
        Footer: function () {
            this.parentNode.innerHTML = item.Html;
        }
    }
    document.querySelector('#' + item.Name + ' button').addEventListener('click', item.Footer);
})();

jsFiddle: link

    
27.04.2015 / 17:51