How to update image src attribute using user input value

649 Views Asked by At

I am building a simple photo editor app using imgix, and I want the image src attribute to be updated when a user input fields receive values. Is there a way to append my new parameters onto the end of the src url?

I have been able to use template literals to create a new url, however I haven't been able to figure out how or if I can update the image src as the user types. Or if the only way to do this would be submitting the changes and show the new image on page reload. I have tried reassigning image.src to the new url, but that hasn't worked.

HTML:

<form id="form" class="input-container">
  <input type="text" placeholder="Enter Text" id="title"/>
  <input type="text" placeholder="Enter Hexcode Color" id="overlay" />
  <input type="submit" value="Apply Changes" id="edit-submit">
</form>


JavaScript:
let form = document.getElementById("form");
let titleInput = document.getElementById("title");
let encodedTitle = encodeURI(titleInput);
let overlayColor = document.getElementById("overlay");
let image = document.getElementById("image");
let timeout = null;

form.onkeyup = function(e) {
  let encodedTitle = "&txt=" + encodeURI(titleInput.value);
  let newColor = "&blend=" + overlayColor.value;
  let url = new URL(`${image.src}`);
  url = `${url}${encodedTitle}${newColor}`;
  console.log(url);
  document.getElementById("url-result").value = url;
  image.src = url;
};

I am able to grab the values but I haven't figured out what I'm needing to do to apply it to the img src url.

1

There are 1 best solutions below

2
On

Your code changes the URL of the image, but the URL gets longer and longer with each keyup.

Look at this snippet - maybe it helps.

let form = document.getElementById("form");
let titleInput = document.getElementById("title");
let encodedTitle = encodeURI(titleInput);
let overlayColor = document.getElementById("overlay");
let image = document.getElementById("image");
let timeout = null;

// URL base for your image - so it doesn't get longer-and-longer
// with each keyup
let baseURL = image.src

// just a display element, so you can see the URL created
let display = document.getElementById('new-url')

form.onkeyup = function(e) {
  const newURL = `${baseURL}&txt=${encodeURI(titleInput.value)}&blend=${overlayColor.value}`
  document.getElementById("url-result").value = newURL;
  image.src = newURL
  display.textContent = newURL
};
img {
  width: 100px;
  height: 100px;
}
<img id="image" src=""><br />
<label for="url-result">URL Result:
<input type="text" id="url-result">
</label>
<div>Display new URL: <span id="new-url"></span></div>
<form id="form" class="input-container">
  <input type="text" placeholder="Enter Text" id="title" />
  <input type="text" placeholder="Enter Hexcode Color" id="overlay" />
  <input type="submit" value="Apply Changes" id="edit-submit">
</form>