0

How can I set a button background image to an <input type="file">?

This is my html code:

<div class="large-9 columns small-9  columns" style="margin-top:2%;">
  <input type="file" name="file" id="file" onchange="changePicture()" class="btn btn-file">
</div>

There is a way to set background image only to the button, not to the selected image text view?

Pugazh
  • 9,453
  • 5
  • 33
  • 54
foo
  • 443
  • 2
  • 8
  • 22
  • 2
    what is the output you are looking for? – Tushar Jul 11 '16 at 10:23
  • I want to set image only to the button not to the text that next to the button, this input include two parts, one- button second-text view of choosen image name. – foo Jul 11 '16 at 10:31
  • Input type file has limitation to style. button and text are not different you cant separately style them. – Tushar Jul 11 '16 at 10:36
  • Ok now with the explanation of OP I understand...And what @Tushar said is very true. If you want to fully customise the file input you should probably consider using a plugin for that. – thepio Jul 11 '16 at 10:37
  • @ thepio which plugin? and how can I use it? – foo Jul 11 '16 at 10:39
  • @Tushar thank you for your edit, and snippet... – foo Jul 11 '16 at 10:40
  • I think this answer could be helpful to you: http://stackoverflow.com/a/18909078/2003702 – thepio Jul 11 '16 at 10:42

1 Answers1

1

You can build a fake input which you can style easily.

// do stuff after page load
window.addEventListener("DOMContentLoaded", function()
{
  // bind event listener to the fake button
  document.getElementById("fake-button").addEventListener("click", function()
  {
    // bind event listener to the real button
    document.getElementById("real").addEventListener("change", function()
    {
      // extract and place the name of the file into the fake label field
      document.getElementById("fake-label").value = this.files[0].name;
    });
    
    // simulate a click event on the real button
    document.getElementById("real").click();
  });
});
#real {
  display: none;
}

#fake-button {
  background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Mozilla_Firefox_logo_2013.svg/40px-Mozilla_Firefox_logo_2013.svg.png");
}
/* Just a random image from the internet */
<input type="file" id="real" />
<input type="button" value="Open files" id="fake-button" />
<input type="text" id="fake-label" />

Now you can style the button and the label separately.

Nekomajin42
  • 638
  • 1
  • 6
  • 20