How to change css attribute of a class

Go To StackoverFlow.com

0

I have <span> inside a <div>, like so:

<div id="#mydiv">
<a href="#">Hello</a><span class="myImageArea"></span>
    <div class="someClass">
    </div>
</div>                          

With the following CSS:

.myImageArea {  
    background: url("../img/upArrow.png") no-repeat right 5px;
    display: inline-block;
    cursor: pointer;
}

I want to change the attribute background:url of class myImageArea

$('#mydiv').click(function() {
    //change the background image of the class
});

How can this be done?

2012-04-04 07:54
by user1184100


5

Within the click function you get a reference to the element you've clicked on, using jQuery's selectors, you can now search inside that for the span. Once you have that you can then change the CSS property 'background-image':

$('#myDiv').click(function() {
    $('.myImageArea', this).css('background-image', 'newimagepath.png');
});
2012-04-04 07:57
by cchana
Voted up. Please state reason for downvoting... - Marco Johannesen 2012-04-04 08:00
Thanks everyone. I want to have -> no-repeat scroll right 10px transparent with the image like .. 'background-image':'url("../img/xArrow.png") no-repeat scroll right 10px transparent' adding this won't work.. - user1184100 2012-04-04 08:08
You can define the other attributes separately in your style sheet, then when jQuery changes the background image, these styles will get applied automatically - cchana 2012-04-04 08:13


4

Even better, instead of setting the attribute directly you can add custom CSS class (for ex. myFancyBackground). To add the class use following:

$('#myDiv').click(function() {
    $('.myImageArea', this).addClass('myFancyBackground');
});

And in the css file you have:

.myFancyBackground {
  background-image:url('...');
}

So in future, if you like to change the background properties, like image, repeating ... you only have to change the CSS.

2012-04-04 08:08
by Goran Nastov
thank you goran. - user1184100 2012-04-04 08:16


2

$('#mydiv').click(function() {
   $(this).find('.myImageArea').css('background-image', 'url("/path/to/new/image.jpg")');
});
2012-04-04 07:56
by Andreas Wong


1

You can do this on the fly using the css() method in jQuery.

$('#mydiv').click(function(){
    $('.myImageArea', this).css({'background-image':'url(path/to/new/image.png)'});
});
2012-04-04 07:56
by Thomas Clayson
Ads