0

I have input type "URL" in my HTML file. How to write JavaScript to fetch image from user entered URL and load it using javascript

<div class="url-container">
  <input type="url" class="form-control" placeholder="Insert image URL"   id="image-url">
  <button class="btn btn-default" type="submit" id="url_submit">
    <i class="material-icons">cloud_download</i>
  </button>
</div>

i want to load it here:

<img class="materialboxed" src="" id="image" style="">

2 Answers2

1

You can just change the src attribute of the image:

document.getElementById("b").addEventListener("click", e => {
  let imageInput = document.getElementById("image-input");
  let image = document.getElementById("image");
  if (imageInput.value) image.src = imageInput.value;
});
<input type="url" id="image-input">
<button id="b">Change Image</button>
<br>

<img src="" id="image">

Or, with jQuery:

$("#b").click(e => {
  let imageInput = $("#image-input");
  let image = $("#image");
  if (imageInput.val()) image.attr("src", imageInput.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="url" id="image-input">
<button id="b">Change Image</button>
<br>

<img src="" id="image">
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • that worked for me. Also How Can I encode this image fetched from url to base64? Help will be really appreciated. – Nikhil Paramane Jul 20 '18 at 12:58
  • You might want to check out [this other question](https://stackoverflow.com/questions/22172604/convert-image-url-to-base64) for that – Luca Kiebel Jul 20 '18 at 13:05
0
$('#url_submit').click(function(e) {
  e.preventDefault();
  $('.materialboxed').attr('src', $('#image-url').val());
}
Danil
  • 176
  • 2
  • 6