Search code examples
javascriptturbolinks

Unable to declare variable within callback in Rails App


I'm currently working on a Rails 6 application using trubolinks. I'm working on a function to reaplace an avatar placeholder with the image selected upon upload. However, something weird is happening I'm declaring two variables, one is stated with a value the over does not.

document.addEventListener('readystatechange', event => {
 if (event.target.readyState === "complete") { 

/**
 * Display the image in the file input when added to the form.
 * Replace avatar with image selected.
 */
  const profileAvatarBlock = document.getElementById('profile-avatar');

  function showImage(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        let avatarPreview = document.getElementById('profile-avatar-preview');
        let img =avatarPreview.children[1].setAttribute("src", e.target.result);

        debugger;
        ['width', 'height'].forEach(attribute => { 
          img.removeAttribute(attribute)
        });
        debugger;
      };

      reader.readAsDataURL(input.files[0]);
    }
  }

  profileAvatarBlock.addEventListener('change', function() {
      showImage(this);
  })
 }
});

At first I thought that it was because of turbolinks so I add "turbolinks:load", but this didn't change anything. When I check for avatarPreview I get back back in the debugger but when I check img I get undefined. if I run avatarPreview.children[1].setAttribute("src", e.target.result); I also get it returned but if I assigned it to img is not working.

Why I cant declare a variable inside the callback? I want to understand dont care much about getting it to work.

enter image description here


Solution

  • You are calling setAttribute to assign e.target.result to the src attribute of the element. Then, you are assigning the return value from that function (which is always undefined) to img.

    Try instead:

    let img = e.target.result
    

    If you really want to get the value from the children, you can try

    let img = avatarPreview.children[1].getAttribute('src')`