0

I want to change two properties of a css, One property Value I want to modify using function call and other one is direct property assigning. I want to add background image at run time and setting property no repeat as well. Following two functions i came to know:

$(selector).css(property,function(index,currentvalue)) for changing value by function call and   other one is :-
$(selector).css({property:value, property:value, ...}) for assigning property.

Here I have two properties One is by function call and other one is direct property. I tried following code:

$('.xl21684').css('background-image', function () {
return 'url(' + imgs[parseInt(this.innerHTML)] + ')'
})
 $('.xl21684').css({background-repeat: no-repeat}) 

But it's not working at all.

5
  • What error messages do you have in the console? (the second on will give you a syntax error) Commented May 13, 2014 at 11:43
  • {background-repeat: no-repeat} is a syntax error. Try { "background-repeat": "no-repeat" } instead, or pass two strings to css() instead of an object. Commented May 13, 2014 at 11:43
  • $('.xl21684').css({ 'background-repeat': 'no-repeat' }) Commented May 13, 2014 at 11:43
  • need to add some quotes on keys and values, Commented May 13, 2014 at 11:44
  • Is it okey to modify same css multiple times?? Commented May 13, 2014 at 11:47

2 Answers 2

3

If you would like to go your own way then don't forget to quote the property and value for proper result as @Cerbrus said:

('.xl21684').css({'background-repeat': 'no-repeat'});

But you can try just once too:

$('.xl21684').css('background', function () {
return 'url(' + imgs[parseInt(this.innerHTML)] + ') no-repeat';
});

As per your comment you can use background shorthand property like below:

background: [background-color] [background-image] [background-repeat] [background-attachment] [background-position];
Sign up to request clarification or add additional context in comments.

2 Comments

@C-link, What if I want to do background-position:center ?
...no-repeat center';
1

The first .css() seems to be fine. The second one just needs some quotes:

$('.xl21684').css({"background-repeat": "no-repeat"});
//                 ^                 ^  ^         ^

That should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.