Dan Lugg
Dan Lugg

Reputation: 20592

jQuery in IE8 .css() returning undefined for value

This seems to fail in IE8 (haven't tested 7, but surely it will fail too) The value in the function returns undefined. It works fine in Firefox:

$('selector').css('property', function(index, value){ alert(value); });

The actual code from my script is as follows:

$('.scrollBkg').css('background-position', function(index, value){
    var backgroundPosition = value.split(' ');
    return (parseFloat(backgroundPosition[0]) + (($(this).hasClass('scrollLeft') ? -1 : 1) * parseInt($(this).css('z-index'))) / 2) + 'px ' + backgroundPosition[1];
});

Why is it that value is undefined in IE? Rather, how can I make this work as expected?

Upvotes: 2

Views: 2924

Answers (3)

Dr.Molle
Dr.Molle

Reputation: 117334

In MSIE retrieve backgroundPositionY and backgroundPositionX instead of backgroundPosition

var backgroundPosition = (document.all && !window.opera)
                              ?[$(this).css('backgroundPositionX'),
                                $(this).css('backgroundPositionY')]
                              : value.split(' ');

Upvotes: 5

Lee
Lee

Reputation: 13542

according to the relevant section of the jquery documentation:

function(index, value): A function returning the value to set. Receives the index position of the element in the set and the old value as arguments.

So if there were no value previously set, I would expect that value might be undefined, or maybe null. I could see this behavior being different between browsers -- essentially, it's a question of what the browser's default value is for the css property you're working with. IE's default might be undefined, while firefox defaults to a more meaningful value.

Upvotes: 1

mahatmanich
mahatmanich

Reputation: 11023

I am not sure if that is your problem, but ... IE7 as well as 8 has issues with singel quotes for selector/id values, and might not find the respective DOM element.

Recently I just finished a jquery project very high on IE side and I switched all my ' quotes to " to make it work.

in your case try:

$("selector").css("property", function(index, value){ alert(value); });

So what I am suggesting is that IE never found your element and thus cannot append a new class to it, therefore "undefined"

For any css value in jquery I tend to use double quotes ... instead of single quotes.

Upvotes: 1

Related Questions