Javascript-Setting background image of a DIV via a function and function parameter
Solution 1
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
Solution 2
From what I know, the correct syntax is:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}
So basically, getElementById(tabName).backgroundImage
and split the string like:
"cssInHere('and" + javascriptOutHere + "/cssAgain')";
jordan
Updated on December 05, 2020Comments
-
jordan over 3 years
I have the following HTML:
<div id="tab1" style="position:relative; background-image:url(buttons/off.png); <a href="javascript:ChangeBackgroundImageOfTab('tab1', 'on');"> <img id="DivBtn1" name="DivBtn1" src="buttons/text.png" > </a> </div>
and the following Javascript:
function ChangeBackgroungImageOfTab(tabName, imagePrefix) { document.getElementById(tabName).style.background-image= 'url("buttons/" + imagePrefix + ".png")'; }
The issue arises when i try to set the tabs background image via a call to getElementByID - I do now know how to create a dynamic URL that uses the parameter that was passed in, along with some other hard coded values. In this case, we are swapping the OFF background image with the ON background image.
How can i do this? Is there some way to use a javascript variable, assign the full path to it, then send it into the call as the background image path?
-
Sikshya Maharjan over 10 yearsWhy are the
"
being included within the string? And I hadn't seen until now, but you can't have-
in a property, or variable, name (it'll be interpreted as an operator), use camel-case:backgroundColor
. -
jordan over 10 yearscreating the string seperatly worked. putting it inline didnt work, but compiled and ran correctly with no errors. thanks for the help!
-
TyMayn over 10 yearsCool. Some people think that creating your string separate like this is creating more code. I find doing this helps with debugging, as I can then see exactly whats going to be assigned using the ol' console.log. :)
-
jordan over 10 years@TyMayn totally. i agree. so much easier for debugging, when you can just hover over a variable instead of typing it into the console or the immediate window.
-
saber tabatabaee yazdi over 7 yearsgetelementbyId doesnt need #divname only name of the id without #