0

I want to insert an image using prompt() in JavaScript

Here is the thing I tried :

var name = prompt("Enter your name"); [Typeof string or number]

What I want is:

var profile_img = prompt("Choose Your Picture"); [Typeof img]

Rahman Haroon
  • 462
  • 1
  • 5
  • 17
  • 1
    Almost certainly not. But ascii art would be possible... if it is an acceptable substitute for your use case – Andrew May 27 '21 at 06:14
  • I would write an implementation of prompts yourself, or use a library -- SweetAlert comes to mind. https://sweetalert2.github.io/ – Nisala May 27 '21 at 06:46
  • 2
    Just don't use any of the `prompt`, `alert` etc. methods. You'll save you a lot of troubles. These are from ages we don't want to remember. Go with a proper interface that won't block your UI and that you will be able to control 100%. – Kaiido May 27 '21 at 06:47

2 Answers2

1

No, it is not possible. A window.prompt() call only accepts text input.

Depending on your use case, the user could enter the public URL to an image (any supported protocol, even the pseude-scheme data:) and your script could then fetch the image from the given URL. Another possibility mentioned by Andrew in the comments: have users input an encoded version of the image (base64, hexdump, …) and then parse it yourself to get back the binary image data.

To then insert the image into your DOM, see other questions and answers on Stackoverflow, such as DOM appendChild to insert images:

let img = document.createElement("img");
img.src = 'path/to/image';

parent_element.appendChild(img);
knittl
  • 197,664
  • 43
  • 269
  • 318
  • Is there any way to insert img anything in javaScript? – Towker_joy May 27 '21 at 06:16
  • @Towker_joy what do you mean? `let img = new Image(); element.appendChild(img);`? – knittl May 27 '21 at 06:23
  • can you show some examples? I want to make a project like this: anyone visits my site but this site fully blank. user can input his name, about, img anything than Press Enter. Than javascript process all data and img and make a website/page with his data – Towker_joy May 27 '21 at 06:37
1

What you can do is to use <input type="file" .. and trigger it with the js

Assuming you have jQuery, but the principle should work regardless

<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />

Then look at this answer how to display the image without uploading it to the server

Eriks Klotins
  • 3,546
  • 1
  • 8
  • 23