Solved

javascript pass variable to url

Posted on 2016-07-30
3
69 Views
Last Modified: 2016-08-04
I am trying to pass a simple variable to url but for some reason it is not working. Am I missing something?

function myFunction() {
    var x = "img_tree.png";
    document.body.style.backgroundColor = "#f3f3f3";
    document.body.style.backgroundImage = 'url(x)';
}

Open in new window

0
Comment
Question by:Mazdajai
  • 2
3 Comments
 
LVL 63

Expert Comment

by:Zvonko
ID: 41736208
Check this:
function myFunction() {
    var x = "img_tree.png";
    document.body.style.backgroundColor = "#f3f3f3";
    document.body.style.backgroundImage = "url('"+x+"')";
}

Open in new window

And that script does not PASS anything to URL.
The script does set the background image to a image file denoted by the url parameter:
http://www.w3schools.com/jsref/prop_style_backgroundimage.asp
0
 
LVL 21

Author Comment

by:Mazdajai
ID: 41736241
Thanks. Can you explain this?

 '"+x+"'

Open in new window

0
 
LVL 63

Accepted Solution

by:
Zvonko earned 500 total points
ID: 41737268
No, that I cannot explain.
But I can explain you this:
"url('"+x+"')";

Open in new window

In JavaScript that are three Strings concatinated to one string value.
In the resulting string value is the middle part enclosed by single quotes and the middle part is comming from variable with the name: x

Is that explanation suitable for you?
1

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Find out what you should include to make the best professional email signature for your organization.
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now