0

is there any way to replace 255px from code below with variable width?

var width = $(".input-textbox").width();

     $("#txtTryContactMob").css('background', '#fff url(\"/img/erroricon.png\") 255px center no-repeat');

I have read a little about it and I don't want to use LESS css.

Thanks in advance.

3
  • 2
    '#fff url(\"/img/erroricon.png\") '+width+'px center no-repeat'? Have you tried string concatenation? Commented Feb 9, 2015 at 14:22
  • Yes but a different way :) looks like I made a mistake, will try your solution. Commented Feb 9, 2015 at 14:23
  • Note: You did not need to escape the double-quotes inside a single-quoted string Commented Feb 9, 2015 at 14:25

3 Answers 3

1

You can also separate the width from the rest of the CSS style by specifically targetting just the background-size style:

 var width = $(".input-textbox").width();
 $("#txtTryContactMob").css('background', '#fff url("/img/erroricon.png") 255px center no-repeat')
      .css('background-size', width);

Notes:

  • it does not need the px added when using a single CSS property.
  • You did not need to escape the double-quotes inside a single-quoted string
Sign up to request clarification or add additional context in comments.

Comments

1

you can use like this by simple concatenation

var customwidth = $(".input-textbox").width();
     $("#txtTryContactMob").css('background', '#fff url(\"/img/erroricon.png\") '+customwidth+'px center no-repeat');

Comments

1

To reply your question, "How to add variable to jquery css method?", maybe hash format css looks more expandable:

$("#txtTryContactMob").css({
  "background": '#fff url("/img/erroricon.png") center',
  "background-size": $(".input-textbox").width() + "px",
  "background-repeat": "no-repeat",
  "background-position": "center"
  // more attribute pairs
});

See http://www.w3schools.com/css/css_background.asp for more background details.

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.