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?
Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.
backgroundImage = "url('image. png')"; You need to put the relative path to the image from your web page's folder. If the image is located in the same folder, then you can reference it directly inside the url() function as in the code above.
The background-image property specifies an image to use as the background of an element. By default, the image is repeated so it covers the entire element.
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
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')";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With