Skip to content Skip to sidebar Skip to footer

Jquery Cannot Assign To A Function Result

I am getting the error in the title above in the following code: $j('.table').delegate('td','click', function(e) { //alert($j(this).parent().css('background-color'));

Solution 1:

There are 2 issues with your question: first one is already answered by @Mike Vranckx, the correct usage of .css() setter is passing a second argument to set as value.

The other problem is that your condition will never be true, I'll address it in this answer. If you fix it in the way I suggest, you won't be needing .css().


Computed CSS values, which are returned from getComputedStyle/jQuery's .css(), are not exactly what you've authored in your code -- they suffer transformations when parsed into the CSSOM.

For instance, in Chrome:

body { background-color: transparent; }

console.log( $('body').css('background-color') ); //returns "rgba(0, 0, 0, 0)"

See for yourself.

That's why your $(...).('background-color') == 'transparent' condition is always false.


The most clean and cross-browser solution is to apply styling with classes (.addClass(), removeClass(), toggleClass()) and do conditional checks with .hasClass().

In your case though, .toggleClass should suffice. Here's a simple way to write your logic (fiddle):

$j(".table").on('click', 'td', function() {
    $j(this).parent().toggleClass('bg-gray');
});

.bg-gray {
    background: #eee;
}

Solution 2:

To set / change the background-color property, you need to pass it as a second argument:

$j(this).parent().css('background-color', '#eee');

Solution 3:

While compare using background color better to use rgba like this

$j(this).parent().css('background-color', 'rgb(0,0,0)');

Solution 4:

It would be cleaner, faster, and easier to modify to use a CSS class :

.tabletd { background-color: transparent; }
.foo { background-color: #EEE; }

And

$j( '.table' ).delegate( 'td', 'click', function() {
    $( this ).toggleClass( 'foo' );
});

Also avoid using reserved words like "table" for class names, it's confusing.

Post a Comment for "Jquery Cannot Assign To A Function Result"