How to make the text following text Bold? - html

So I was adding the blinking text widget in the sidebar of my website.
I am using the following code to do it,
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Blink Text using JavaScript</title></style>
<script language="javascript">
setInterval(blinktext, 500);
var txt = "";
var count = 0;
function blinktext() {
var cntrl = document.getElementById("txtblinkingtext");
if (count == 0)
txt = cntrl.value;
if (count % 2 == 0)
cntrl.value = "";
else
cntrl.value = txt;
count++;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="margin: auto; text-align: center;">
<input type="text" id="txtblinkingtext" name="txtblinkingtext" value="NEWS STREAM"
readonly="readonly" style="height: 20px; width: 300px; background-color: #E64946;
color: White; border: 0px none; text-align: center;">
</div>
</form>
</body>
</html>
I just wanted to know how to use Bold or Strong method on "NEWS STREAM" text value

You have a </style> tag hanging, remove it.
In your input style, add font-weight:bold. But, you'd rather have a CSS file with that rather than style in the HTML like this, it's not too pretty.

Related

How to hover over text (later a link) and have image and text next to it show up

I have a simple webpage with "site map" on bottom that won't be implemented for weeks or months and am developing the rest as I go.
So, "Site Map" needs to be a link (I presume) with "href=" (?) where I can add a link later? Upon hover, I need text saying "coming soon" to show up, along with an image on both sides, i.e.
(before hover)
Site Map
(after hover)
Site Map Coming Soon
There should be a little space between the pic and text that pops up.
#my_map:hover:after {
margin-left: 20px;
color: green;
content: "(Coming Soon)";
}
<h1>Before and After Tag Example</h1>
<p id="my_map">Site Map</p>
<p>Go back to Main Menu</p>
<span> <img src="lightening_bolt" alt="bolt" height="20" width="20";> coming soon <img src="lightening_bolt" alt="bolt" height="20" width="20";> </span>
<p style "margin-top: 50px;">Hover over Site Map... </p>
Above isn't allowing for an image, just content= some text, and all the searching I've done to find some code ideas seem to be with other objectives...
You can add an image to the content of an :after pseudo element by using the url() attribute. If you want text as well as an image, you need to string these together without a space. If you want space between the image and the text, just be sure to include the spaces withing your text string. The snippet below shows an image placed before and after the string.
Note: the images take a second or two to load.
var myMap = document.getElementById("my_map2");
var comingSooon = document.getElementById("my_map2");
//
myMap.addEventListener("mouseover", function() {
cs.innerHTML = "<img src='https://picsum.photos/200' height='15' width='40' /> (Coming Soon) <img src='https://picsum.photos/200' height='15' width='40' />";
}, false);
//
myMap.addEventListener("mouseout", function() {
cs.innerHTML = "";
}, false);
#my_map:hover:after {
margin-left: 20px;
font-size: 20px;
color: green;
content: url("https://picsum.photos/20")" (Coming Soon) "url("https://picsum.photos/20");
}
<p id="my_map">Site Map</p>
<p>Site Map 2 <span id="cs"></span></p>
You could also just have the image already there and hide it until the anchor is hovered over:
#map-link {
display: inline-block;
}
#hidden-message {
display: none;
transition: display 1s linear;
}
#map-link:hover+#hidden-message {
display: block;
}
#cmg-soon-img {
margin: 0;
padding: 0;
height: 100px;
width: 100px;
}
<div id="my_map">
<p id="map-link">Site Map</p>
<div id="hidden-message">
<img id="cmg-soon-img" src="https://picsum.photos/20">
<p>
"Coming soon..."
</p>
</div>
</div>
Which would allow you to control the width and height of the image shown.
<!-- Here's what I got (hope answer my own question doesn't close thread...-->
<!DOCTYPE html>
<html>
<head>
<style>
#my_map {
margin-right: 30px;
font-size: 35px;
text-decoration: none;
}
</style>
</head>
<body>
<p>Site Map <span id="cs"></span></p>
<script>
var myMap = document.getElementById("my_map");
var comingSooon = document.getElementById("my_map");
myMap.addEventListener("mouseover", function() {cs.innerHTML = "<img src='https://picsum.photos/20' height='35' width='35' /> (Coming Soon) <img src='https://picsum.photos/20' height='35' width='35' />";}, false);
myMap.addEventListener("mouseout", function() {cs.innerHTML = "";}, false);
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<style>
#soon:hover:after {
margin-left: 20px;
color: green;
content: "Soon";
}
</style>
</head>
<body>
<p id="soon" style="font-size: 25px; margin-left:5%;"> Site Map </p>
<p style="margin-bottom: 150px;"></p>
<!-- take out the image and it's broken... it shows what I'm trying to do... -->
<img src="lightening-bolt.jpg" alt="Lightening bolt"
height="42" width="42">
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "inline") {
x.style.display = "none";
} else {
x.style.display = "inline";
}
}
</script>
<p style="display: inline" onmouseover="myFunction()"
onmouseleave="myFunction()">Click Me
</p>
<div id="myDIV">
<span><img src="lightening-bolt.jpg" alt="Lightening bolt"
height="42" width="42"> Text <img src="399-3991460_face-with-stuck-out-tongue-
eye.jpg" alt="Lightening bolt"
height="42" width="42"> </span>
</div>
</body>
</html>

Div does not get the full width of the page

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Data Retrieve</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="bootstrap.css">
<style>
#demo{
background-color:purple;
color: white;
width: 100%;
}
#home{
width: 45px;
}
#back{
width: 25px;
}
#header{
width:100%;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 col-sm-12">
<table id="info_table" class="table">
<tr>
<td id="header">
<p align="center"><span style="float: left"><img src="back.png" id="back"></span><b>মন্ত্রণালয়</b><span style="float: right"><img src="home.png" id="home"></span><span style="float: right"><img src="refresh.png" id="refresh"></span></p>
</td>
</tr>
<tr>
<td id="demo" align="center"><td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
<script>
var bn_num = new Array('০','১','২','৩','৪','৫','৬','৭','৮','৯');
function bn_num_convert(num){
//console.log(num.length);
var bn_val = '';
for(i=0;i<num.length;i++){
//console.log(num[i] + '/' + bn_num[num[i]]);
bn_val = bn_val + bn_num[num[i]];
}
//console.log(bn_val);
return bn_val;
}
$.getJSON("http://localhost/directory/ministri.json",function(obj){
var info ='';
//alert(obj.data.length);
var count = obj.data.length;
document.getElementById("demo").innerHTML ='মোট মন্ত্রণালয় ('+bn_num_convert(count.toString())+')';
var count = obj.data.length;
$.each(obj.data,function(key,value){
info += '<tr>';
info +='<td>'+value.sitename_bn+'<span style="float: right"> > </span>'+ '</td>';
info += '</tr>';
[This is the corresponding output of the code.][1]
});
$('#info_table').append(info);
});
</script>
Firstly here purple background color doesn't get the full wide.if i inspect the background there shows an empty td which cause the problem.if i delete the empty td then i get perfect result.but there is no empty td in my code.plz see the code and show me the error.
Secondly there is no horizontal line at the end of the output result.why last line doesn't get horizontal line?
You are not closing the td, thats why empty td is appending.
<td id="demo" align="center"></td>
Close the td like in above code
and remove margin and padding as other posts suggested in case if you want full width till ends.
Set body margin paddding to 0px
body {
padding: 0px;
margin: 0px;
}
Just put in demo id td, it will show.
See thishttps://jsfiddle.net/v6mwpz89/3/
Cheers!

Regex to validate a date

so basically, I am creating a booking form for a practice website. I want to validate the date so that the user can only enter a date in 2017, and cannot proceed without entering a date in 2017. They also cannot proceed without entering a valid name and email. An alert message appears if one of these is not satisfied, and the related text boxes are highlighted.
Here is what I have so far in terms of code:
Any help is appreciated, thank you.
HTML
<html>
<head>
<title> Booking </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css">
<script>
function validate{} {
result = true;
contentUsername=booking.username.value;
if (contentUsername=="")
result=false;
}
</script>
<script>
function validate() {
result = true;
contentUsername=booking.username.value;
contentEmail=booking.email.value;
contentDate=booking.date.value;
var email = /^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
var username = /^[A-Za-z]+[A-Za-z\s\.'-]+[A-Za-z]$/;
var date = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d).\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d).(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d).\d{2})$/;
var alertMessage="";
if (contentUsername==""){
result=false;
document.getElementById('username').style.background="lightyellow";
document.getElementById('username').style.border="solid firebrick 1px";
}
if (contentEmail=="") {
result=false;
document.getElementById('email').style.background="lightyellow";
document.getElementById('email').style.border="solid firebrick 1px";
}
if (contentDate=="") {
result=false;
document.getElementById('date').style.background"lightyellow";
document.getElementById('date').style.border="solid firebrick 1px";
}
if (!(email.test(contact.email.value)) && contact.email.value != "") {
alertMessage += contact.email.value + ' is not a valid email address.\r\n';
result=false;
}
if (!(username.test(contact.username.value)) && contact.username.value != "") {
alertMessage += contact.username.value + ' is not a valid name.\r\n';
result=false;
}
if (!(date.test(contact.date.value)) && contact.date.value != "") {
alertMessage += contact.date.value + ' is not a valid date. Please select a date in 2017.\r\n';
result=false;
}
if (!result) {
alertMessage += "Please fill out the highlighted fields";
alert(alertMessage);
}
return result;
}
</script>
</head>
<body>
<div id="header">
<div id="branding">
<img src="Images/logo.png">
</div><!-- end of "logo" -->
<div id="tagline">
<p> Welcome to yourday.com - We hope you enjoy your visit!
<br> This is where you can book an appointment with one of our agents!
<br> Please note: Dates for 2016 are fully booked. Next available appointments are in 2017. We apologies for any inconvenience caused.</p>
</div><!-- end of "tagline" -->
</div><!-- end of "header" -->
<div id="bodycontent4">
<form action="http://www.rebol.com/cgi-bin/test-cgi.cgi" method="post" class="booking" id="booking" onsubmit="return validate()">
<fieldset>
<legend>Booking</legend>
<label for="username">Name: </label>
<input type="text" name="username" id="username"></br>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email"></br>
<label for="date">Date:</label>
<input type="date" name="date" id="date"></br>
<label for="location">Location:</label>
<select>
<option value="manor">Uppercourt Manor</option>
<option value="killruddery">Killrudderry</option>
<option value="carriage">The Carriage Rooms</option>
<option value="coolclogher">Coolclogher House</option>
</select>
</fieldset>
<input type="submit" value="Submit">
</form>
</div><!--end of "bodycontent" -->
<div id="navigation">
<ul class="topnav" id="TopNav">
<li>Home</li>
<li>Locations</li>
<li>Booking</li>
<li>Testimonials</li>
<li>Contact Us</li>
<li>About</li>
</li>
</ul>
</div> <!--end of "navigation" -->
<div id="footer" style = "position: absolute; top: 550px;">
<p>Created by: Calvin Leong</p>
<p>Contact information: calvin.leong#CLDesign.com</p>
</div>
</body>
</html>
CSS
/* Booking Form */
form.booking label {
display: block;
width: 100px;
float: left;
font-weight: bold;
font-size: small;
color: black;
line-height: 150%
}
form.booking fieldset {
border: 2px solid red;
padding: 10px;
}
form.booking legend {
font-weight: bold;
font-size: small;
color: black;
padding: 5px;
}
#bodycontent4 {
position: absolute;
top: 270px;
width: 25%;
left: 500px;
}
#div {
margin: 0 auto;
}
You could do like this:
var date = new Date("01/01/2017");
var year = date.getFullYear();
if(year == 2017){
alert(year);
}else{
alert("crap");
}
Here is your regex for date:
var date = /^2017-\d{2}-\d{2}$/;
And, here is the working link: http://jsbin.com/getunisagi

HTML linking image to image to image

Html- i am writing a program so that the user clicks on an image and is linked to another image and to another i can do it for one image but am struggling with the code to make the second image link to the third and so on any suggestions greatly appreciated?
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<script language="JavaScript">
var clockID = 0;
function UpdateClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
var tDate = new Date();
document.theClock.theTime.value = ""
+ tDate.getHours() `enter code here`+ ":"
+ tDate.getMinutes() + ":"
+ tDate.getSeconds();
clockID = setTimeout("UpdateClock()", 1000);
}
function StartClock() {
clockID = setTimeout("UpdateClock()", 500);
}
function KillClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
}
</script>
<body onload="StartClock()" onunload="KillClock()">
<form name="theClock">
<input type=text name="theTime" size=8 style="text-align: center">
</form>
<font face="Tahoma"><a target="_blank" href="http://www.htmlfreecodes.com/"><span style="font-size: 8pt; text-decoration: none"></span></a></font>
<A HREF = "img2.png">
<img src= "img1.png">
<!--<A HREF = "img4.png">
<img src= "img3.png"> </a>-->
</body>
</html>

Change default text in input type="file"?

I want to change default text on button that is "Choose File" when we use input="file".
How can I do this? Also as you can see in image button is on left side of text. How can I put it on right side of text?
Use the for attribute of label for input.
<div>
<label for="files" class="btn">Select Image</label>
<input id="files" style="visibility:hidden;" type="file">
</div>
Below is the code to fetch name of the uploaded file
$("#files").change(function() {
filename = this.files[0].name;
console.log(filename);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="files" class="btn">Select Image</label>
<input id="files" style="visibility:hidden;" type="file">
</div>
I think this is what you want:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
</body>
</html>
Each browser has it's own rendition of the control and as such you can't change either the text or the orientation of the control.
There are some "kind of" hacks you may want to try if you want an html/css solution rather than a Flash or silverlightsolution.
http://www.quirksmode.org/dom/inputfile.html
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
Personally, because most users stick to their browser of choice, and therefore are probably used to seeing the control in the default rendition, they'd probably get confused if they saw something different (depending on the types of users you're dealing with).
This might help someone in the future, you can style the label for the input as you like and put anything you want inside it and hide the input with display none.
It works perfectly on cordova with iOS
<link href="https://cdnjs.cloudflare.com/ajax/libs/ratchet/2.0.2/css/ratchet.css" rel="stylesheet"/>
<label for="imageUpload" class="btn btn-primary btn-block btn-outlined">Seleccionar imagenes</label>
<input type="file" id="imageUpload" accept="image/*" style="display: none">
To achieve this, the default input button must be hidden using display:none CSS property and a new button element is added to replace it, so we can customize as we wish.
With Bootstrap
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
Optional text here
<label for="img" class="btn btn-info">Try me</label>
<input type="file" id="img" style="display:none">
With jQuery
In this case the onclick attribute added to the button element is indicating to JavaScript to click on the hidden default input button whenever the visible button is clicked.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Optional text here
<button style="cursor:pointer" onclick="$('#input').click()">Click me</button>
<input type="file" id="input" style="display:none">
Plain JavaScript with event listener
document.getElementById('btn').addEventListener('click', () => {
document.getElementById('input').click();
})
Optional text here
<button style="cursor:pointer" id="btn">Click me</button>
<input type="file" id="input" style="display:none">
It is not possible. Otherwise you may need to use Silverlight or Flash upload control.
$(document).ready(function () {
$('#choose-file').change(function () {
var i = $(this).prev('label').clone();
var file = $('#choose-file')[0].files[0].name;
$(this).prev('label').text(file);
});
});
.custom-file-upload{
background: #f7f7f7;
padding: 8px;
border: 1px solid #e3e3e3;
border-radius: 5px;
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
can you try this
<label for="choose-file" class="custom-file-upload" id="choose-file-label">
Upload Document
</label>
<input name="uploadDocument" type="file" id="choose-file"
accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
The trick is to trigger a click event on click of the file input and manage the visibility of the default input file via CSS. Here's how you can do it:
jQuery:
$(function() {
$("#labelfile").click(function() {
$("#imageupl").trigger('click');
});
})
css
.file {
position: absolute;
clip: rect(0px, 0px, 0px, 0px);
display: block;
}
.labelfile {
color: #333;
background-color: #fff;
display: inline-block;
margin-bottom: 0;
font-weight: 400;
text-align: center;
vertical-align: middle;
cursor: pointer;
background-image: none;
white-space: nowrap;
padding: 6px 8px;
font-size: 14px;
line-height: 1.42857143;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input name="imageupl" type="file" id="imageupl" class="file" />
<label class="labelfile" id="labelfile"><i class="icon-download-alt"></i> Browse File</label>
</div>
I made a script and published it at GitHub: get selectFile.js
Easy to use, feel free to clone.
HTML
<input type=file hidden id=choose name=choose>
<input type=button onClick=getFile.simulate() value=getFile>
<label id=selected>Nothing selected</label>
JS
var getFile = new selectFile;
getFile.targets('choose','selected');
DEMO
jsfiddle.net/Thielicious/4oxmsy49/
Update 2017:
I have done research on how this could be achieved. And the best explanation/tutorial is here:
https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/
I'll write summary here just in case it becomes unavailable. So you should have HTML:
<input type="file" name="file" id="file" class="inputfile" />
<label for="file">Choose a file</label>
Then hide the input with CSS:
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;}
Then style the label:
.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}
Then optionally you can add JS to display the name of the file:
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
But really just read the tutorial and download the demo, it's really good.
This should work:
input.*className*::-webkit-file-upload-button {
*style content..*
}
Here is how its done with bootstrap, only u should put the original input somewhere...idk
in head and delete the < br > if you have it, because its only hidden and its taking space anyway :)
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<label for="file" button type="file" name="image" class="btn btn-secondary">Secondary</button> </label>
<input type="file" id="file" name="image" value="Prebrskaj" style="visibility:hidden;">
<footer>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</footer>
Using Bootstrap you can do this thing like the below code.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.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;
}
</style>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<span class="btn btn-file">Upload image from here<input type="file">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
</body>
</html>
I'd use a button to trigger the input:
<button onclick="document.getElementById('fileUpload').click()">Open from File...</button>
<input type="file" id="fileUpload" name="files" style="display:none" />
Quick and clean.
You can use this approach, it works even if a lot of files inputs.
const fileBlocks = document.querySelectorAll('.file-block')
const buttons = document.querySelectorAll('.btn-select-file')
;[...buttons].forEach(function (btn) {
btn.onclick = function () {
btn.parentElement.querySelector('input[type="file"]').click()
}
})
;[...fileBlocks].forEach(function (block) {
block.querySelector('input[type="file"]').onchange = function () {
const filename = this.files[0].name
block.querySelector('.btn-select-file').textContent = 'File selected: ' + filename
}
})
.btn-select-file {
border-radius: 20px;
}
input[type="file"] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file-block">
<button class="btn-select-file">Select Image 1</button>
<input type="file">
</div>
<br>
<div class="file-block">
<button class="btn-select-file">Select Image 2</button>
<input type="file">
</div>
My solution...
HTML :
<input type="file" id="uploadImages" style="display:none;" multiple>
<input type="button" id="callUploadImages" value="Select">
<input type="button" id="uploadImagesInfo" value="0 file(s)." disabled>
<input type="button" id="uploadProductImages" value="Upload">
Jquery:
$('#callUploadImages').click(function(){
$('#uploadImages').click();
});
$('#uploadImages').change(function(){
var uploadImages = $(this);
$('#uploadImagesInfo').val(uploadImages[0].files.length+" file(s).");
});
This is just evil :D
Ok so very simple pure css way of creating your custom input file.
Use labels, but as you know from previous answers, label doesn't invoke onclick
function in firefox, may be a bug but doesn't matter with the following.
<label for="file" class="custom-file-input"><input type="file" name="file" class="custom-file-input"></input></label>
What you do is style the label to look how you want it to
.custom-file-input {
color: transparent;/* This is to take away the browser text for file uploading*/
/* Carry on with the style you want */
background: url(../img/doc-o.png);
background-size: 100%;
position: absolute;
width: 200px;
height: 200px;
cursor: pointer;
top: 10%;
right: 15%;
}
now simply hide the actual input button, but you cant set it to to visability: hidden
So make in invisible by setting opacity: 0;
input.custom-file-input {
opacity: 0;
position: absolute;/*set position to be exactly over your input*/
left: 0;
top: 0;
}
now as you might have noticed i have the same class on my label as i do my input field, that is because i want the to both have the same styling, thus where ever you click on the label, you are actually clicking on the invisible input field.
I build a script that can be easier to do that.
For example:
<input data-com="fileBtn" placeholder="Select Image">
basically, my script is very similar to this link
Code
Pure javascript, no dependencies needed
<!-- bootstrap.min.css not necessary -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.0/css/bootstrap.min.css">
<input data-com="fileBtn" placeholder="Select Image"> <!-- com: components -->
<input data-com="fileBtn" placeholder="Select File">
<div class="mt-2">
<input id="build-by-myself" placeholder="Select Video" accept="video/mp4, video/webm">
<div>
<script>
// 👇 Test
(()=>{
window.onload = () =>{
// FileButton.className ="btn btn-danger"
FileButton.BuildAll() // auto build all data-com="fileBtn"
// or you can specify the target that you wanted.
new FileButton(document.getElementById("build-by-myself"), "btn btn-danger")
}
})()
// 👇 script begin
class FileButton {
static className = "btn btn-primary"
static BuildAll() {
document.querySelectorAll(`input[data-com="fileBtn"]`).forEach(input=>{
new FileButton(input, FileButton.className)
})
}
/**
* #param {HTMLInputElement} input
* #param {string} btnClsName
* */
constructor(input, btnClsName) {
input.style.display = "none" // [display is better than visibility](https://stackoverflow.com/a/48495293/9935654)
input.type = "file"
const frag = document.createRange().createContextualFragment(`<button class="${btnClsName}">${input.placeholder}</button>`)
const button = frag.querySelector(`button`)
input.parentNode.insertBefore(frag, input)
button.onclick = ()=>{
input.click()
}
input.addEventListener(`change`, (e)=>{
// create a textNode to show the file name.
const file = input.files[0]
if (file === undefined) {
return
}
const textNode = document.createTextNode(file.name)
if (button.textNode) { // create a new attribute to record previous data.
button.textNode.remove()
}
button.textNode = textNode
button.parentNode.insertBefore(textNode, input)
})
}
}
</script>
Reference
What is the difference between visibility:hidden and display:none?
data-*
Below is an example of a stylized upload button that will read an image, compress it, and download the resulting image. It works by hiding the actual input element, and then through some trickery we make it so that when you click on our fake file uploader it uses the actual input element to pop up the window for choosing a file. By using this method we get 100% control over how the file uploader looks since we are using our own element instead of styling the file upload menu. It also makes it easy to add drag and drop functionality in the future if we ever want to do that.
And then I actually created a series of blog posts about this file upload button.
'use strict'
var AMOUNT = 10
var WIDTH = 600
var HEIGHT = 400
var canvas = document.getElementById('canvas')
canvas.width = WIDTH
canvas.height = HEIGHT
//here's how I created the clickable area
//user clicks the clickable area > we send a click event
//to the file opener > the file opener clicks on the open
//file button > the open file dialogue pops up
function clickableAreaListener(e){
let clickEvent = new CustomEvent("click",{"from":"fileOpenerHandler"});
document.getElementById("fileOpener").dispatchEvent(clickEvent);
}
function fileOpenerListener(e) {
document.getElementById("file-btn").click();
e.preventDefault();
}
function fileSelectedListener(e){
readFiles(e.target.files);
}
document.getElementById('file-btn').addEventListener('change', fileSelectedListener);
document.getElementById("clickable-area").addEventListener('click', clickableAreaListener);
document.getElementById("fileOpener").addEventListener("click", fileOpenerListener);
function readFiles(files){
files = [].slice.call(files); //turning files into a normal array
for (var file of files){
var reader = new FileReader();
reader.onload = createOnLoadHandler(file);
reader.onerror = fileErrorHandler;
//there are also reader.onloadstart, reader.onprogress, and reader.onloadend handlers
reader.readAsDataURL(file);
}
}
function fileErrorHandler(e) {
switch(e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
throw 'Image not found';
break;
case e.target.error.NOT_READABLE_ERR:
throw 'Image is not readable';
break;
case e.target.error.ABORT_ERR:
break;
default:
throw 'An error occurred while reading the Image';
};
}
function createOnLoadHandler(file){
console.log('reading ' + file.name + ' of type ' + file.type) //file.type will be either image/jpeg or image/png
function onLoad(e){
var data = e.target.result
display(data);
var compressedData = compressCanvas(AMOUNT)
download(compressedData)
}
return onLoad
}
function display(data){
var img = document.createElement('img');
img.src = data;
var context = canvas.getContext('2d')
context.clearRect(0, 0, WIDTH, HEIGHT);
context.drawImage(img, 0, 0, WIDTH, HEIGHT);
}
function compressCanvas(){
return canvas.toDataURL('image/jpeg', AMOUNT / 100);
}
function download(data) {
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
var chromeApp = Boolean(chrome && chrome.permissions)
if (chromeApp){
chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) {
chrome.fileSystem.getWritableEntry(entry, function(entry) {
entry.getFile('example.jpg', {create:true}, function(entry) {
entry.createWriter(function(writer){
writer.write(b64toBlob(data.slice(23), 'image/jpg'))
})
})
})
})
} else {
let a = document.createElement("a");
a.href = data;
a.download = 'downloadExample.jpg'
document.body.appendChild(a)
a.click();
window.URL.revokeObjectURL(a.href);
a.remove()
}
}
.fileInput {
display: none;
position: absolute;
top: 0;
right: 0;
font-size: 100px;
}
#clickable-area{
background: #ccc;
width: 500px;
display: flex;
margin-bottom: 50px;
}
#clickable-area-text{
margin: auto;
}
.yellow-button {
cursor: pointer;
color: white;
background: #f1c40f;
height: 30px;
width: 120px;
padding: 30px;
font-size: 22px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
}
<div id="clickable-area">
<a id='fileOpener'> </a>
<input type="file" class="fileInput" id="file-btn" accept="image/*" multiple/>
<div class="yellow-button"><span>Shrink Image</span>
</div><p id="clickable-area-text">( you can click anywhere in here ) </p>
</div>
<canvas id="canvas"></canvas>
Stack Overflow limitations seem to prevent the code snippet from actually compressing and downloading the file. The exact same code here shows that the full upload/compress/download process does actually work as intended.
With answers from this question, I fixed what many in coments said doesn¨t work for them which is that it's not showing how many files user chose.
<label for="uploadedFiles" class="btn btn-sm btn-outline-primary">Choose files</label>
<input type="file" name="postedFiles" id="uploadedFiles" multiple="multiple" hidden onchange="javascript:updateList()" />
<input class="btn btn-primary mt-2 btn-action" type="submit" value="Send" formmethod="post" formaction="#Url.Action("Create")" /><br />
<span id="selected-count">Selected files: 0</span>
<script>
updateList = function () {
var input = document.getElementById('uploadedFiles');//list of files user uploaded
var output = document.getElementById('selected-count');//element displaying count
output.innerHTML = 'Selected files: ' + input.files.length;
}
</script>
You can easily improve it by showing names of files instead or whatever you wish to do but all I wanted was to inform user that they have already picked files.
You can use a simple button and hide input file
using jquery and bootstrap :
HTML code
<button class="btn btn-white" id="btn-file" type="button"><i class="fa fa-file-pdf"></i> Anexar Documento</button>
<input name="shutdown" id="input-file" type="file" class="form-control hidden" accept="application/pdf, image/png, image/jpeg">
CSS :
.hidden{display:none}
JS :
$("#btn-file").click(function () {
$("#input-file").trigger('click');
});
$("#input-file").change(function () {
var file = $(this)[0].files[0].name;
$("#btn-file").html('<i class="fa fa-file-pdf"></i> ' + file);
});