user2828274
user2828274

Reputation: 31

Getting a image through javascript

I just want to bring image whenever i press css button but image is not coming. what can be wrong in this?

<html>
<head>
<script >
function create() {


var x = document.createElement("IMG");
x.setAttribute("src", "C:\Users\jai guru umesh\Desktop\webops\sha\fronthead images\rover0.png");
document.body.appendChild(x);




};

</script>
</head>
<body>
<input type="button" name="cssandcreate" id="cssandcreate" value="css"  onclick="create()"/>

</body>
</html>

Upvotes: 0

Views: 56

Answers (3)

FabioSorre
FabioSorre

Reputation: 310

Use relative path (absolute if you have a link):

x.setAttribute("src", "../image.png");

In surplus, I suggest you to pay attention to the directory names (e.g fronthead images) it's better not use special characters and blank spaces (so "fronthead images", it's better in thi form "frontheadImages", or "fronthead_images")

Upvotes: 0

stackErr
stackErr

Reputation: 4170

You could load the image with the page and hide it until a user clicks on it.

<html>
<head>
<script >
function showImage(image) {



image.style.display = "inline";




};

</script>
</head>
<body>
<input type="button" name="cssandcreate" id="cssandcreate" value="css"  onclick="create()"/>
<img src="../fronthead images/rover0.png" style="display:none;" onclick="showImage(this)" />

</body>
</html>

Also I changed your path to a relative path since browsers will not allow access to your HD.

Upvotes: 0

Marko Gresak
Marko Gresak

Reputation: 8207

Your error is in setAttribute function, you can't use this kind of path in web browsers as it works on client's pc and this would mean you could access their storage, which would be huge privacy concern.

You should use images locally from your file, either in same file as this html file, or in a subfolder, e.g. .../img (where ... is folder which contains html file). Then you can use relative path:

x.setAttribute("src", "img/rover0.png"); // this should work on any system

You can use / for windows paths too, but if you want to use \, make sure to use \\.

But if you insist on absolute file path, use this:

x.setAttribute("src", "file:///C:\\Users\\jai guru umesh\\Desktop\\webops\\sha\\fronthead images\\rover0.png");

Note the use of file:/// and \\ (using / instead \\ should work as well)

Upvotes: 1

Related Questions