Startec
Startec

Reputation: 13206

Why can't I set z-index through javascript with this function? (I know about camelcase)

Hi I want to change the z-index of my DOM element, so I used a function to do so. The function works for many properties but not z-index I am using Dev Tools and I can see that it is not even being set on the element and I do not know why.

Javascript:

    function setStyle(obj, propertyObj) {
        for (var property in obj) {
             if(obj.hasOwnProperty(property)){
                obj.style[property] = propertyObj[property];
            }
        }
    }
    var img = new Image();
    img.onload = function() {
       setStyle(this, {'zIndex':'-5'}) ;
    };
    img.src = 'test.jpg'

EDIT

Thanks for the good answers.

I was applying a border in the CSS code somewhere, so when I was looping through the objects properties border was being changed (but the same was not true for z-index).

Upvotes: 1

Views: 416

Answers (5)

Phil
Phil

Reputation: 164809

Might as well add yet another answer...

typeof obj.style === 'object' && Object.keys(propertyObj).forEach(function(key) {
    obj.style[key] = propertyObj[key];
});

IMO, Object.keys is superior to a for ... in loop as it is immune from Object prototype injection problems.

This also ensures that obj has a style property to begin with.

Update

Because some people are in to micro-optimisation, here it is without the Array.forEach

if (typeof obj.style === 'object') {
    var keys = Object.keys(propertyObj);
    for (var i = 0, l = keys.length; i < l; i++) {
        var key = keys[i];
        obj.style[key] = propertyObj[key];
    }
}

Upvotes: 0

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

You have 2 errors:

Your for in loop is looping through image object, not the properties object.

Your hasOwnProperty check is wrong (and unnecessary). You're checking to see if the obj has your style props, not whether the style object has the style props

It should read:

function setStyle(obj, propertyObj) {
    for (var property in propertyObj) {
        obj.style[property] = propertyObj[property];
    }
}

Upvotes: 0

EasyBB
EasyBB

Reputation: 6554

function setStyle(el, propertyObj) {
    for (var property in propertyObj){
          el.style[property] = propertyObj[property]
    }
 }

var img = new Image();
img.onload=function(){
   setStyle(this,{
      'zIndex':"999"
   });
};

Upvotes: 3

richie
richie

Reputation: 467

Setting a z-index with JS is as easy as this:

document.getElementById('IDHERE').style.zIndex = "2000";

Upvotes: 0

Jonathan Crowe
Jonathan Crowe

Reputation: 5803

if(obj.style && obj.style.hasOwnProperty(property)){
    obj.style[property] = propertyObj[property];
}

Upvotes: 0

Related Questions