April 5, 2012

added a css background, how to entirely remove it

Question by sameold

I’m using the jquery .css property to add a background

myobj.css('background', '#AE0000');

This results in this style html being added to the markup

style="background: none repeat scroll 0% 0% rgb(174, 0, 0);"

Later on, I want to remove this background. I thought that setting css background to white myobj.css('background', '#FFFFFF'); would work, but unfortunately, this creates problems because the div has white background as opposed to nothing.

style="background: none repeat scroll 0% 0% rgb(255, 255, 255);"

Is there a similar way with jquery to entirely remove the background property of the CSS? like style=""

Answer by SiGanteng

Short Answer

myobj.css('backgroundColor', 'transparent');

Long Answer

I’d suggest for better maintainability, use css classes for things like this:

.active { background:#AE00000 }

then in your javascript

myobj.addClass('active');

to toggle off

myobj.removeClass('active');

This has the benefit of you not having to worry about changing the css value (if you use css()) everytime there’s change in your design or if you need to add more markup to that particular element.

For example, in the end you need to use background, font-size and color, in your js:

myobj.css({'background':'#aaa', 'font-size':'15px', 'color':'red'});

Then everytime you need to toggle off:

myobj.css({'background':'none', 'font-size':defaultSize + 'px', 'color':'black'});

Not only it’s error prone, but more difficult to maintain, if you use css:

.active { background:#AE00000; font-size:15px; color:red }

then in your javascript

myobj.addClass('active');

to toggle off

myobj.removeClass('active');

Answer by Starx

I would say, this will be a good way

myobj.css({
  'background': 'none', //remove all the background property
  'backgroundColor': '#FFF' //then only set the background color property
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!