How to implement successive jquery functions- select followed by keypress/keydown - html

I'm trying to simulate keypress by buttons using jquery. But cannot figure out how buttons can trigger a select/click followed by a keypress/keydown event. Can someone please help?
Requirement: Whenever I press the + or - button, it should slide the dot right or left and it should update the year
My code is
$("#range").on("change", function() {
$("#year").html($(this).val());
});
$("#down-year").on("click", function() {
$("#range").trigger("select").trigger("keypress", function(e) {
e.which = 37; //Left arrow
})
});
$("#up-year").on("click", function() {
$("#range").trigger("select").trigger("keypress", function(e) {
e.which = 39; //Right arrow
})
});
.slidecontainer {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 100%;
height: 5px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: #28A745;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 15px;
height: 15px;
border-radius: 50%;
background: #28A745;
cursor: pointer;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slidecontainer text-center">
<input type="range" min="1966" max="2015" value="2015" class="slider" id="range">
<div class="row">
<div class="col-sm-1">
<button id="down-year">
<i class="fa fa-minus-circle" aria-hidden="true"></i>
</button>
</div>
<div class="col-sm-10">
<small>Year: <strong id="year" class="text-success">2015</strong></small>
</div>
<div class="col-sm-1">
<button id="up-year">
<i class="fa fa-plus-circle" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
And how I'm trying with jQuery [Even tried swapping keypress with keydown]:

You don't really have to call the keyup/keydown/keypress events. The way you've got it setup right now you can just increment the range value by 1, up or down. Also it would probably be better to create an "updateLabel()" function instead of triggering another event.
JQuery:
$("#down-year").on("click", function() {
var newVal = parseInt($("#range").val()) - 1;
$("#range").val(newVal);
updateLabel(newVal);
});
$("#up-year").on("click", function() {
var newVal = parseInt($("#range").val()) + 1;
$("#range").val(newVal);
updateLabel(newVal);
});
function updateLabel(num){
$("#year").html(num);
}
Just make sure you parseInt on the value otherwise it will read a string and you'll concatenate a 1 on the end of the value (e.g. range at 2001 when you click, $("#range").val() + 1 will equal 20011, which will shoot your slider to the max value of 2015).

Related

Focus an input field after appending with jQuery

I want to append an input field on click, and focus it so that it has a blinking cursor and can be typed directly. With the following code I am able to append it but i doesn't focus. I first need to click on the field and then I can type.
How can I append and focus?
I have tried following line but it doesn't do anything
$('.fields').append(field_html).focus();
HTML:
<div class="fields">
<!-- append here -->
</div>
<div class="row">
<input name="input" class="input">
</div>
<button>Add</button>
JS:
$('button').on('click', function(e){
var field_html = $('.row').html();
$('.fields').append(field_html);
});
CSS:
.input{
padding: 10px 10px;
border: 1px solid blue;
width: 300px;
margin-bottom: 10px;
}
.row {
display: none;
}
$('button').on('click', function(e){
var field_html = $('.row').html();
$('.fields').append(field_html);
});
.input{
padding: 10px 10px;
border: 1px solid blue;
width: 300px;
margin-bottom: 10px;
}
.row {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fields">
<!-- append here -->
</div>
<div class="row">
<input name="input" class="input">
</div>
<button>Add</button>
JSFiddle:
https://jsfiddle.net/sLob7cwh/
$('button').on('click', function(e){
var field_html = $('.row').html();
$('.fields').append(field_html).find('input:last').focus();
});
.input{
padding: 10px 10px;
border: 1px solid blue;
width: 300px;
margin-bottom: 10px;
}
.row {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fields">
<!-- append here -->
</div>
<div class="row">
<input name="input" class="input">
</div>
<button>Add</button>
this code works and will add focus to the latest added input
$('button').on('click', function(e){
var field_html = $('.row').html();
$('.fields').append(field_html).find('input:last').focus();
});
fiddle
JQuery methods generally chain the collections, in the case of .append it passes through the original collection.
Instead, you can use .appendTo which passes through the new html (as it's the original collection)
Change
var container = $("container").append("new_html");
to
var newElements = $("new_html").appendTo("container");
You can then use that result going forward, so your code becomes:
$('button').on('click', function(e){
var field_html = $('.row').html();
$(field_html).appendTo(".fields").find("input.input").focus();
});

How to create a box around around controls in webprgramming

I have a few controls that I am attempting to encapsulate on my webpage. I have tried a few different methods on encapsulating my controls and they have not succeeded. I tried using a div and this did not work too well and I have also tried this post:
Create a group box around certain controls on a web form using CSS
What is happening is that a box is being created but it is at the top of my webpage instead of around the controls.
I would like to create a grey box similar to the ones found on this webpage:
https://img.labnol.org/di/trigger1.png
Below, I am attaching a copy of the CSS and HTML code that I am using in order to create my form. The form is a simple file upload form that I tweaked from an example. I am using this on my own, personal website.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
//_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
document.getElementById('p1').innerHTML = "Drag your file here or click in this area.";
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
function changeText()
{
document.getElementById('p1').innerHTML = "1 file selected";
}
</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h2>Upload</h2>
<fieldset>
<legend>Group 1</legend>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<p id="p1">Drag your file here or click in this area.</p>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:508px; margin-left: -4px; margin-top: 10px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</fieldset>
<script>
// self executing function here
(function() {
document.getElementById('upload_form')[0].onchange = changeText;
})();
</script>
</body>
</html>
Here is the CSS (which is referred to in the html as test.css):
body{
background: rgba(0,0,0,0.0);
}
form{
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -250px;
width: 500px;
height: 200px;
border: 4px dashed #0D0D0D;
}
form p{
width: 100%;
height: 100%;
text-align: center;
line-height: 140px;
color: #0D0D0D;
font-family: Arial;
}
h2{
text-align: center;
}
form input[type="file"]{
position: absolute;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
outline: none;
opacity: 0;
}
form input[type="button"]{
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 508px;
height: 35px;
margin-top: -20px;
margin-left: -4px;
border-radius: 4px;
border-bottom: 4px solid #117A60;
transition: all .2s ease;
outline: none;
}
form input[type="button"]:hover{
background: #149174;
color: #0C5645;
}
form input[type="button"]:active{
border:0;
}
form progressBar{
text-align: center;
}
Coming back to the HTML, the fieldset tags are placed around the controls that I am attempting to encapsulate. I left them there so that anyone can see the main issue that I am running into.
I apologize but I am very new to web programming. Any help will be greatly appreciated, thank you.
Note: how the box is created doesn't really matter to me. I would expect that the box is created in HTML and then I can style it using CSS.
The structure of your HTML is fine, but the position: absolute properties in your CSS are clashing with the fieldset.
Since <fieldset> is wrapping all your controls, I would suggeset giving it a fixed width and height and position your child elements based on that, i.e. use width: 100% for your children and give all of them the same margin so they align nicely. Also make sure you either edit your #progressBar style in the markup.
Here's a snippet with the changes I just mentioned:
body {
background: rgba(0, 0, 0, 0.0);
}
fieldset {
width: 508px;
height: 270px;
/* fixed width and height*/
margin: 13vh auto;
}
#p1 {
border: 4px dashed #0D0D0D;
/* modified the actual text box instead of the entire form */
width: 508px;
height: 140px;
line-height: 140px;
margin-top: 0px;
}
form p {
text-align: center;
color: #0D0D0D;
font-family: Arial;
}
h2 {
text-align: center;
}
form input[type="file"] {
position: absolute;
margin: 0;
outline: none;
width: 508px;
height: 140px;
margin: 22px 4px;
opacity: 1;
background-color: orange;
/* Last two properties are a visual representation. Delete background-color and set opacity to 0 */
}
form input[type="button"] {
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 100%;
/* width relative to parent fieldset */
height: 35px;
margin-top: -20px;
border-radius: 4px;
border-bottom: 4px solid #117A60;
transition: all .2s ease;
outline: none;
}
form input[type="button"]:hover {
background: #149174;
color: #0C5645;
}
form input[type="button"]:active {
border: 0;
}
form progressBar {
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
//_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
document.getElementById('p1').innerHTML = "Drag your file here or click in this area.";
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
function changeText() {
document.getElementById('p1').innerHTML = "1 file selected";
}
</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h2>Upload</h2>
<fieldset>
<legend>Group 1</legend>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<p id="p1">Drag your file here or click in this area.</p>
<input type="button" value="Upload File" onclick="uploadFile()">
<!-- changed progressBar style -->
<progress id="progressBar" value="0" max="100" style="width:100%; margin-top: 10px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</fieldset>
<script>
// self executing function here
(function() {
document.getElementById('upload_form')[0].onchange = changeText;
})();
</script>
</body>
</html>
Hope it helps!

How to make an image a 'jump to' button?

I have a small icon image of 'Arrow Up' at the bottom of my page.
How do I make this image a clickable button that jumps to the top of the page?
I am new to HTML and this is my first project so please bear with me.
So far I have tried:
input type="button" id="btnx" style="background-image:url('arrowup.png')"
Try this: Wrap your image in an anchor (A tag) link "#" will go to top
<img src="/some-image-folder/arrowup.png">
maybe your html is like this:
<i class="fa fa-arrow-up" aria-hidden="true"></i>
maybe you'd like to use the input button? Ok:
<form>
<input type="button" value="Click me" onclick="$(window).scrollTop(0);">
</form>
If you dont want to just jump to the top here is an animated method.
Animated with Image:
function topFunction() {
if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) {
window.scrollBy(0, -50);
requestAnimationFrame(topFunction);
}
}
.test {
background-color: lightgrey;
padding: 30px;
height: 2500px;
margin-bottom: 10px;
}
<div class="test">Scroll to Bottom</div>
<img alt="Click" src="/images/arrowup.png">
Animated with Symbol:
function topFunction() {
if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) {
window.scrollBy(0, -50);
requestAnimationFrame(topFunction);
}
}
.test {
background: lightgrey;
padding: 30px;
height: 2500px;
margin-bottom: 10px;
}
.uparrow {
color: white;
background: black;
font-size: 22px;
padding: 5px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div class="test">Scroll to Bottom</div>
<i class="material-icons uparrow"></i>
Check this FIDDLE
HTML
<h1>Top of the page</h1>
<article style="height: 1000px">
<p style="margin-bottom: 600px">Scroll down the page…</p>
<p>Then click the box.</p>
Scroll
</article>
Script
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
$('.scrollup').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});

How best to make a smileys box in html

I'd like to add a box containing smileys icons above the comment area which opens using jQuery on click. What I come up with is this:
<div class="emo">
<i href="#" id="showhide_emobox"> </i>
<div id="emobox">
<input class="emoticon" id="icon-smile" type="button" value=":)" />
<input class="emoticon" id="icon-sad" type="button" value=":(" />
<input class="emoticon" id="icon-widesmile" type="button" value=":D" /> <br>
</div>
</div>
css:
.emoticon-smile{
background: url('../smileys/smile.png');
}
#icon-smile {
border: none;
background: url('../images/smile.gif') no-repeat;
}
jQuery:
// =======show hide emoticon div============
$('#showhide_emobox').click(function(){
$('#emobox').toggle();
$(this).toggleClass('active');
});
// ============add emoticons============
$('.emoticon').click(function() {
var textarea_val = jQuery.trim($('.user-comment').val());
var emotion_val = $(this).attr('value');
if (textarea_val =='') {
var sp = '';
} else {
var sp = ' ';
}
$('.user-comment').focus().val(textarea_val + sp + emotion_val + sp);
});
However I have difficulty placing buttons in a nice array and make background image for them (the button values appear before image and the array is not perfectly rectangular. So I'm wondering maybe this is not the best way to render this box.
Any ideas to do this properly?
First show images, on hover hide image and show text. No need for input elements to get text of Dom Node
Something like this:
$(document).ready(function() {
$(".wrapper").click(function() {
var value = $(this).find(".smily-text").text();
console.log(value);
alert("Smily text is '" + value + "'");
});
});
.smily {
background: url(http://www.smiley-lol.com/smiley/manger/grignoter/vil-chewingum.gif) no-repeat center center;
width: 45px;
height: 45px;
}
.smily-text {
display: none;
font-size: 20px;
text-align: center;
line-height: 45px;
height: 45px;
width: 45px;
}
.wrapper {
border: 1px solid red;
float: left;
cursor: pointer;
}
.wrapper:hover .smily {
display: none;
}
.wrapper:hover .smily-text {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:)</div>
</div>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:(</div>
</div>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:]</div>
</div>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:[</div>
</div>

How to customize <input type="file">?

Is it possible to change the appearance of <input type="file">?
You can’t modify much about the input[type=file] control itself.
Since clicking a label element correctly paired with an input will activate/focus it, we can use a label to trigger the OS browse dialog.
Here is how you can do it…
label {
cursor: pointer;
/* Style as you please, it will become the visible UI component. */
}
#upload-photo {
opacity: 0;
position: absolute;
z-index: -1;
}
<label for="upload-photo">Browse...</label>
<input type="file" name="photo" id="upload-photo" />
The CSS for the form control will make it appear invisible and not take up space in the document layout, but will still exist so it can be activated via the label.
If you want to display the user’s chosen path after selection, you can listen for the change event with JavaScript and then read the path that the browser makes available to you (for security reasons it can lie to you about the exact path). A way to make it pretty for the end user is to simply use the base name of the path that is returned (so the user simply sees the chosen filename).
There is a great guide by Tympanus for styling this.
Something like that maybe?
<form>
<input id="fileinput" type="file" style="display:none;"/>
</form>
<button id="falseinput">El Cucaratcha, for example</button>
<span id="selected_filename">No file selected</span>
<script>
$(document).ready( function() {
$('#falseinput').click(function(){
$("#fileinput").click();
});
});
$('#fileinput').change(function() {
$('#selected_filename').text($('#fileinput')[0].files[0].name);
});
</script>
<label for="fusk">dsfdsfsd</label>
<input id="fusk" type="file" name="photo" style="display: none;">
why not? ^_^
See the example here
If you're using Bootstrap here is a better solution:
<label class="btn btn-default btn-file">
Browse <input type="file" style="display: none;" required>
</label>
For IE8 and below: https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/#legacy-approach-(ie8-and-below)
Source: https://stackoverflow.com/a/18164555/625952
Easiest way..
<label>
Upload
<input type="file" style="visibility: hidden;"/>
</label>
The trick is hide the input and customize the label.
HTML:
<div class="inputfile-box">
<input type="file" id="file" class="inputfile" onchange='uploadFile(this)'>
<label for="file">
<span id="file-name" class="file-box"></span>
<span class="file-button">
<i class="fa fa-upload" aria-hidden="true"></i>
Select File
</span>
</label>
</div>
CSS:
.inputfile-box {
position: relative;
}
.inputfile {
display: none;
}
.container {
display: inline-block;
width: 100%;
}
.file-box {
display: inline-block;
width: 100%;
border: 1px solid;
padding: 5px 0px 5px 5px;
box-sizing: border-box;
height: calc(2rem - 2px);
}
.file-button {
background: red;
padding: 5px;
position: absolute;
border: 1px solid;
top: 0px;
right: 0px;
}
JS:
function uploadFile(target) {
document.getElementById("file-name").innerHTML = target.files[0].name;
}
You can check this example: https://jsfiddle.net/rjurado/hnf0zhy1/4/
In webkit you can try this out...
input[type="file"]::-webkit-file-upload-button{
/* style goes here */
}
first of all it's a container:
<div class="upload_file_container">
Select file!
<input type="file" name="photo" />
</div>
The second, it's a CSS style, if you want to real more customization, just keeping your eyes is open :)
.upload_file_container{
width:100px;
height:40px;
position:relative;
background(your img);
}
.upload_file_container input{
width:100px;
height:40px;
position:absolute;
left:0;
top:0;
cursor:pointer;
}
This example hasn't style for text inside the button, it depends on font-size, just correct the height and padding-top values for container
It's much better if you just use a <label>, hide the <input>, and customize the label.
HTML:
<input type="file" id="input">
<label for="input" id="label">Choose File</label>
CSS:
input#input{
display: none;
}
label#label{
/* Customize your label here */
}
Bootstrap example
<label className="btn btn-info btn-lg">
Upload
<input type="file" style="display: none" />
</label>
Here is a quick pure CSS workaround (works on chrome and has a FireFox fallback included), including the file name,a label and an custom upload button, does what it should - no need for JavaScript at all! 🎉
Note: ☝ anyways, I would not use it on a real world website - if browser compatibility is a thing to you (what it should be). So it's more kind of experimental, otherwise while time goes by, it could be that this isn't an issue today.
.fileUploadInput {
display: grid;
grid-gap: 10px;
position: relative;
z-index: 1; }
.fileUploadInput label {
display: flex;
align-items: center;
color: setColor(primary, 0.5);
background: setColor(white);
transition: .4s ease;
font-family: arial, sans-serif;
font-size: .75em;
font-weight: regular; }
.fileUploadInput input {
position: relative;
z-index: 1;
padding: 0 gap(m);
width: 100%;
height: 50px;
border: 1px solid #323262;
border-radius: 3px;
font-family: arial, sans-serif;
font-size: 1rem;
user-select: none;
cursor: pointer;
font-weight: regular; }
.fileUploadInput input[type="file"] {
padding: 0 gap(m); }
.fileUploadInput input[type="file"]::-webkit-file-upload-button {
visibility: hidden;
margin-left: 10px;
padding: 0;
height: 50px;
width: 0; }
.fileUploadInput button {
position: absolute;
right: 0;
bottom: 0;
width: 50px;
height: 50px;
line-height: 0;
user-select: none;
color: white;
background-color: #323262;
border-radius: 0 3px 3px 0;
font-family: arial, sans-serif;
font-size: 1rem;
font-weight: 800; }
.fileUploadInput button svg {
width: auto;
height: 50%; }
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
border: 0px;
outline: 0;
background-repeat: no-repeat;
appearance: none;
border-radius: 0;
vertical-align: middle;
font-weight: inherit;
font-style: inherit;
font-family: inherit;
text-decoration: none;
list-style: none;
user-select: text;
line-height: 1.333em; }
body {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100vh;
background: rgba(66, 50, 98, 0.05); }
.container {
padding: 25px;
box-shadow: 0 0 20px rgba(66, 50, 98, 0.35);
border: 1px solid #eaeaea;
border-radius: 3px;
background: white; }
#-moz-document url-prefix() {
.fileUploadInput button{
display: none
}
}
<!-- Author: Ali Soueidan-->
<!-- Author URI: https//: www.alisoueidan.com-->
<div class="container">
<div class="fileUploadInput">
<label>✨ Upload File</label>
<input type="file" />
<button>+</button></div>
</div>
to show path of selected file you can try this
on html :
<div class="fileinputs">
<input type="file" class="file">
</div>
and in javascript :
var fakeFileUpload = document.createElement('div');
fakeFileUpload.className = 'fakefile';
var image = document.createElement('div');
image.className='fakebtn';
image.innerHTML = 'browse';
fakeFileUpload.appendChild(image);
fakeFileUpload.appendChild(document.createElement('input'));
var x = document.getElementsByTagName('input');
for (var i=0;i<x.length;i++) {
if (x[i].type != 'file') continue;
if (x[i].parentNode.className != 'fileinputs') continue;
x[i].className = 'file hidden';
var clone = fakeFileUpload.cloneNode(true);
x[i].parentNode.appendChild(clone);
x[i].relatedElement = clone.getElementsByTagName('input')[0];
x[i].onchange = x[i].onmouseout = function () {
this.relatedElement.value = this.value;
}
}
and style :
div.fileinputs {
position: relative;
height: 30px;
width: 370px;
}
input.file.hidden {
position: relative;
text-align: right;
-moz-opacity: 0;
filter: alpha(opacity: 0);
opacity: 0;
z-index: 2;
}
div.fakefile {
position: absolute;
top: 0px;
left: 0px;
right: 0;
width: 370px;
padding: 0;
margin: 0;
z-index: 1;
line-height: 90%;
}
div.fakefile input {
margin-bottom: 5px;
margin-left: 0;
border: none;
box-shadow: 0px 0px 2px 1px #ccc;
padding: 4px;
width: 241px;
height: 20px;
}
div.fakefile .fakebtn{
width: 150px;
background: #eb5a41;
z-index: 10;
font-family: roya-bold;
border: none;
padding: 5px 15px;
font-size: 18px;
text-align: center;
cursor: pointer;
-webkit-transition: all 0.4s ease;
-moz-transition: all 0.4s ease;
-o-transition: all 0.4s ease;
-ms-transition: all 0.4s ease;
transition: all 0.4s ease;
display: inline;
margin-left: 3px;
}
div.fileinputs input[type="file"]:hover + div .fakebtn{
background: #DA472E;
}
div.fileinputs input[type="file"] {
opacity: 0;
position: absolute;
top: -6px;
right: 0px;
z-index: 20;
width: 102px;
height: 40px;
cursor: pointer;
}
Here is one way which I like because it makes the input fill out the whole container. The trick is the "font-size: 100px", and it need to go with the "overflow: hidden" and the relative position.
<div id="upload-file-container" >
<input type="file" />
</div>
#upload-file-container {
width: 200px;
height: 50px;
position: relative;
border: dashed 1px black;
overflow: hidden;
}
#upload-file-container input[type="file"]
{
margin: 0;
opacity: 0;
font-size: 100px;
}
I went for this option which clarifies how to fully customize the browse button by including an handler of the uploaded file name, also customized.
It adds additional fields and client-side controls on them just to show how to include the browse in a "real" form, not just a standalone.
Here's the codepen: http://codepen.io/emiemi/pen/zxNXWR
JS:
//click on our custom btn triggers a click on the hidden actual file input
$("#btnup").click(function(){
$("#fileup").click();
});
//changes on the three fields (input, tit,and name) trigger a control which checks if the 3 fields are all filled and if file field is valid (an image is uploaded)
$('#fileup').change(function(){
var formDOMObj = document.upload;
//here we assign tu our text field #fileup the name of the selected file
var res=$('#fileup').val();
var arr = res.split("\\");
//if file is not valid we show the error icon and the red alert
if (formDOMObj.fileup.value.indexOf(".jpg") == -1 && formDOMObj.fileup.value.indexOf(".png") == -1 && formDOMObj.fileup.value.indexOf(".jpeg") == -1 && formDOMObj.fileup.value.indexOf(".bmp") == -1 && formDOMObj.fileup.value.indexOf(".JPG") == -1 && formDOMObj.fileup.value.indexOf(".PNG") == -1 && formDOMObj.fileup.value.indexOf(".JPEG") == -1 && formDOMObj.fileup.value.indexOf(".BMP") == -1){
$( ".imgupload" ).hide("slow");
$( ".imguploadok" ).hide("slow");
$( ".imguploadstop" ).show("slow");
$('#nomefile').css({"color":"red","font-weight":700});
$('#nomefile').html("The file "+arr.slice(-1)[0]+" is not an image!");
$( "#bottone" ).hide();
$( "#fakebtn" ).show();
}else{
//if file is valid we show the green alert
$( ".imgupload" ).hide("slow");
$( ".imguploadstop" ).hide("slow");
$( ".imguploadok" ).show("slow");
$('#nomefile').html(arr.slice(-1)[0]);
$('#nomefile').css({"color":"green","font-weight":700});
if (formDOMObj.nome.value!=""&&formDOMObj.tit.value!=""&&formDOMObj.fileup.value!=""){
//if all three fields are valid the fake input btn is hidden and the actual one i s finally hown
$( "#fakebtn" ).hide();
$( "#bottone" ).show();
}
}
});
$('#nome').change(function(){
//same as file change but on name field
var formDOMObj = document.upload;
if (formDOMObj.nome.value!=""&&formDOMObj.tit.value!=""&&formDOMObj.fileup.value!=""){
$( "#fakebtn" ).hide();
$( "#bottone" ).show();
}else{
$( "#bottone" ).hide();
$( "#fakebtn" ).show();
}
});
$('#tit').change(function(){
//same as file change but on tit field
var formDOMObj = document.upload;
if (formDOMObj.nome.value!=""&&formDOMObj.tit.value!=""&&formDOMObj.fileup.value!=""){
$( "#fakebtn" ).hide();
$( "#bottone" ).show();
}else{
$( "#bottone" ).hide();
$( "#fakebtn" ).show();
}
});
HTML:
<form name="upload" method="post" action="/" enctype="multipart/form-data" accept-charset="utf-8">
<div class="row">
<div class="col-md-6 center">
<!--this is the actual file input, s hidden beacause we wanna use our custom one-->
<input type="file" value="" class="hidden" name="fileup" id="fileup">
<div class="btn-container">
<!--the three icons: default, ok file (img), error file (not an img)-->
<h1 class="imgupload"><i class="fa fa-file-image-o"></i></h1>
<h1 class="imguploadok"><i class="fa fa-check"></i></h1>
<h1 class="imguploadstop"><i class="fa fa-times"></i></h1>
<!--this field changes dinamically displaying the filename we are trying to upload-->
<p id="nomefile">Only pics allowed! (jpg,jpeg,bmp,png)</p>
<!--our custom btn which triggers the actual hidden one-->
<button type="button" id="btnup" class="btn btn-primary btn-lg">Browse for your pic!</button>
</div>
</div>
<!--additional fields-->
<div class="col-md-6">
<div class="row">
<div class="form-group" id="top">
<div class="col-md-12">
<input type="text" maxlength="100" class="form-control" name="nome" id="nome" placeholder="Your Name">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<input type="text" maxlength="50" class="form-control" name="tit" id="tit" placeholder="I am rubber, you are glue">
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<p class="white">All fields are mandatory</p>
</div>
<div class="col-md-4">
<!--the defauld disabled btn and the actual one shown only if the three fields are valid-->
<input type="submit" value="Submit!" class="btn btn-primary" id="bottone" style="padding-left:50px; padding-right:50px; display:none;">
<button type="button" class="btn btn-default" disabled="disabled" id="fakebtn" style="padding-left:40px; padding-right:40px;">Submit! <i class="fa fa-minus-circle"></i></button>
</div>
</div>
</div>
</div>
$(document).ready(function () {
$(document).mousemove(function () {
$('#myList').css('display', 'block');
$("#seebtn").css('display', 'none');
$("#hidebtn").css('display', 'none');
$('#displayFileNames').html('');
$("#myList").html('');
var fileArray1 = document.getElementsByClassName('file-input');
for (var i = 0; i < fileArray1.length; i++) {
var files = fileArray1[i].files;
for (var j = 0; j < files.length; j++) {
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");
}
};
if (($("#myList").html()) != '') {
$('#unselect').css('display', 'block');
$('#divforfile').css('color', 'green');
$('#attach').css('color', 'green');
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');
};
if (($("#myList").html()) == '') {
$('#divforfile').css('color', 'black');
$('#attach').css('color', 'black');
$('#displayFileNames').append('Nessun File Selezionato');
};
});
});
function choosefiles(obj) {
$(obj).hide();
$('#myList').css('display', 'none');
$('#hidebtn').css('display', 'none');
$("#seebtn").css('display', 'none');
$('#unselect').css('display', 'none');
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");
$('#displayFileNames').html('');
}
$(document).ready(function () {
$('#unselect').click(function () {
$('#hidebtn').css('display', 'none');
$("#seebtn").css('display', 'none');
$('#displayFileNames').html('');
$("#myList").html('');
$('#myFileInput').val('');
document.getElementById('upload-form').reset();
$('#unselect').css('display', 'none');
$('#divforfile').css('color', 'black');
$('#attach').css('color', 'black');
});
});
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.divs {
position: absolute;
display: inline-block;
background-color: #fff;
}
.inputs {
position: absolute;
left: 0px;
height: 2%;
width: 15%;
opacity: 0;
background: #00f;
z-index: 100;
}
.icons {
position: absolute;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>
<div class="divs" id="divforfile" style="color:black">
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>
</div>
</form>
<br />
</div>
<br />
<div>
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">
<span style="color:red">×</span>
</button>
<div id="displayFileNames">
</div>
<ul id="myList"></ul>
</div>
This is my fully functional customerized file upload/Attachment using jquery & javascript (Visual studio). This will be useful !
Code will be available at the comment section !
Link : https://youtu.be/It38OzMAeig
Enjoy :)
$(document).ready(function () {
$(document).mousemove(function () {
$('#myList').css('display', 'block');
$("#seebtn").css('display', 'none');
$("#hidebtn").css('display', 'none');
$('#displayFileNames').html('');
$("#myList").html('');
var fileArray1 = document.getElementsByClassName('file-input');
for (var i = 0; i < fileArray1.length; i++) {
var files = fileArray1[i].files;
for (var j = 0; j < files.length; j++) {
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");
}
};
if (($("#myList").html()) != '') {
$('#unselect').css('display', 'block');
$('#divforfile').css('color', 'green');
$('#attach').css('color', 'green');
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');
};
if (($("#myList").html()) == '') {
$('#divforfile').css('color', 'black');
$('#attach').css('color', 'black');
$('#displayFileNames').append('Nessun File Selezionato');
};
});
});
function choosefiles(obj) {
$(obj).hide();
$('#myList').css('display', 'none');
$('#hidebtn').css('display', 'none');
$("#seebtn").css('display', 'none');
$('#unselect').css('display', 'none');
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");
$('#displayFileNames').html('');
}
$(document).ready(function () {
$('#unselect').click(function () {
$('#hidebtn').css('display', 'none');
$("#seebtn").css('display', 'none');
$('#displayFileNames').html('');
$("#myList").html('');
$('#myFileInput').val('');
document.getElementById('upload-form').reset();
$('#unselect').css('display', 'none');
$('#divforfile').css('color', 'black');
$('#attach').css('color', 'black');
});
});
<style>
.divs {
position: absolute;
display: inline-block;
background-color: #fff;
}
.inputs {
position: absolute;
left: 0px;
height: 2%;
width: 15%;
opacity: 0;
background: #00f;
z-index: 100;
}
.icons {
position: absolute;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>
<div class="divs" id="divforfile" style="color:black">
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>
</div>
</form>
<br />
</div>
<br />
<div>
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">
<span style="color:red">×</span>
</button>
<div id="displayFileNames">
</div>
<ul id="myList"></ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function () {
$(document).mousemove(function () {
$('#myList').css('display', 'block');
$("#seebtn").css('display', 'none');
$("#hidebtn").css('display', 'none');
$('#displayFileNames').html('');
$("#myList").html('');
var fileArray1 = document.getElementsByClassName('file-input');
for (var i = 0; i < fileArray1.length; i++) {
var files = fileArray1[i].files;
for (var j = 0; j < files.length; j++) {
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");
}
};
if (($("#myList").html()) != '') {
$('#unselect').css('display', 'block');
$('#divforfile').css('color', 'green');
$('#attach').css('color', 'green');
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');
};
if (($("#myList").html()) == '') {
$('#divforfile').css('color', 'black');
$('#attach').css('color', 'black');
$('#displayFileNames').append('Nessun File Selezionato');
};
});
});
function choosefiles(obj) {
$(obj).hide();
$('#myList').css('display', 'none');
$('#hidebtn').css('display', 'none');
$("#seebtn").css('display', 'none');
$('#unselect').css('display', 'none');
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");
$('#displayFileNames').html('');
}
$(document).ready(function () {
$('#unselect').click(function () {
$('#hidebtn').css('display', 'none');
$("#seebtn").css('display', 'none');
$('#displayFileNames').html('');
$("#myList").html('');
$('#myFileInput').val('');
document.getElementById('upload-form').reset();
$('#unselect').css('display', 'none');
$('#divforfile').css('color', 'black');
$('#attach').css('color', 'black');
});
});
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.divs {
position: absolute;
display: inline-block;
background-color: #fff;
}
.inputs {
position: absolute;
left: 0px;
height: 2%;
width: 15%;
opacity: 0;
background: #00f;
z-index: 100;
}
.icons {
position: absolute;
}
</style>
<div>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>
<div class="divs" id="divforfile" style="color:black">
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>
</div>
</form>
<br />
</div>
<br />
<div>
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">
<span style="color:red">×</span>
</button>
<div id="displayFileNames">
</div>
<ul id="myList"></ul>
</div>
You can style them, but you can't remove the elements that are already there. If you're creative, you can work with that and do something like this:
input[type=file] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #EEE;
background: linear-gradient(to top, #FFF, #DDD);
border: thin solid rgba(0,0,0, .5);
border-radius: .25em;
box-shadow: inset .25em .25em .25em rgba(255,255,255, .5), inset -.1em -.1em .1em rgba(0,0,0, 0.1);
cursor: text;
padding: .25em;
}
http://jsfiddle.net/zr1x1m2b/1/
I suggest you play around with this code, remove lines, add your own, do whatever until you get something that looks how you like!
Just style a normal button however you want, using your favorite CSS.
Then call a simple JS function to create and link a hidden input element to your styled button. Don't add browser-specific CSS to do the hiding part.
<!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.
For more details, research DropZone and gmail uploads.
Here is one way I recently discovered, with a bit of jQuery
HTML Code:
<form action="">
<input type="file" name="file_upload" style="display:none" id="myFile">
<a onclick="fileUpload()"> Upload a file </a>
</form>
For the javascript/jQuery part :
<script>
function fileUpload() {
$("#myFile").click();
}
</script>
In this example, I have put an "anchor" tag to trigger the file upload. You can replace with anything you want, just remember to put the "onclick" attribute with the proper function.
Hope this helps!
P.S. : Do not forget to include jQuery from CDN or any other source