Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Variable with .css() concatenation issue?

I am trying to change CSS of a button on blur. I suspect it might be a concatenation issue but am unable to figure out what I am doing wrong. Here is my code...

HTML

<input type="text" value="blue" id="textinput">
<button>Button</button>
<span id="color">red</span>

CSS

button {
 background-color:blue;
 background-image: -webkit-linear-gradient(top, white 0%, black 100%);    
}

jQuery

$("#textinput").blur(function () {
     setTimeout(function () {
          endColor = $("#textinput").val();
          $('button').css({ 
              'background-color' : endColor
              'background-image' : '-webkit-linear-gradient(top, #309ACB 0%,' + endColor + '100%)'       });
     }, 500);
});​

FIDDLE LINK

http://jsfiddle.net/krishollenbeck/p2jah/20/

It works fine when I remove the gradient CSS. So I am guessing I am concatenating the variable wrong. However I have tried it multiple ways but just can't seem to figure it out. It is probably something really obvious.

Also note. I am using webkit gradient so test in chrome or safari. Thanks in advance for the help.

like image 983
Kris Hollenbeck Avatar asked Dec 20 '22 16:12

Kris Hollenbeck


1 Answers

You are missing a whitespace between your variable holding the color and the percentage string.

'-webkit-linear-gradient(top, #309ACB 0%,' + endColor + ' 100%)'
                                                        ^
                                                        |
                                                        +-- Here

A good way to debug this kind of situations is to use console.log to see the result of the concatenated string. In this case, for example, you'd get red100% instead of red 100%.

An alternative, which imho, is less error-prone, is to use String.format(). This way, you can (more) clearly see if you are missing something:

'-webkit-linear-gradient(top, #309ACB 0%, {0} 100%)'.format(endColor)

Note that some browsers don't support this function, but you can use this pollyfill to define it.

like image 107
João Silva Avatar answered Dec 31 '22 11:12

João Silva