0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習45日目

Last updated at Posted at 2025-07-18

内容

画像プレビュー処理の外部ファイルへの切り出し

前提

  • active storageの画像投稿機能実装済
  • javascriptの画像プレビュー機能実装済
  • 追記部分以外は省略

目的

コードの可読性向上。
現在viewファイルに直接scriptタグでjsを書いているため、外部jsファイルへ切り出し、viewで呼び出すようにする。

手順

jsファイルを作成し、処理を記述する。
※記述は一例。そのままコピペしても正しく処理されないことに注意。

/app/assets/javascripts/image_preview.js

    let imageInput = document.getElementById("district_image")
    let imagePreview  = document.getElementById("image_preview")
    imagePreview.setAttribute('style', 'width:150px; height:150px;');
    imageInput.addEventListener('change', (e) => {
        let file = e.target.files[0];
        let blob = window.URL.createObjectURL(file);
        let img = document.createElement('img');
        img.setAttribute('src', blob);
        imagePreview.appendChild(img);
    })

viewファイルにjsを読み込む記述を追記する。

/app/views/xxxx/yyyy.html.erb

<%= javascript_include_tag 'image_preview' %>

viewファイルに元々記述していた処理のうち、jsファイルに記述した部分を削除する。

/app/views/xxxx/yyyy.html.erb

<script>
// ここから削除↓↓
    let imageInput = document.getElementById("district_image")
    let imagePreview  = document.getElementById("image_preview")
    imagePreview.setAttribute('style', 'width:150px; height:150px;');
    imageInput.addEventListener('change', (e) => {
        let file = e.target.files[0];
        let blob = window.URL.createObjectURL(file);
        let img = document.createElement('img');
        img.setAttribute('src', blob);
        imagePreview.appendChild(img);
    })
// ここまで削除↑↑
</script>

コメント

調べてみるとjsを読み込む方法には複数あるとわかったので、その違いについても調べる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?