0

Getting error in the following code:

var attribute=["position","top","bottom","left","right","zIndex"],
            prop=["fixed","0","0","0","0","-2"];

        for(var i=0;i<attribute.length;i++)
            video.style.attribute[i]=prop[i];

Error displayed by the console: Uncaught TypeError: Cannot set property '0' of undefined .

Please Help!

2 Answers2

1

This is a bad way of organizing attributes and properties, actually relations in generel:

var attribute=["position","top","bottom","left","right","zIndex"],
            prop=["fixed","0","0","0","0","-2"];

It is very difficult to maintain and expand upon. You should associate key and value:

var data = {
     "position" : "fixed"
    ,"top" : "0"
    ,"bottom" : "0"
    ,"left" : "0"
    ,"right" : "0"
    ,"zIndex" : "-2"
}

You should then be able to set the properties using 1 line of code:

for(key in data) video.style[key] = data[key];

Complete example:

var data = {
     "position" : "fixed"
    ,"top" : "0"
    ,"bottom" : "0"
    ,"left" : "0"
    ,"right" : "0"
    ,"zIndex" : "-2"
}
for(key in data) video.style[key] = data[key];
0

video.style.attribute tries to read a property called attribute which does not exist, so attribute[0] throws the observed error.

To set video.style.position = "fixed" you need to use [] notation in your loop:

video.style[attribute[i]] = prop[i];

i.e. video.style["position"] = "fixed"

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Could you tell me more about the [ ] notation. –  Nov 16 '14 at 20:49
  • See http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets - It's the way to access a property of an object when that property name is in a variable, such as your `attribute[i]` list. – Alex K. Nov 16 '14 at 20:51