soomro
soomro

Reputation: 171

Can't add property to object (Cannot set property of undefined)

I am having problems with adding properties to an object. I want it to, when you click like, it will create a new property inside the "scores"-object and then increment that value by one. But I am getting this error when doing this:

Uncaught TypeError: Cannot set property '(hex-code)' of undefined

HTML

<p style="display: inline;">Hex-code: </p>
<input id="demo" type="text">
<button onclick="generate()">Generate</button>

<div id="showcase" style="background: #FFF; width: 200px; height: 200px; margin: 20px; border-radius: 3px;"></div>

<button onclick="like()">Like</button>
<button onclick="dislike()">Dislike</button>

JAVASCRIPT

var result = document.getElementById('demo').innerHTML;
var hex;

var scores = {}

function generate () {
    var length = 3,
        charset = "ABCDEF0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    finalVal = "#" + retVal;
    document.getElementById('demo').value = finalVal;
    document.getElementById('showcase').style.backgroundColor = finalVal;
    return hex = retVal;
}

function like () {
    scores[hex] = 0;
    scores[hex] += 1;
    return generate();
}

Link to fiddle: https://jsfiddle.net/elliotsoomro/o0kuwc0d/4/

Upvotes: 0

Views: 1377

Answers (1)

baao
baao

Reputation: 73211

You have included your script in the <head> of your html, without wrapping it in window.onload. This will make this line fail

var result = document.getElementById('demo').innerHTML;

because the element isn't found at runtime, which further leads to score being never defined because of above breaking error.

See this updated fiddle with the working script beeing included in the html's <body>. Alternatively, you could just wrap the first part of your code within window.onload = function() {} or just put the

var result = document.getElementById('demo').innerHTML;

in your generate() function.

Upvotes: 3

Related Questions