Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery backgroundColor animation

I have a DIV with a link and a SPAN.

When clicking the link, it renders a list of items by using AJAX. When an item is clicked, the content of the SPAN is changed.

I want to highlight this change, by setting the background-color of the DIV to green, and animating it back to white using jQuery.

  var originalColor = elementToUpdate.parentNode.style.backgroundColor;
  elementToUpdate.style.backgroundColor = 'green'; //lastSender.style.color;
  jQuery(elementToUpdate.id).animate({ backgroundColor: '#ffffff' }, 1000);

The background of the SPAN is changed to green on the 2nd line, but the 3rd line doesn't do anything. No errors, or changes what so ever...

Any ideas?


Edit: As noted by Ted Naleid in a comment below:

Also note that you have to have the color animations plugin installed for this to work (http://plugins.jquery.com/project/color), if you don't have it installed, jQuery can't animate colors, only numeric properties (at least as of 1.3.1).

like image 830
MartinHN Avatar asked Jan 08 '09 17:01

MartinHN


People also ask

Can you animate background color in jQuery?

The background color animate can be performed with the help of the animate() function or css() function. The background color animate is used to set the background color of the selected elements.

How can set background color in jQuery?

To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to check the present value of the property for the selected element.

How do you animate in jQuery?

The jQuery animate() method is used to create custom animations. Syntax: $(selector).animate({params},speed,callback);


1 Answers

You don't need the .id if you already have the element. Hand it directly to jQuery:

jQuery(elementToUpdate).animate({ backgroundColor: '#ffffff' }, 1000);

You don't get an error because elementToUpdate.id is a string, which jQuery (probably) interprets as a selector. It just happens to be a selector that doesn't select anything.

Alternatively, you can say this to make it a valid selector:

jQuery('#' + elementToUpdate.id).animate({ backgroundColor: '#ffffff' }, 1000);

But I think the first form is preferable since you already have the element itself.

like image 101
Adam Bellaire Avatar answered Sep 20 '22 18:09

Adam Bellaire