0

I am using the below code to set up a file upload. However on my page, the width of the input element is greater than the actual button that shows up. I can click anywhere in this invisible box and still open the file browser. I want to just be able to click the button and open it, not blank space. How can I achieve this?

<input type="file" action="/upload" id="selectFiles" name="myFile" enctype="multipart/form-data" />
brk
  • 48,835
  • 10
  • 56
  • 78
user2763557
  • 449
  • 5
  • 18
  • please share more html code, this is not enough to reproduce the problem – brk Jan 30 '19 at 17:04
  • becuase that is how the input works, the element is more than just the button. https://jsfiddle.net/6to8cLsn/ – epascarello Jan 30 '19 at 17:04
  • This is the default behaviour of the component, i dont think you can configure it the way you specified. Insted you may need to do something like this https://stackoverflow.com/questions/10798761/how-to-link-an-input-button-to-a-file-select-window – M S Jan 30 '19 at 17:08

2 Answers2

1

Did you mean that ?

<label>
    <input type="file" />
    <span class="file-button">Upload File</span>
</label>

label {
    display: inline-block;
}

label input[type="file"] {
    display: none;
}

.file-button {
    padding: 13px 20px;
    color: #fff;
    display: block;
    cursor: pointer;
    font-weight: 500;
    font-size: 0.8em;
    background: #f00;
}
Xerjoff
  • 151
  • 3
1

You can hide the file button, and create a fake one to mimic it. Like this:

var fakeButton = document.getElementById('fake-file-btn');
var fileButton = document.getElementById('selectFiles');
fakeButton.addEventListener('click', function(e) {

  // creates a event that triggers click on fileButton 
  var clickEvent = new MouseEvent('click', {bubbles: true});
  fileButton.dispatchEvent(clickEvent);
  
});
#selectFiles {
  display: none;
}
<button id="fake-file-btn">Choose File</button>
<input type="file" action="/upload" id="selectFiles" name="myFile" enctype="multipart/form-data" />
dabishan
  • 671
  • 3
  • 10