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 Answers 2

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">

Sign up to request clarification or add additional context in comments.

2 Comments

that worked for me. Also How Can I encode this image fetched from url to base64? Help will be really appreciated.
You might want to check out this other question for that
0
$('#url_submit').click(function(e) {
  e.preventDefault();
  $('.materialboxed').attr('src', $('#image-url').val());
}

1 Comment

Please add explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.