Possible Duplicate:
Using Javascript in CSS
is it possible to use javascript
codes in css background
?
mean something like this :
style="background:url(javascript:---javascript codes---);" does this syntax work or not?
thanks in advance
Possible Duplicate:
Using Javascript in CSS
is it possible to use javascript
codes in css background
?
mean something like this :
style="background:url(javascript:---javascript codes---);" does this syntax work or not?
thanks in advance
You cant use JavaScript inside CSS. But if you want to change the background image using JavaScript following line will work,
document.getElementById("<element ID>").style.backgroundImage = "url(<url of image>)";
You cannot use JavaScript in your CSS, but you can use JavaScript to set your CSS rules. For instance:
// Create CSS BackgroundImage Rule
var bg = "url('http://placekitten.com/200/300)";
// Apply Rule
document.getElementById("foo").style.backgroundImage = bg;
Additionally, there are a series of frameworks and tools that permit you to use functions and variables in CSS, such as SASS or LESS.
The closest you'll get to having JavaScript in your CSS would be something Dynamic Properties (introduced in IE5), which have very poor support cross-browser, and are no longer supported in modern versions of IE.
If you need to do a lot of modifications to your styles with JavaScript, by and large people are moving towards adopting frameworks to assist with that. For instance, one popular framework is jQuery, which permits things like:
$("#foo").css('background-color', 'red');
As well as mass-assignment through objects:
var color = "#ffe",
border = "5px solid #ccc";
$("#foo").css({ 'background-color': color, 'border-left': border });
Technically yes, with an expression:
background: expression(JS code resulting in a vali background image string here)
However I think it only works in IE and it's very bad practice because it may have to re-evaluate the code hundreds of times every second.
Instead, you should have a suitable default there, and then use JavaScript later on the page to change it.