Create Image Preview with jQuery
Tags: javascript, jquery, webdev, tutorial
Published: 2022-12-17 12:30:19

Hey devs, today we’re going to make an image preview with Jquery.
I’m using jQuery 3 which can be found [here](https://releases.jquery.com/) if you use CDN or [here](https://jquery.com/download/) if you want to download it.

## 1. Create our HTML
In our HTML we have a card, an input type file, a label that acts as our input button, a button to delete or remove our image preview, and an image tag with an empty src attribute for our image preview.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Image Preview with Jquery</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="styles.css" />

    <script
      src="https://code.jquery.com/jquery-3.6.1.min.js"
      integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
      crossorigin="anonymous"
    ></script>
    <script src="./script.js"></script>
  </head>
  <body>
    <h3 class="title">Image Preview with Jquery</h3>
    <div class="card-input-image" id="card_input_image">
      <input
        type="file"
        id="input_image"
        name="foto[]"
        class="input-image"
        accept=".png, .jpg, .jpeg"
        onchange="onchange_value('input_image', 'card_input_image')"
      />
      <label for="input_image" class="label-upload-image">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="1em"
          height="1em"
          preserveAspectRatio="xMidYMid meet"
          viewBox="0 0 24 24"
        >
          <path
            fill="currentColor"
            d="M12 20c-4.41 0-8-3.59-8-8s3.59-8 8-8s8 3.59 8 8s-3.59 8-8 8m0-18A10 10 0 0 0 2 12a10 10 0 0 0 10 10a10 10 0 0 0 10-10A10 10 0 0 0 12 2m1 5h-2v4H7v2h4v4h2v-4h4v-2h-4V7Z"
          />
        </svg>
        Upload File
      </label>
      <button
        type="button"
        class="btn-delete"
        onclick="delete_value('input_image', 'card_input_image')"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="1em"
          height="1em"
          preserveAspectRatio="xMidYMid meet"
          viewBox="0 0 256 256"
        >
          <path
            fill="currentColor"
            d="M208.5 191.5a12 12 0 0 1 0 17a12.1 12.1 0 0 1-17 0L128 145l-63.5 63.5a12.1 12.1 0 0 1-17 0a12 12 0 0 1 0-17L111 128L47.5 64.5a12 12 0 0 1 17-17L128 111l63.5-63.5a12 12 0 0 1 17 17L145 128Z"
          />
        </svg>
        Delete
      </button>
      <img src="" id="img_preview" class="image-preview" alt="" />
    </div>
  </body>
</html>
```

## 2. Create our CSS
These are our basic CSS.

```css
/* base */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

* {
  font-family: 'Poppins', sans-serif;
}
body {
  padding: 0;
  margin: 0;
}

.title {
  text-align: center;
}

/* input image */
.card-input-image {
  height: 125px;
  width: 200px;
  border-radius: 8px;
  position: relative;
  margin: 0 auto 12px auto;
}
.card-input-image .label-upload-image {
  margin: auto;
  width: 200px;
  height: 100%;
  border-radius: 8px;
  color: #629ef5;
  font-weight: 700;
  font-size: 14px;
  line-height: 21px;
  border: 2px dashed #b0cffa;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.card-input-image input {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}
.card-input-image .image-preview {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
  object-fit: cover;
  display: none;
}
.card-input-image .btn-delete {
  background: #ef4e4e;
  border-radius: 14.5455px;
  color: #ffffff;
  font-weight: 700;
  font-size: 10px;
  line-height: 10px;
  border: none;
  padding: 7.27273px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
}

/* input image active state */
.card-input-image.active .label-upload-image {
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.45));
  color: #ffffff;
  border: none;
}
.card-input-image.active .image-preview {
  display: initial;
}
.card-input-image.active .btn-delete {
  display: flex;
  align-items: center;
  justify-content: center;
}
```

## 3. Create our JS
So the logic for the `onChange` input is when the input or the label in this case is clicked, it will get the file property and put it in the file variable and then copy the array and put it in variable `filesArr`. After that, it will add a class called `active` to our `image-preview`, create a blob inside the `image-preview`, and remove the inside of the `label-upload-image`.

```javascript
//handle on change
function onchange_value(name, preview) {
  files = $(`#${name}`).prop('files');
  var filesArr = Array.prototype.slice.call(files);

  $(`#${preview}`).addClass('active');
  $(`#${preview} label.label-upload-image`).html('');
  $(`#${preview} img.image-preview`).attr(
    'src',
    URL.createObjectURL(filesArr[0])
  );
}
```
For our `onClick` delete, when the `btn-delete` is clicked, it will remove the value of our input file, remove the class `active` from the `image-preview`, remove the value of the `src` attribute from the `image-preview`, and put back the default `label-upload-image`.

```javascript
//handle on click button delete
function delete_value(name, preview) {
  $(`#${name}`).val('');
  $(`#${preview}`).removeClass('active');
  $(`#${preview} label.label-upload-image`).html(
    "<svg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' preserveAspectRatio='xMidYMid meet' viewBox='0 0 24 24'><path fill='currentColor' d='M12 20c-4.41 0-8-3.59-8-8s3.59-8 8-8s8 3.59 8 8s-3.59 8-8 8m0-18A10 10 0 0 0 2 12a10 10 0 0 0 10 10a10 10 0 0 0 10-10A10 10 0 0 0 12 2m1 5h-2v4H7v2h4v4h2v-4h4v-2h-4V7Z'/></svg>Upload File"
  );
  $(`#${preview} img.image-preview`).attr('src', '');
}
```

## Add file size limit
To add size limit, simply add a conditional if the size of the variable `filesArr` is bigger than for this case 2MB (2MB = 2097152), then it will pop out an `alert` that said `File (file name) is too big!`. The code below the alert is to prevent any change when the file is bigger than the max size (2097152 or 2MB). 
If the file size is under 2MB, it will add class `active` to our `image-preview`, create a blob inside the `image-preview`, and remove the inside of the `label-upload-image`.

```javascript
//handle on change
function onchange_value(name, preview) {
  files = $(`#${name}`).prop('files');
  var filesArr = Array.prototype.slice.call(files);

  if (filesArr[0].size > 2097152) {
    alert(`File ${filesArr[0].name} is too big!`);

    //The code below is to prevent any change when the file is bigger than the max size (2097152 or 2MB)
    $(`#${name}`).val('');
    $(`#${preview}`).removeClass('active');
    $(`#${preview} label.label-upload-image`).html(
      "<svg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' preserveAspectRatio='xMidYMid meet' viewBox='0 0 24 24'><path fill='currentColor' d='M12 20c-4.41 0-8-3.59-8-8s3.59-8 8-8s8 3.59 8 8s-3.59 8-8 8m0-18A10 10 0 0 0 2 12a10 10 0 0 0 10 10a10 10 0 0 0 10-10A10 10 0 0 0 12 2m1 5h-2v4H7v2h4v4h2v-4h4v-2h-4V7Z'/></svg>Upload File"
    );
    $(`#${preview} img.image-preview`).attr('src', '');
  } else {
    $(`#${preview}`).addClass('active');
    $(`#${preview} label.label-upload-image`).html('');
    $(`#${preview} img.image-preview`).attr(
      'src',
      URL.createObjectURL(filesArr[0])
    );

    console.log(filesArr[0].name, 'name'); //for testing in console
  }
}
```
And there you have it, our image preview with jQuery. You can check the repo [here](https://github.com/NabillaTrisnani/jquery-image-preview). And as always, let me know if it helps.

Thanks for coming by and Peace ✌

---

## Author
- Github: [@NabillaTrisnani](https://github.com/NabillaTrisnani)
- LinkendIn: [Nabilla Trisnani](https://www.linkedin.com/in/nabilla-trisnani/)
- Twitter: [@NabillaTrisnani](https://twitter.com/NabillaTrisnani)