how do I use one script for multiple buttons/links? - javascript

this is gonna be probably a basic thing to answer too as I'm learning to code html/css/js and to do so I'm building a random website for a company that doesn't even know I exist.
So I have built a side nav menu with LINKS ()that show modal windows on-click so that the website remains a one-page website and one of those is a "ask an estimate" form that so far send info to nowhere (I will learn that later on).
Now, on the main page, I have made a series of hero banners to display their products and on each one of them I want to add a "ask an estimate" BUTTON () that show the same modal window as the link in the side nav. (probably will do the same with the contact link on one of those banners)
Now this is the code I'm using (most of it from w3):
Javascript file:
var modalPreventivo = document.getElementById("modalPreventivo");
var btnPreventivo = document.getElementById("btnPreventivo");
var spanPreventivo = document.getElementsByClassName("closePreventivo")[0];
btnPreventivo.onclick=function() {
modalPreventivo.style.display= "block";
}
spanPreventivo.onclick = function() {
modalPreventivo.style.display = "none";
}
windowPreventivo.onclick = function(eventPreventivo) {
if (eventPreventivo.target == modalPreventivo) {
modalPreventivo.style.display = "none";
}
}
HTML on the link (works good Preventivo=Estimate)
<li>Preventivo</li>
<div id="modalPreventivo" class="modalPreventivo">
<div class="modal-contentPreventivo">
<div class="container">
<span class="closePreventivo">×</span>
<h1>Chiedi ora il tuo preventivo gratuitamente e senza impegno!</h1><br>
<form action="/action_page.php">
<label for="fname">Nome</label><br>
<input type="text" id="fname" name="firstname" placeholder="Il tuo nome">
<br>
<label for="lname">Cognome</label><br>
<input type="text" id="lname" name="lastname" placeholder="Il tuo cognome">
<br>
<label for="country">E-mail (solo per ricontattarvi no spam)</label><br>
<input type="text" id="Email" name="email" placeholder="Il tuo indirizzo di posta elettronica">
<br>
<label for="subject">Come possiamo aiutarvi?</label><br>
<textarea id="subject" name="subject" placeholder="Scrivici i dettagli della tua richiesta!" style="height:200px"></textarea>
<br>
<input type="submit" value="Richiedi ora!">
</form>
</div>
</div>
</div>
<script src="/Odorici/Javascript/preventivo.js"></script>
HTML button on hero banner (doesn't work at all)
<div class="hero-image" style="background-image: url(/Odorici/img/sliding\ gate.jpg);">
<div class="hero-text">
<h1>Cancelli Carrai</h1>
<p>Produciamo:
<ul>
<li>Cancelli carrai scorrevoli ciechi</li>
<li>Cancelli carrai scorrevoli normali</li>
<li>Cancelli carrai ad anta ciechi</li>
<li>Cancelli carrai ad anta normali in ferro</li>
</ul>
Su misura e con la possibilità di verniciatura e zincatura a caldo.</p>
<button type="button" id="btnPreventivo" >Richiedi Preventivo</button>
</div>
</div>
I forgot to put the CSS (thanks KEN!)
.modalPreventivo {
display:none; /* Hidden by default */
position:fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 50px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.5); /* Black w/ opacity */
float: center;
}
/* Modal Content */
.modal-contentPreventivo {
display: block;
background-color: wheat;
color:goldenrod;
margin: auto;
padding: 10px 20px 10px 20px;
border: 1px solid #111;
border-radius: 5px;
width: fit-content;
}
/* The Close Button */
.closePreventivo {
color: #aaa;
float: right;
font-size: 35px;
font-weight: bold;
}
.closePreventivo:hover,
.closePreventivo:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
input[type=text], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: goldenrod;
color: #7a1818;
padding: 12px 20px;
border: 1px solid #111;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
input[type=submit]:hover {
background-color: rgb(16, 172, 16);
color: goldenrod;
font-weight: bold;
}
In the beginning, I thought that using the same ID would have work (also because while building the menu the "contacts" link has been showing the "estimate" form instead of its own "contact" modal window, but it won't work.
I tried to copy and paste the whole code from the "estimate" LINK with all the boxes and the and it won't work, I tried changing id, using href #preventivo, but I feel like nothing works cause I'm probably using the wrong functions or maybe I'm coding something wrong in the ... I can't figure it out!
When I google this problem I read many articles that use Jquery (?) but I feel this should be much easier since when I didn't want this modal showing on the wrong link on the menu, it would have kept showing up (and it took me a while to fix that!) but now that I want it to show up on several links/buttons it won't...

Related

How to change the position of the div after file upload?

I want to reposition my browse button when the user uploaded a file. This is the sample of how it should really look before and after uploading the file:
Before:
After:
I change the content of my button "Browse file" to "Replace File"
This is my html code.
<div id="uploadModal" class="upload-modal">
<div class="modal-content">
<h2 style="font-size: 24px;">Choose file</h2>
<p>
Choose the csv file containing the data you want to create a forecast for.
</p>
<div class="browse-file">
<div id="filename"></div>
<input type="file" id="file-upload" multiple required />
<label for="file-upload">Browse file</label>
</div>
<div class="options">
<button class="cancel"><h4>Cancel</h4></button>
<button class="proceed"><h4>Proceed</h4></button>
</div>
</div>
</div>
Here is my CSS
.upload-modal {
display: none;
position: fixed;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 34, 2, 0.3);
}
input[type="file"] {
position: absolute;
opacity: 0;
z-index: -1;
}
input + label {
padding: 10px 24px;
background: #D4E8CF;
border-radius: 100px;
position: static;
width: 119px;
height: 40px;
border: none;
cursor: pointer;
z-index: 1;
}
#filename{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100px;
justify-content: left;
align-items: flex-start;
}
What's happening here is that my button moves according to the length of the file so I added max-width but no luck. Thanks!
EDIT: I added css for upload-modal
I'm not sure you need to use absolute positioning for what you want.
You could set div#upload-modal or div.modal-content to position: relative;
and then position the button element with left: or right: or use float: right;
https://developer.mozilla.org/en-US/docs/Web/CSS/position
https://developer.mozilla.org/en-US/docs/Web/CSS/float
This alternate version uses CSS's Flexbox and JavaScript's Event Listeners.
It probably doesn't do precisely what you want but should come close enough that reading through the comments a few times and playing around with the code should make clear how you can get to where you want to go using just a few lines of JavaScript to grab the file name and show it on the screen.
MDN (linked above) is a great place to get more clarity about any particular front-end feature that you're interested in using. Happy coding!
// Unnamed function runs as soon as the DOM elements are ready
window.addEventListener('DOMContentLoaded', () => {
// Identifies some of the DOM elements
const
filenameSpan = document.getElementById("filename-span"),
fileInput = document.getElementById("file-input"),
chooseBtn = document.getElementById("choose-btn");
// When the input changes (when a file is chosen), calls `updateDisplay`
fileInput.addEventListener("change", updateDisplay);
// Defines `updateDisplay`
function updateDisplay(){
// Puts first fiename in span and "unhides" it
const filename = fileInput.files[0]?.name;
filenameSpan.textContent = filename || "(choose file)";
filenameSpan.classList.remove("hidden");
};
});
*{
margin: 0;
}
#container{
width: 18rem; /* "rem" unit is the base character height */
padding: 2rem;
border-radius: 1.5rem;
background-color: lightgrey;
}
#header{
margin-bottom: 2rem;
}
#chooser{
/* flex w/ space-around makes choose-btn shift right when filename appears */
display: flex;
justify-content: space-around;
margin-bottom: 4rem;
}
#options{
text-align: right;
}
#filename-span{
padding: 1rem 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 6rem;
}
button{ /* the "options" buttons */
border: none;
font-weight: bold;
color: darkgreen;
background-color: lightgrey;
}
#choose-btn{
/* Not a true "button" element -- the "label" for file-input */
padding: 1rem 1.5rem;
background-color: darkseagreen;
border-radius: 2rem;
border: none;
font-weight: bold;
}
.hidden{ /* Uses a class so all styling happens thru CSS */
display: none;
}
<div id="container">
<div id="header">
<h2>Choose file</h2>
<p> Choose the csv file containing the data you want to create a forecast for</p>
</div>
<div id="chooser">
<!-- The span and input elements are initially "hidden" via CSS -->
<span id="filename-span" class="hidden"></span>
<label id="choose-btn">
<!-- input element is inside its stylable & clickable label -->
Browse File
<input id="file-input" type="file" class="hidden" />
</label>
</div>
<div id="options">
<button id="cancel-btn">Cancel</button>
<button id="proceed-btn">Proceed</button>
</div>
</div>

Open select file dialog using Enter key press

I have a problem with my project
I would like to open the input file on "Enter" key to improve some accessibility.
I've added tabindex on label because when I jump in to this label by using tab and press "enter" I would like to fire function which will open the input file picker.
.input {
position: absolute;
visibility: hidden;
}
<input id="input" class="input" name="newFile" type="file" accept=".pdf" data-required="true" />
<label class="btn" for="input" tabindex="0">
<span class="upload label">
<span class="label__text" data-label="Upload file" data-next-label="Upload next file">Upload file</span>
</span>
</label>
Warning the following is just a quick idea of how to achieve this by styling the actual input and visually hiding the label (to ensure it is still accessible).
However there are lots of accessibility issues you still need to consider, showing which file was selected for example.
But this does show you how you can style the input to keep all the native functionality without having to re implement it yourself (active state for example, which I styled here). Also don't forget a custom focus indicator, input:focus::before.
There are other issues such as browser support to consider as well, however in theory this should fall back reasonably gracefully, I just haven't tested it.
This codepen gives a good starting point on how to implement some of the features this is missing such as showing the file name selected.
input{
color: transparent;
width:150px;
height:28px
}
input::-webkit-file-upload-button {
visibility: hidden;
}
input::before {
content: 'Select a PDF';
color: black;
display: inline-block;
border: 1px solid #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
text-shadow: 1px 1px #fff;
font-weight: 700;
font-size: 10pt;
width:132px;
}
input:hover::before {
border-color: black;
}
input:active {
outline: 0;
}
label {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
white-space: nowrap; /* added line */
}
<input id="input" class="input" name="newFile" type="file" accept=".pdf" data-required="true"/>
<label for="input">upload file</label>

jQuery load modal after an interval only one time per session

I would like to show a modal after 5 seconds, but only once per session (website visit).
This is what I have so far:
$(document).ready(function ()
{
//Fade in delay for the background overlay (control timing here)
$("#bkgOverlay").delay(4800).fadeIn(400);
//Fade in delay for the popup (control timing here)
$("#delayedPopup").delay(5000).fadeIn(400);
//Hide dialouge and background when the user clicks the close button
$("#btnClose").click(function (e)
{
HideDialog();
e.preventDefault();
});
});
//Controls how the modal popup is closed with the close button
function HideDialog()
{
$("#bkgOverlay").fadeOut(400);
$("#delayedPopup").fadeOut(300);
}
This is the codepen for it:
https://codepen.io/uxfed/pen/BmyeEr
I would like this modal to only show one time per website session.
You can put your fading code into body of if statement. I did it via localStorage tool. This code works for me:
$(function(){
console.log(window.localStorage);
var ip_s = localStorage.getItem('ip');
var d = new Date();
!ip_s ? use_local_storage(d) : console.log('not the first visit');
})
function use_local_storage(d) {
$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
var iip = String(JSON.parse(JSON.stringify(data, null, 2)).ip);
localStorage.setItem('ip', iip);
localStorage.setItem('day_visit', d.toLocaleDateString());
console.log(window.localStorage);
// load your function here
// question_body();
});
}
Code in Snippet doesn't works here, but in your project it would.
function hideDialog(){
$("#bkgOverlay").fadeOut(400);
$("#delayedPopup").fadeOut(300);
}
function question_body(){
//Fade in delay for the background overlay (control timing here)
$("#bkgOverlay").delay(4800).fadeIn(400);
//Fade in delay for the popup (control timing here)
$("#delayedPopup").delay(5000).fadeIn(400);
//Hide dialouge and background when the user clicks the close button
$("#btnClose").click(function (e){
HideDialog();
e.preventDefault();
});
}
$(function(){
console.log(window.localStorage);
var ip_s = localStorage.getItem('ip');
var d = new Date();
!ip_s ? use_local_storage(d) : console.log('not the first visit');
})
function use_local_storage(d) {
$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
var iip = String(JSON.parse(JSON.stringify(data, null, 2)).ip);
localStorage.setItem('ip', iip);
localStorage.setItem('day_visit', d.toLocaleDateString());
console.log(window.localStorage);
// load your function here
// question_body();
});
}
.instructions {
text-align:center;
font-size:20px;
margin: 15vh;
}
/* //////////////////////////////////////////////////////////////////////////////////////////////
// Default Modal Styles //
////////////////////////////////////////////////////////////////////////////////////////////// */
/* This is the background overlay */
.backgroundOverlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background: #000000;
opacity: .85;
filter: alpha(opacity=85);
-moz-opacity: .85;
z-index: 101;
display: none;
}
/* This is the Popup Window */
.delayedPopupWindow {
display: none;
position: fixed;
width: auto;
max-width: 480px;
height: 310px;
top: 50%;
left: 50%;
margin-left: -260px;
margin-top: -180px;
background-color: #efefef;
border: 2px solid #333;
z-index: 102;
padding: 10px 20px;
}
/* This is the closing button */
#btnClose {
width:100%;
display: block;
text-align: right;
text-decoration: none;
color: #BCBCBC;
}
/* This is the closing button hover state */
#btnClose:hover {
color: #c90c12;
}
/* This is the description headline and paragraph for the form */
#delayedPopup > div.formDescription {
float: left;
display: block;
width: 44%;
padding: 1% 3%;
font-size: 18px;
color: #666;
clear: left;
}
/* This is the styling for the form's headline */
#delayedPopup > div.formDescription h2 {
color: #444444;
font-size: 36px;
line-height: 40px;
}
/*
////////// MailChimp Signup Form //////////////////////////////
*/
/* This is the signup form body */
#delayedPopup #mc_embed_signup {
float: left;
width: 47%;
padding: 1%;
display: block;
font-size: 16px;
color: #666;
margin-left: 1%;
}
/* This is the styling for the signup form inputs */
#delayedPopup #mc-embedded-subscribe-form input {
width: 95%;
height: 30px;
font-size: 18px;
padding: 3px;
margin-bottom: 5px;
}
/* This is the styling for the signup form inputs when they are being hovered with the mouse */
#delayedPopup #mc-embedded-subscribe-form input:hover {
border:solid 2px #40c348;
box-shadow: 0 1px 3px #AAAAAA;
}
/* This is the styling for the signup form inputs when they are focused */
#delayedPopup #mc-embedded-subscribe-form input:focus {
border:solid 2px #40c348;
box-shadow: none;
}
/* This is the styling for the signup form submit button */
#delayedPopup #mc-embedded-subscribe {
width: 100%!important;
height: 40px!important;
margin: 10px auto 0 auto;
background: #5D9E62;
border: none;
color: #fff;
}
/* This is the styling for the signup form submit button hover state */
#delayedPopup #mc-embedded-subscribe:hover {
background: #40c348;
color: #fff;
box-shadow:none!important;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="instructions">Wait for 5 seconds</div>
<div id="bkgOverlay" class="backgroundOverlay"></div>
<div id="delayedPopup" class="delayedPopupWindow">
<!-- This is the close button -->
[ X ]
<!-- This is the left side of the popup for the description -->
<div class="formDescription">
<h2>Sign Up and <span style="color: #40c348; font-weight: bold;">Save $25!</span></h2>
<p>Sign up for our Deal Alerts and save
$25 Off of your first order of $50 or more!</p>
</div>
<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup">
<form action="" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
<div class="mc-field-group">
<label for="mce-FNAME">First Name
<span class="asterisk">*</span>
</label>
<input type="text" value="" name="FNAME" class="" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name
<span class="asterisk">*</span>
</label>
<input type="text" value="" name="LNAME" class="" id="mce-LNAME">
</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address
<span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;">
<input type="text" name="b_2aabb98e55b83ba9d3bd551f5_e6c08b53b4" value="">
</div>
<div class="clear">
<input type="submit" value="Save Money!" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>
</form>
</div>
<!-- End MailChimp Signup Form -->
</div>

I need to change the color of the icon on text input focus

I would like to incorporate a form focus feature where it changes the
color of each icon when you focus on that specific field
<div id="rightside">
<div th:replace="fragments/loginform">
<form method="post" id="login" th:object="${credential}">
<p id="errors" class="warning" role="alert">
<span th:each="err : ${#fields.errors('*')}" th:utext="${err}"/>
</p>
<p id="block">
<label for="username" class="has-feedback"><i class="fa fa-user" aria-hidden="true"></i></label>
<span th:if="${openIdLocalId}">
<strong>
<span th:utext="${openIdLocalId}"/>
</strong>
<input type="hidden"
id="username"
name="username"
th:value="${openIdLocalId}"/>
</span>
<span th:unless="${openIdLocalId}">
<input class="required textinput has-feedback"
placeholder="UH Username"
id="username"
size="14"
tabindex="1"
type="text"
th:field="*{username}"
th:accesskey="#{screen.welcome.label.netid.accesskey}"
autocomplete="off"
autocapitalize="off"
autocorrect="off"
required="required"
autofocus="autofocus"
/>
</span>
</p>
<p id="block">
<label for="password" class="fontawesome-lock"><i class="fa fa-lock" aria-hidden="true"></i></label>
<input class="required textinput"
placeholder="Password"
type="password"
id="password"
name="password"
size="14"
tabindex="2"
th:accesskey="#{screen.welcome.label.password.accesskey}"
th:field="*{password}"
autocomplete="off"
required="required"
/>
</p>
Here is the CSS
#rightside {
margin-top: 15px;
float: left;
width: 70%;
}
#rightside h3 {
font-size: 110%;
}
#rightside a {
display: block;
}
#rightside input.textinput {
width: 60%;
float: left;
padding-left: 5px;
height: 35px;
border-radius: 7px;
}
#rightside input.textinput:focus {
outline-width: 0;
}
#rightside form label {
background-color: #e1e1e1;
border-radius: 8px 0px 0px 8px;
border: solid 1px #CCC;
border-right: 1px solid #CCC;
color: #000;
display: block;
float: left;
line-height: 50px;
text-align: center;
font-size: 20px;
width: 15%;
height: 50px;
}
#rightside form input[type="text"] {
float: left;
background-color: #fff;
border-radius: 0px 8px 8px 0px;
color: #000;
padding: 0 3%;
width: 77%;
height: 50px;
}
#rightside form input[type="password"] {
float: left;
background-color: #fff;
border-radius: 0px 8px 8px 0px;
color: #000;
padding: 0 3%;
width: 77%;
height: 50px;
}
#rightside form input[type="submit"] {
float: left;
background: #e1e1e1;
width: 99%;
height: 50px;
border-radius: 5px;
border: solid 1px #978257;
margin-bottom: 1.5em;
color: black;
cursor: pointer;
transition: background 0.3s ease-in-out;
font-weight: 600;
}
#rightside form input[type="submit"]:hover {
background: #b6985a;
color: #fff;
}
When the user focuses on either text field, the font-awesome icon pertaining to that input field should change color. Any help would be great! Thanks! CSS only would be preferable, but a js would work too
I went ahead and made a codepen for you to show you the value of the following blog post:
https://css-tricks.com/snippets/jquery/highlight-related-label-when-input-in-focus/
Here's what it offers:
$("form :input").focus(function() {
$("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
$("label").removeClass("labelfocus");
});
The above utilizes jQuery and it works well as a conceptual example.
http://codepen.io/MassDebates/pen/ZBaVJL
If you wanted to do something that leverages CSS's :focus then I would suggest you change your markup to allow something like a sibling (~), adjacent/following sibling (+) or even a descendant selector if you wrap your input in the label.
The key here is to associate your label's icon (<i>) with your input element.
You can play with :focus and :blur pseudo-classes
$(document).ready(function(){
$(".username").focus(function(){
$(".fa-user").css("color","red");
console.log("in");
}).blur(function() {
$(".fa-user").css("color","yellow");
console.log('out');
});
$(".password").focus(function(){
$(".fa-lock").css("color","red");
console.log("in");
}).blur(function() {
$(".fa-lock").css("color","yellow");
console.log('out');
});
});
https://jsfiddle.net/czs3sy0a/2/
I have created a pen that sets a highlighted class on the parent p, and colors the icon using this CSS:
p.highlighted .fa {color: red;}
And this JS:
$(function() {
$('input').focusin(function() {
$(this).parent().parent().addClass('highlighted');
});
$('input').focusout(function() {
$(this).parent().parent().removeClass('highlighted');
});
});
http://codepen.io/anon/pen/pNdqYP
Here is a pure css solution you can use. As we know we dont have any way to select parent element along with css but we can get the next sibling element with the '+' selector. So what i have done is placed the label containing the icon right after the input that will change it's color when focused using the css :focus pseudo element along with the '+' selector of css to get the icon in the label next to the input focused.
In order to set the positions correctly after moving the labels in front of the inputs. I changed the input and label css class from float:left to float:right. This aligned them where label came before input and the width percentage i changed from 77% to 75% just to keep the responsiveness correct on smaller screens. Below is the sample code.
Sample Code: http://codepen.io/Nasir_T/pen/VmrgWw
Hope this helps you and any future coders who do not want work with a JS code solution.

How can the formatting of "Input-file" be changed? [duplicate]

How do you style an input type="file" button?
<input type="file" />
You don't need JavaScript for this! Here is a cross-browser solution:
See this example! - It works in Chrome/FF/IE - (IE10/9/8/7)
The best approach would be to have a custom label element with a for attribute attached to a hidden file input element. (The label's for attribute must match the file element's id in order for this to work).
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file"/>
As an alternative, you could also just wrap the file input element with a label directly: (example)
<label class="custom-file-upload">
<input type="file"/>
Custom Upload
</label>
In terms of styling, just hide1 the input element using the attribute selector.
input[type="file"] {
display: none;
}
Then all you need to do is style the custom label element. (example).
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
1 - It's worth noting that if you hide the element using display: none, it won't work in IE8 and below. Also be aware of the fact that jQuery validate doesn't validate hidden fields by default. If either of those things are an issue for you, here are two different methods to hide the input (1, 2) that work in these circumstances.
Styling file inputs are notoriously difficult, as most browsers will not change the appearance from either CSS or javascript.
Even the size of the input will not respond to the likes of:
<input type="file" style="width:200px">
Instead, you will need to use the size attribute:
<input type="file" size="60" />
For any styling more sophisticated than that (e.g. changing the look of the browse button) you will need to look at the tricksy approach of overlaying a styled button and input box on top of the native file input. The article already mentioned by rm at www.quirksmode.org/dom/inputfile.html is the best one I've seen.
UPDATE
Although it's difficult to style an <input> tag directly, this is easily possible with the help of a <label> tag. See answer below from #JoshCrozier: https://stackoverflow.com/a/25825731/10128619
follow these steps then you can create custom styles for your file upload form:
this is the simple HTML form(please read the HTML comments I have written here below)
<form action="#type your action here" method="POST" enctype="multipart/form-data">
<div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
<!-- this is your file input tag, so i hide it!-->
<div style='height: 0px;width:0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<input type="submit" value='submit' >
</form>
then use this simple script to pass the click event to file input tag.
function getFile(){
document.getElementById("upfile").click();
}
Now you can use any type of styling without worrying about how to change default styles.
I know this very well because I have been trying to change the default styles for a month and a half. believe me, it's very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms. Here is the full AUTOMATED UPLOAD code.
function getFile() {
document.getElementById("upfile").click();
}
function sub(obj) {
var file = obj.value;
var fileName = file.split("\\");
document.getElementById("yourBtn").innerHTML = fileName[fileName.length - 1];
document.myForm.submit();
event.preventDefault();
}
#yourBtn {
position: relative;
top: 150px;
font-family: calibri;
width: 150px;
padding: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px dashed #BBB;
text-align: center;
background-color: #DDD;
cursor: pointer;
}
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">click to upload a file</div>
<!-- this is your file input tag, so i hide it!-->
<!-- i used the onchange event to fire the form submission-->
<div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)" /></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<!-- <input type="submit" value='submit' > -->
</form>
All rendering engines automatically generate a button when an <input type="file"> is created. Historically, that button has been completely un-styleable. However, Trident and WebKit have added hooks through pseudo-elements.
Trident
As of IE10, the file input button can be styled using the ::-ms-browse pseudo-element. Basically, any CSS rules that you apply to a regular button can be applied to the pseudo-element. For example:
::-ms-browse {
background: black;
color: red;
padding: 1em;
}
<input type="file">
This displays as follows in IE10 on Windows 8:
WebKit
WebKit provides a hook for its file input button with the ::-webkit-file-upload-button pseudo-element. Again, pretty much any CSS rule can be applied, therefore the Trident example will work here as well:
::-webkit-file-upload-button {
background: black;
color: red;
padding: 1em;
}
<input type="file">
This displays as follows in Chrome 26 on OS X:
Hide it with css and use a custom button with $(selector).click() to activate the the browse button. then set an interval to check the value of the file input type. the interval can display the value for the user so the user can see whats getting uploaded. the interval will clear when the form is submitted [EDIT] Sorry i have been very busy was meaning to update this post, here is an example
<form action="uploadScript.php" method="post" enctype="multipart/form-data">
<div>
<!-- filename to display to the user -->
<p id="file-name" class="margin-10 bold-10"></p>
<!-- Hide this from the users view with css display:none; -->
<input class="display-none" id="file-type" type="file" size="4" name="file"/>
<!-- Style this button with type image or css whatever you wish -->
<input id="browse-click" type="button" class="button" value="Browse for files"/>
<!-- submit button -->
<input type="submit" class="button" value="Change"/>
</div>
$(window).load(function () {
var intervalFunc = function () {
$('#file-name').html($('#file-type').val());
};
$('#browse-click').on('click', function () { // use .live() for older versions of jQuery
$('#file-type').click();
setInterval(intervalFunc, 1);
return false;
});
});
::file-selector-button
https://developer.mozilla.org/en-US/docs/Web/CSS/::file-selector-button
This is a new selector that can be used to style the file selector button.
It has full support on recent browser versions.
input[type=file]::file-selector-button {
border: 2px solid #6c5ce7;
padding: .2em .4em;
border-radius: .2em;
background-color: #a29bfe;
transition: 1s;
}
input[type=file]::file-selector-button:hover {
background-color: #81ecec;
border: 2px solid #00cec9;
}
<form>
<label for="fileUpload">Upload file</label>
<input type="file" id="fileUpload">
</form>
Here is another snippet that demonstrates different styling:
.input_container {
border: 1px solid #e5e5e5;
}
input[type=file]::file-selector-button {
background-color: #fff;
color: #000;
border: 0px;
border-right: 1px solid #e5e5e5;
padding: 10px 15px;
margin-right: 20px;
transition: .5s;
}
input[type=file]::file-selector-button:hover {
background-color: #eee;
border: 0px;
border-right: 1px solid #e5e5e5;
}
<form>
<div class="input_container">
<input type="file" id="fileUpload">
</div>
</form>
I felt that this answer was needed as most answers here are outdated.
$('.new_Btn').click(function() {
$('#html_btn').click();
});
.new_Btn {
// your css propterties
}
#html_btn {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="new_Btn">SelectPicture</div><br>
<input id="html_btn" type='file' /><br>
You can reach your goals too without jQuery with normal JavaScript.
Now the newBtn is linkes with the html_btn and you can style your new btn like you want :D
If you are using Bootstrap 3, this worked for me:
See https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<span class="btn btn-primary btn-file">
Browse...<input type="file">
</span>
Which produces the following file input button:
Seriously, check out https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/
Working example here with native Drag and drop support : https://jsfiddle.net/j40xvkb3/
When styling a file input, you shouldn't break any of native interaction
the input provides.
The display: none approach breaks the native drag and drop support.
To not break anything, you should use the opacity: 0 approach for the input, and position it using relative / absolute pattern in a wrapper.
Using this technique, you can easily style a click / drop zone for the user, and add custom class in javascript on dragenter event to update styles and give user a feedback to let him see that he can drop a file.
HTML :
<label for="test">
<div>Click or drop something here</div>
<input type="file" id="test">
</label>
CSS :
input[type="file"] {
position: absolute;
left: 0;
opacity: 0;
top: 0;
bottom: 0;
width: 100%;
}
div {
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #ccc;
border: 3px dotted #bebebe;
border-radius: 10px;
}
label {
display: inline-block;
position: relative;
height: 100px;
width: 400px;
}
Here is a working example (with additional JS to handle dragover event and dropped files).
https://jsfiddle.net/j40xvkb3/
Hope this helped !
I am able to do it with pure CSS using below code. I have used bootstrap and font-awesome.
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
<label class="btn btn-default btn-sm center-block btn-file">
<i class="fa fa-upload fa-2x" aria-hidden="true"></i>
<input type="file" style="display: none;">
</label>
ONLY CSS
Use this very simple and EASY
.choose::-webkit-file-upload-button {
color: white;
display: inline-block;
background: #1CB6E0;
border: none;
padding: 7px 15px;
font-weight: 700;
border-radius: 3px;
white-space: nowrap;
cursor: pointer;
font-size: 10pt;
}
<label>Attach your screenshort</label>
<input type="file" multiple class="choose">
<label>
<input type="file" />
</label>
You can wrap your input type="file" inside of a label for the input. Style the label however you'd like and hide the input with display: none;
This approach gives you the whole flexibility! ES6 / VanillaJS!
html:
<input type="file" style="display:none;"></input>
<button>Upload file</button>
javascript:
document.querySelector('button').addEventListener('click', () => {
document.querySelector('input[type="file"]').click();
});
This hides the input-file button, but under the hood clicks it from another normal button, that you can obviously style like any other button. This is the only solution with no downside apart from a useless DOM-node. Thanks to display:none;, the input-button does not reserve any visible space in the DOM.
(I don't know anymore to whom to give props for this. But I got that idea from somewhere here on Stackoverflow.)
Put upload file button over your nice button or element and hide it.
Very simple and will work on any browser
<div class="upload-wrap">
<button type="button" class="nice-button">upload_file</button>
<input type="file" name="file" class="upload-btn">
</div>
Styles
.upload-wrap {
position: relative;
}
.upload-btn {
position: absolute;
left: 0;
opacity: 0;
}
Here is a solution which doesn't really style the <input type="file" /> element but instead uses a <input type="file" /> element on top of other elements (which can be styled). The <input type="file" /> element is not really visible hence, the overall illusion is of a nicely styled file upload control.
I came across this problem recently and despite the plethora of answers on Stack Overflow, none really seemed to fit the bill. In the end, I ended up customizing this so as to have a simple and an elegant solution.
I have also tested this on Firefox, IE (11, 10 & 9), Chrome and Opera, iPad and a few android devices.
Here's the JSFiddle link -> http://jsfiddle.net/umhva747/
$('input[type=file]').change(function(e) {
$in = $(this);
$in.next().html($in.val());
});
$('.uploadButton').click(function() {
var fileName = $("#fileUpload").val();
if (fileName) {
alert(fileName + " can be uploaded.");
}
else {
alert("Please select a file to upload");
}
});
body {
background-color:Black;
}
div.upload {
background-color:#fff;
border: 1px solid #ddd;
border-radius:5px;
display:inline-block;
height: 30px;
padding:3px 40px 3px 3px;
position:relative;
width: auto;
}
div.upload:hover {
opacity:0.95;
}
div.upload input[type="file"] {
display: input-block;
width: 100%;
height: 30px;
opacity: 0;
cursor:pointer;
position:absolute;
left:0;
}
.uploadButton {
background-color: #425F9C;
border: none;
border-radius: 3px;
color: #FFF;
cursor:pointer;
display: inline-block;
height: 30px;
margin-right:15px;
width: auto;
padding:0 20px;
box-sizing: content-box;
}
.fileName {
font-family: Arial;
font-size:14px;
}
.upload + .uploadButton {
height:38px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data">
<div class="upload">
<input type="button" class="uploadButton" value="Browse" />
<input type="file" name="upload" accept="image/*" id="fileUpload" />
<span class="fileName">Select file..</span>
</div>
<input type="button" class="uploadButton" value="Upload File" />
</form>
Hope this helps!!!
This is simple with jquery. To give a code example of Ryan's suggestion with a slight modification.
Basic html:
<div id="image_icon"></div>
<div id="filename"></div>
<input id="the_real_file_input" name="foobar" type="file">
Be sure to set the styling on the input when you're ready: opacity: 0
You can't set display: none because it needs to be clickable. But you can position it under the "new" button or tuck in under something else with z-index if you prefer.
Setup some jquery to click the real input when you click the image.
$('#image_icon').click(function() {
$('#the_real_file_input').click();
});
Now your button is working. Just cut and paste the value when changed.
$('input[type=file]').bind('change', function() {
var str = "";
str = $(this).val();
$("#filename").text(str);
}).change();
Tah dah! You may need to parse the val() to something more meaningful but you should be all set.
Here is a PURE CSS, Javascript-free, Bootstrap-free, 100% cross-browser solution! Just cut-and-paste one block of styles, then test your file upload control.
This solution does NOT attempt to hide then recreate the original HTML element like the other posts here do. It uses plain CSS without any circus tricks or third party tools to style the original file upload form control for all the major browsers. You do not need to even change your HTML code! Just cut-and-paste the code below into your web page to test it...
<style>
/* Note: This CSS will style all instances of
<input type=file /> controls in your website. */
input[type="file"],
input[type="file"]:visited,
input[type="file"]:hover,
input[type="file"]:focus,
input[type="file"]:active {
margin:0;
padding: 0em 0em;/* fallback: older browsers like IE 1-8 need "em" */
padding: 0rem 0rem;/* older browsers dont know what "rem" is */
overflow: hidden; /* long file names overflow so just hide the end */
background: #fff;
border-radius: .2em;
border-radius: .2rem;
outline: none;
border: 2px solid #bbb;
cursor: pointer;
-webkit-appearance: textfield;
-moz-appearance: textfield;
}
input[type="file"]:hover {
background: #f9f9ff; /* Optional rollover color: I am using a light blue to indicate an interaction */
border: 2px solid #999;
}
input[type="file"]:visited,
input[type="file"]:focus,
input[type="file"]:active {
background: #fff; /* Default back to white when focused. */
border: 2px solid #999;
}
/* Note: These "disabled" selectors blow up in IE so have to be separated from the same styles above. */
input[type="file"]:disabled {
margin: 0;
padding: 0em 0em;
padding: 0rem 0rem;
overflow: hidden; /* long file names overflow so just hide the end */
background: #ddd;
border-radius: .2em;
border-radius: .2rem;
outline: none;
border: 2px solid #bbb;
cursor: pointer;
-webkit-appearance: textfield;
-moz-appearance: textfield;
}
input[type="file"]:disabled:hover {
background: #ddd; /* disabled-readonly buttons should be grey */
border: 2px solid #999;
}
input[type="file"]:disabled:visited,
input[type="file"]:disabled:focus,
input[type="file"]:disabled:active {
background: #ddd; /* disabled-readonly buttons should be grey */
border: 2px solid #999;
}
/* IE UPLOAD BUTTON STYLE: This attempts to alter the file upload button style in IE. Keep in mind IE gives you limited design control but at least you can customize its upload button.*/
::-ms-browse { /* IE */
display: inline-block;
margin: 0;
padding: .2em .5em;
padding: .2rem .5rem;
text-align: center;
outline: none;
border: none;
background: #fff;
white-space: nowrap;
cursor: pointer;
}
/* FIREFOX UPLOAD BUTTON STYLE */
::file-selector-button {/* firefox */
display: inline-block;
margin: 0rem 1rem 0rem 0rem;
padding: .18em .5em;
padding: .18rem .5rem;
-webkit-appearance: button;
text-align: center;
border-radius: .1rem 0rem 0rem .1rem;
outline: none;
border: none;
border-right: 2px solid #bbb;
background: #eee;
white-space: nowrap;
cursor: pointer;
}
/* CHROME AND EDGE UPLOAD BUTTON STYLE */
::-webkit-file-upload-button { /* chrome and edge */
display: inline-block;
margin: 0rem 1rem 0rem 0rem;
padding: .19em .5em;
padding: .19rem .5rem;
-webkit-appearance: button;
text-align: center;
border-radius: .1rem 0rem 0rem .1rem;
outline: none;
border: none;
border-right: 2px solid #bbb;
background: #eee;
white-space: nowrap;
cursor: pointer;
}
</style>
<input type="file" id="fileupload" name="fileupload"
value="" tabindex="0" enctype="multipart/form-data"
accept="image/*" autocomplete="off" multiple="multiple"
aria-multiselectable="true" title="Multiple File Upload"
aria-label="Multiple File Upload" />
<br /><br />
<input disabled="disabled" type="file" id="fileupload"
name="fileupload" value="" tabindex="0"
enctype="multipart/form-data" accept="image/*"
autocomplete="off" multiple="multiple"
aria-multiselectable="true" title="Disabled Multiple File Upload"
aria-label="Disabled Multiple File Upload" />
This is what the file upload control looks like in Firefox, Chrome, and Edge using the CSS below. This is a very simple clean design. You can change it to look any way you like:
Internet Explorer gives you limited design control, but at least you can manipulate the control using CSS enough to change a few things, including rounded borders and colors:
The advantages to my solution are:
You stick with simple CSS to style the original HTML input control
You can see one or more file names in the file input textbox
Screen readers and ARIA-friendly devices can interact normally with your file upload control
You can set tabindex on your HTML element so its part of the tab order
Because you are using plain HTML and CSS, your file input button works perfectly in old and new browsers
ZERO JavaScript required!
Runs and loads lighting fast in even the oldest of browsers
Because your are not using "display:none" to hide the control, its file block stream data is never disabled from reaching the server in any old or new browser version known
You do not need goofy JavaScript tricks, Bootstrap, or to try and hide/recreate your file input control. That just destroys usability for everyone online. Styling the original HTML control means your file upload control is guaranteed to work well in 25 years worth of web browsers, old and new.
This is why you cannot trust all these scripted hacks here that erase, rewrite, or destroy HTML just to try and recreate some visual experience. That shows that you do not understand how HTML is used or why its been around for 30 years practically unchanged. You should never try and rewrite HTML's native form control functionality. Why? There is more to using natural HTML in websites than just manipulation of markup for some forced visual experience. The trade-offs of limited visual design in these replaced HTML elements was designed that way for a reason.
My advice: Stay with simple HTML and CSS solutions and you will have ZERO problems as a web developer.
<input type="file" name="media" style="display-none" onchange="document.media.submit()">
I would normally use simple javascript to customize the file input tag.A hidden input field,on click of button,javascript call the hidden field,simple solution with out any css or bunch of jquery.
<button id="file" onclick="$('#file').click()">Upload File</button>
VISIBILITY:hidden TRICK
I usually go for the visibility:hidden trick
this is my styled button
<div id="uploadbutton" class="btn btn-success btn-block">Upload</div>
this is the input type=file button. Note the visibility:hidden rule
<input type="file" id="upload" style="visibility:hidden;">
this is the JavaScript bit to glue them together. It works
<script>
$('#uploadbutton').click(function(){
$('input[type=file]').click();
});
</script>
Multiple file solution with converted filename
Bootstrap EXAMPLE
HTML:
<div>
<label class="btn btn-primary search-file-btn">
<input name="file1" type="file" style="display:None;"> <span>Choose file</span>
</label>
<span>No file selected</span>
</div>
<div>
<label class="btn btn-primary search-file-btn">
<input name="file2" type="file" style="display:None;"> <span>Choose file</span>
</label>
<span>No file selected</span>
</div>
1. JS with jQuery:
$().ready(function($){
$('.search-file-btn').children("input").bind('change', function() {
var fileName = '';
fileName = $(this).val().split("\\").slice(-1)[0];
$(this).parent().next("span").html(fileName);
})
});
2. JS without jQuery
Array.prototype.forEach.call(document.getElementsByTagName('input'), function(item) {
item.addEventListener("change", function() {
var fileName = '';
fileName = this.value.split("\\").slice(-1)[0];
this.parentNode.nextElementSibling.innerHTML = fileName;
});
});
the only way i can think of is to find the button with javascript after it gets rendered and assign a style to it
you might also look at this writeup
Here we use a span to trigger input of type file and we simply customized that span, so we can add any styling using this way.
Note that we use input tag with visibility:hidden option and trigger it in the span.
.attachFileSpan{
color:#2b6dad;
cursor:pointer;
}
.attachFileSpan:hover{
text-decoration: underline;
}
<h3> Customized input of type file </h3>
<input id="myInput" type="file" style="visibility:hidden"/>
<span title="attach file" class="attachFileSpan" onclick="document.getElementById('myInput').click()">
Attach file
</span>
Reference
Here is a solution, that also shows the chosen file name:
http://jsfiddle.net/raft9pg0/1/
HTML:
<label for="file-upload" class="custom-file-upload">Chose file</label>
<input id="file-upload" type="file"/>
File: <span id="file-upload-value">-</span>
JS:
$(function() {
$("input:file[id=file-upload]").change(function() {
$("#file-upload-value").html( $(this).val() );
});
});
CSS:
input[type="file"] {
display: none;
}
.custom-file-upload {
background: #ddd;
border: 1px solid #aaa;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
color: #444;
display: inline-block;
font-size: 11px;
font-weight: bold;
text-decoration: none;
text-shadow: 0 1px rgba(255, 255, 255, .75);
cursor: pointer;
margin-bottom: 20px;
line-height: normal;
padding: 8px 10px; }
This is a nice way to do it with material / angular file upload.
You could do the same with a bootstrap button.
Note I used <a> instead of <button> this allows the click events to bubble up.
<label>
<input type="file" (change)="setFile($event)" style="display:none" />
<a mat-raised-button color="primary">
<mat-icon>file_upload</mat-icon>
Upload Document
</a>
</label>
Maybe a lot of awnsers. But I like this in pure CSS with fa-buttons:
.divs {
position: relative;
display: inline-block;
background-color: #fcc;
}
.inputs {
position:absolute;
left: 0px;
height: 100%;
width: 100%;
opacity: 0;
background: #00f;
z-index:999;
}
.icons {
position:relative;
}
<div class="divs">
<input type='file' id='image' class="inputs">
<i class="fa fa-image fa-2x icons"></i>
</div>
<div class="divs">
<input type='file' id='book' class="inputs">
<i class="fa fa-book fa-5x icons"></i>
</div>
<br><br><br>
<div class="divs">
<input type='file' id='data' class="inputs">
<i class="fa fa-id-card fa-3x icons"></i>
</div>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
Fiddle: https://jsfiddle.net/zoutepopcorn/v2zkbpay/1/
Don't be fooled by "great" CSS-only solutions that are actually very browser-specific, or that overlay the styled button on top of the real button, or that force you to use a <label> instead of a <button>, or any other such hack. JavaScript IS necessary to get it working for general usage. Please study how gmail and DropZone do it if you don't believe me.
Just style a normal button however you want, then call a simple JS function to create and link a hidden input element to your styled button.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
button {
width : 160px;
height : 30px;
font-size : 13px;
border : none;
text-align : center;
background-color : #444;
color : #6f0;
}
button:active {
background-color : #779;
}
</style>
<button id="upload">Styled upload button!</button>
<script>
function Upload_On_Click(id, handler) {
var hidden_input = null;
document.getElementById(id).onclick = function() {hidden_input.click();}
function setup_hidden_input() {
hidden_input && hidden_input.parentNode.removeChild(hidden_input);
hidden_input = document.createElement("input");
hidden_input.setAttribute("type", "file");
hidden_input.style.visibility = "hidden";
document.querySelector("body").appendChild(hidden_input);
hidden_input.onchange = function() {
handler(hidden_input.files[0]);
setup_hidden_input();
};
}
setup_hidden_input();
}
Upload_On_Click("upload", function(file) {
console.log("GOT FILE: " + file.name);
});
</script>
Notice how the above code re-links it after every time the user chooses a file. This is important because "onchange" is only called if the user changes the filename. But you probably want to get the file every time the user provides it.
Update Nevermind, this doesn't work in IE or it's new brother, FF. Works on every other type of element as expected, but doesn't work on file inputs. A much better way to do this is to just create a file input and a label that links to it. Make the file input display none and boom, it works in IE9+ seamlessly.
Warning: Everything below this is crap!
By using pseudo elements positioned/sized against their container, we can get by with only one input file (no additional markup needed), and style as per usual.
Demo
<input type="file" class="foo">
<style>
.foo {
display: block;
position: relative;
width: 300px;
margin: auto;
cursor: pointer;
border: 0;
height: 60px;
border-radius: 5px;
outline: 0;
}
.foo:hover:after {
background: #5978f8;
}
.foo:after {
transition: 200ms all ease;
border-bottom: 3px solid rgba(0,0,0,.2);
background: #3c5ff4;
text-shadow: 0 2px 0 rgba(0,0,0,.2);
color: #fff;
font-size: 20px;
text-align: center;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
content: 'Upload Something';
line-height: 60px;
border-radius: 5px;
}
</style>
Enjoy guys!
Old Update
Turned this into a Stylus mixin. Should be easy enough for one of you cool SCSS cats to convert it.
file-button(button_width = 150px)
display block
position relative
margin auto
cursor pointer
border 0
height 0
width 0
outline none
&:after
position absolute
top 0
text-align center
display block
width button_width
left -(button_width / 2)
Usage:
<input type="file">
input[type="file"]
file-button(200px)
I've found a very easy method to switch the file button to a picture.
You just label a picture and place it on top of the file button.
<html>
<div id="File button">
<div style="position:absolute;">
<!--This is your labeled image-->
<label for="fileButton"><img src="ImageURL"></label>
</div>
<div>
<input type="file" id="fileButton"/>
</div>
</div>
</html>
When clicking on the labeled image, you select the file button.
This week I also needed to custom the button and display the selected file name aside it, so after reading some of the answers above (Thanks BTW) I came up with the following implementation:
HTML:
<div class="browse">
<label id="uploadBtn" class="custom-file-upload">Choose file
<input type="file" name="fileInput" id="fileInput" accept=".yaml" ngf-select ngf-change="onFileSelect($files)" />
</label>
<span>{{fileName}}</span>
</div>
CSS
input[type='file'] {
color: #a1bbd5;
display: none;
}
.custom-file-upload {
border: 1px solid #a1bbd5;
display: inline-block;
padding: 2px 8px;
cursor: pointer;
}
label{
color: #a1bbd5;
border-radius: 3px;
}
Javascript (Angular)
app.controller('MainCtrl', function($scope) {
$scope.fileName = 'No file chosen';
$scope.onFileSelect = function ($files) {
$scope.selectedFile = $files;
$scope.fileName = $files[0].name;
};
});
Basically I'm working with ng-file-upload lib, Angular-wise I'm binding the filename to my $scope and giving it the initial value of 'No file chosen', I'm also binding the onFileSelect() function to my scope so when a file gets selected I'm getting the filename using ng-upload API and assign it to the $scope.filename.
Simply simulate a click on the <input> by using the trigger() function when clicking on a styled <div>. I created my own button out of a <div> and then triggered a click on the input when clicking my <div>. This allows you to create your button however you want because it's a <div> and simulates a click on your file <input>. Then use display: none on your <input>.
// div styled as my load file button
<div id="simClick">Load from backup</div>
<input type="file" id="readFile" />
// Click function for input
$("#readFile").click(function() {
readFile();
});
// Simulate click on the input when clicking div
$("#simClick").click(function() {
$("#readFile").trigger("click");
});

Categories