Skip to main content

Bug Tracker

Side navigation

#4388 closed bug (fixed)

Opened March 19, 2009 08:38PM UTC

Closed September 28, 2010 09:59PM UTC

.css(name, somefunc()) and .attr(name, somefunc()) cause fatal js errors when somefunc() returns undefined

Reported by: dantman Owned by:
Priority: major Milestone: 1.4.3
Component: attributes Version: 1.4.2
Keywords: Cc:
Blocked by: Blocking:

When dealing with a function that returns data and using that data to set a css value using this very common pattern to set css will cause fatal errors that stop the rest of the script from running if you try to do any chaining.

$(someNode).css(name, someGetFunc());

While you could say that you could use || to change it from undefined to an empty string that causes issues with the fact that 0 is also caught by || and 0 and "" do not have the same meaning in css, in fact if you try that on opacity you will end up unsetting the opacity instead of making it transparent.

This is a common pattern which when read by a programmer looks like you are trying to set css, but depending on the result of someGetFunc jQuery may treat this as a css get instead of a set like it is meant to be.

This causes bigger issues when you try to chain the .css, which is of course one of jQuery's key philosophies.

$(someNode).css(name, someFunc()).text(someText);

If someFunc() returns undefined .css will return a string instead of the chain, this will cause a fatal error that stops the rest of the script from working because .text (or any other jQuery method for that matter) does not exist on string.

This can be fixed by using an arguments.length > 1 approach rather than checking for undefined.

There are no properties expected after the value so there is no worry about those.

As for people's understanding of things. I have no doubt the common users of jQuery consider undefined to have the same meanings as "" when it comes to what happens when used on css.

Attachments (0)
Change History (3)

Changed March 21, 2009 01:49AM UTC by dmethvin comment:1

Yeah, I think this case was fixed for non-function values in 1.3.x so the function case should be fixed as well.

Changed June 20, 2010 08:26PM UTC by dmethvin comment:2

component: coreattributes

So to be clear, if the func returns undefined the .css(name, undefined) or .attr(name, undefined) should do nothing and return the jQuery object.

Changed September 28, 2010 09:59PM UTC by john comment:3

resolution: → fixed
status: newclosed