Skip to content
Advertisement

Create code template from input javascript

I’m trying to make app that generates code with HTML tags from images.

User pastes an image link, image displays and after that user will click button to generate the img code to copy.

I’ve got code that loads and previews images from input.

I’m struggling with generating the HTML code. User will get: <img src="link photo"> in div code.

I can’t make it:

document.getElementById('code').innerHTML = '<img src=" ' + source + '">';

Because it won’t display HTML tags.

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <style>
      img {
      width: 10%;
      height: 10%;
      border-radius: 10px;
      box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
      opacity: 85%;
  </style>
</head>

<body>
  <form>
    <input type="text" id="imagename" value="" />
    <input type="button" id="btn" value="Show" />
  </form>
  <div id="before">
  </div>
  <div>
    <p>HTML`s code to copy:</p>
  </div>
  <div name="code" id="code">
  </div>
  <script type="text/javascript">
    document.getElementById('btn').addEventListener("click", fun);

    function fun() {
      var val = document.getElementById('imagename').value;
      source = val;
      img = document.createElement('img');
      img.src = source;
      document.body.appendChild(img);
      // move child to up
      var before = document.getElementById('before');
      before.insertBefore(img, before.children[0]);

      document.getElementById('code').innerHTML = '<img src=" ' + source + '">';

    }
  </script>
</body>

</html>

Advertisement

Answer

Don’t use innerHTML, use innerText:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <style>
      img {
      width: 10%;
      height: 10%;
      border-radius: 10px;
      box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
      opacity: 85%;
  </style>
</head>

<body>
  <form>
    <input type="text" id="imagename" value="" />
    <input type="button" id="btn" value="Show" />
  </form>
  <div id="before">
  </div>
  <div>
    <p>HTML`s code to copy:</p>
  </div>
  <div name="code" id="code">
  </div>
  <script type="text/javascript">
    document.getElementById('btn').addEventListener("click", fun);

    function fun() {
      var val = document.getElementById('imagename').value;
      source = val;
      img = document.createElement('img');
      img.src = source;
      document.body.appendChild(img);
      // move child to up
      var before = document.getElementById('before');
      before.insertBefore(img, before.children[0]);

      document.getElementById('code').innerText = '<img src="' + source + '">';

    }
  </script>
</body>

</html>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement