This question already has answers here:
Styling an input type="file" button
(46 answers)
Closed 5 years ago.
I have a file upload button which i need to file. I currently defaults to some pre-set styles.
<form class="uploadButton" method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file[]" multiple>
</form>
You can try the below code
$('input[type="file"]').on('change', function() {
$('input[type="text"]').val($(this).val());
});
$('span').on('click', function() {
$('input[type="text"]').val($('input[type="file"]').val());
});
form.uploadButton {
position: relative;
display: flex;
}
input[type="text"] {
width: 200px;
height: 40px;
box-sizing: border-box;
border-radius: 2px;
border: 1px solid #ccc;
margin-right: 5px;
}
span {
background: red;
border: 0;
color: #fff;
padding: 0 20px;
width: 80px;
text-align: center;
line-height: 40px;
cursor: pointer;
}
input[type="file"] {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 0;
cursor: pointer;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="uploadButton" method="" action="" enctype="multipart/form-data">
<input type="text">
<span>Browse</span>
<input type="file" name="file[]" multiple>
</form>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<form class="uploadButton" method="POST" action="upload.php" enctype="multipart/form-data">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file" name="file[]" multiple/>
</form>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "Name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "Size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
::-webkit-file-upload-button {
background: black;
color: red;
padding: 0.5em;
}
<body onload="myFunction()">
<input type="file" id="myFile" class="custom-file-upload" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
</body>
Try this.
'use strict';
;( function ( document, window, index )
{
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;
});
// Firefox bug fix
input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
});
}( document, window, 0 ));
input[type="file"] {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
width: 100%;
margin: 0;
padding: 0;
font-size: 1px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
.inputfile + label span {
width: 200px;
min-height: 18px;
display: inline-block;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
vertical-align: top;
border: 1px solid #ccc;
}
.inputfile + label strong {
height: 100%;
color: #fff;
background-color: #d3394c;
display: inline-block;
}
.inputfile + label span,
.inputfile + label strong {
padding: 10px;
}
.inputfile + label svg {
width: 1em;
height: 1em;
vertical-align: middle;
fill: currentColor;
margin-top: -0.25em;
margin-right: 0.25em;
}
.box {
position: relative;
}
<div class="box">
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file"><span></span> <strong><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg> Choose a file…</strong></label>
</div>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "Name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "Size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<body onload="myFunction()">
<input type="file" id="myFile" class="custom-file-upload" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
</body>
Try something like this.
document.getElementById("file-upload").addEventListener("change", function() {
var fullPath = document.getElementById("file-upload").value
var filename = fullPath.replace(/^.*[\\\/]/, '')
document.getElementById("status").innerHTML = filename;
});
.file-upload {
opacity: 0;
position: absolute;
top:0;
left:0;
height:75px;
width:100%;
border: 1px solid red;
}
.file-container {
position:relative;
}
.custom-file-upload {
position: absolute;
top:0;
left:0;
}
#status {
font-size: 25px;
color:red;
font-weight: bold;
}
<div class="file-container">
<div class="custom-file-upload">
Put fancy <img src="https://cdn3.iconfinder.com/data/icons/badger-s-christmas/300/stocking-32.png" /> stuff here <img src="https://cdn3.iconfinder.com/data/icons/badger-s-christmas/300/bells-48.png" /> (click me)
<input type="file" class="file-upload" id="file-upload" />
</div>
</div><br /><br /><br /><p id="status"></p>
Step 1. Create a simple html markup
<div class="fileUpload btn btn-primary">
<span>Upload</span>
<input type="file" class="upload" />
</div>
Step 2. CSS: Tricky Part
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
Related
I want to Generate and Download Screenshot of webpage without lossing the styles. I have a web page .In that web page i have a download button . When user click on download button then the screen shot of entire Page need to download as image in user computer . How can i do this ?
Please check my code
Index.html
<html>
<body>
<link href="style.css" rel="stylesheet">
<h1>Scrrenshot</h1>
<form class="cf">
<div class="half left cf">
<input type="text" id="input-name" placeholder="Name">
<input type="email" id="input-email" placeholder="Email address">
<input type="text" id="input-subject" placeholder="Subject">
</div>
<div class="half right cf">
<textarea name="message" type="text" id="input-message" placeholder="Message"></textarea>
</div>
<input type="submit" value="Submit" id="input-submit">
</form>
<a class="btn btn-success" href="javascript:void(0);" onclick="generate();">Generate Screenshot »</a>
</body>
<script>
(function (exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype
|| nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function (el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
</script>
</html>
style.css
#import "compass/css3";
#import url(https://fonts.googleapis.com/css?family=Merriweather);
$red: #e74c3c;
*,
*:before,
*:after {
#include box-sizing(border-box);
}
html, body {
background: #f1f1f1;
font-family: 'Merriweather', sans-serif;
padding: 1em;
}
h1 {
text-align: center;
color: #a8a8a8;
#include text-shadow(1px 1px 0 rgba(white, 1));
}
form {
border: 2px solid blue;
margin: 20px auto;
max-width: 600px;
padding: 5px;
text-align: center;
}
input, textarea {
border:0; outline:0;
padding: 1em;
#include border-radius(8px);
display: block;
width: 100%;
margin-top: 1em;
font-family: 'Merriweather', sans-serif;
#include box-shadow(0 1px 1px rgba(black, 0.1));
resize: none;
&:focus {
#include box-shadow(0 0px 2px rgba($red, 1)!important);
}
}
#input-submit {
color: white;
background: $red;
cursor: pointer;
&:hover {
#include box-shadow(0 1px 1px 1px rgba(#aaa, 0.6));
}
}
textarea {
height: 126px;
}
}
.half {
float: left;
width: 48%;
margin-bottom: 1em;
}
.right { width: 50%; }
.left {
margin-right: 2%;
}
#media (max-width: 480px) {
.half {
width: 100%;
float: none;
margin-bottom: 0;
}
}
/* Clearfix */
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.cf:after {
clear: both;
}
.half.left.cf > input {
margin: 5px;
}
For this i used the method [http://www.xpertdeveloper.com/2012/10/webpage-screenshot-with-html5-js/] , here screenshot is generated but without style also it is not downloading . Please help , is there any jQuery library available for this?
You can achieve this using the following JavaScript libraries ...
html2canvas ( for taking screenshot of webpage )
FileSave.js ( for downloading the screenshot as an image )
ᴅᴇᴍᴏ
(function(exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function(el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
var wrapper = document.getElementById('wrapper');
html2canvas(wrapper, {
onrendered: function(canvas) {
canvas.toBlob(function(blob) {
saveAs(blob, 'myScreenshot.png');
});
}
});
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function(e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
screenshotPage();
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
#import url(https://fonts.googleapis.com/css?family=Merriweather);
$red: #e74c3c;
*,
*:before,
*:after {
#include box-sizing(border-box);
}
html,
body {
background: #f1f1f1;
font-family: 'Merriweather', sans-serif;
padding: 1em;
}
h1 {
text-align: center;
color: #a8a8a8;
#include text-shadow(1px 1px 0 rgba(white, 1));
}
form {
border: 2px solid blue;
margin: 20px auto;
max-width: 600px;
padding: 5px;
text-align: center;
}
input,
textarea {
border: 0;
outline: 0;
padding: 1em;
#include border-radius(8px);
display: block;
width: 100%;
margin-top: 1em;
font-family: 'Merriweather', sans-serif;
#include box-shadow(0 1px 1px rgba(black, 0.1));
resize: none;
&:focus {
#include box-shadow(0 0px 2px rgba($red, 1)!important);
}
}
#input-submit {
color: white;
background: $red;
cursor: pointer;
&:hover {
#include box-shadow(0 1px 1px 1px rgba(#aaa, 0.6));
}
}
textarea {
height: 126px;
}
}
.half {
float: left;
width: 48%;
margin-bottom: 1em;
}
.right {
width: 50%;
}
.left {
margin-right: 2%;
}
#media (max-width: 480px) {
.half {
width: 100%;
float: none;
margin-bottom: 0;
}
}
/* Clearfix */
.cf:before,
.cf:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.cf:after {
clear: both;
}
.half.left.cf > input {
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="wrapper">
<h1>Scrrenshot</h1>
<form class="cf">
<div class="half left cf">
<input type="text" id="input-name" placeholder="Name">
<input type="email" id="input-email" placeholder="Email address">
<input type="text" id="input-subject" placeholder="Subject">
</div>
<div class="half right cf">
<textarea name="message" type="text" id="input-message" placeholder="Message"></textarea>
</div>
<input type="submit" value="Submit" id="input-submit">
</form>
</div>
<a class="btn btn-success" href="javascript:void(0);" onclick="generate();">Generate Screenshot »</a>
I found that dom-to-image did a much better job than html2canvas. See the following question & answer: https://stackoverflow.com/a/32776834/207981
If you're looking to download the image(s) you'll want to combine it with FileSaver.js (already mentioned here), and if you want to download a zip with multiple image files all generated client-side take a look at jszip.
Few options for this
either use this
<html>
<head>
<title> Download-Button </title>
</head>
<body>
<p> Click the image ! You can download! </p>
<a download="logo.png" href="http://localhost/folder/img/logo.png" title="Logo title">
<img alt="logo" src="http://localhost/folder/img/logo.png">
</a>
</body>
</html>
or You can use Mordernizr
or maybe this works
<a href="/path/to/image" download>
<img src="/path/to/image" />
</a>
refer to this link aswell
[1] http://www.w3schools.com/tags/att_a_download.asp
Basically I got my css file which will be under the text but when i try to open the html file that uses it in the browser it doesn't work, the css code won't run and the styling and the javascript don't work because of that. The code is supposed to be like this one: https://codepen.io/ritaD86/pen/MyOdQr but it doesn't work in my browser while it works on the codepen.io. I also don't get it why the javascript doesn't work. What is going on? What can I do?
persons = [
person = {
firstName: "Maria",
lastName: "Fernanda",
age: "mf#desk.com",
phone: "917697967"
},
];
document.getElementById('search_button').addEventListener('click', searchPerson);
document.getElementById('add_button').addEventListener('click', addPerson);
document.getElementById('show_all').addEventListener('click', showAllPersons);
function searchPerson() {
var input = document.getElementById("search").value.toLowerCase();
var result = document.getElementById('result');
for (var i = 0; i < persons.length; i++) {
if (input === persons[i].firstName.toLowerCase() || input === persons[i].lastName.toLowerCase()) {
result.innerHTML = '<h4>I found this:</h4>' + persons[i].firstName + ' ' +
persons[i].lastName + ' </br>' + persons[i].age + ' </br>' + persons[i].phone;
return persons[i];
} else if (!isNaN(input)) {
result.innerHTML = 'Tem de inserir um nome';
} else {
result.innerHTML = 'Nenhum contacto encontrado';
}
}
}
function Person(first, last, age, phone) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.phone = phone;
}
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function addPerson() {
var firstName = titleCase(document.getElementById("name").value);
var lastName = titleCase(document.getElementById("lastname").value);
var age = document.getElementById("age").value;
var phone = document.getElementById("phone").value;
var newPerson = new Person(firstName, lastName, age, phone);
persons.push(newPerson);
if (newPerson.firstName != undefined) {
alert(newPerson.firstName + ' added');
} else {
alert('No person added');
}
showAllPersons();
}
function showAllPersons() {
var i;
var l;
var showButton = document.getElementById('show_all');
var list = document.getElementById('all_list');
while (list.firstChild) {
list.removeChild(list.firstChild);
}
for (var l = 0; l < persons.length; l++) {
var node = document.createElement("LI");
list.appendChild(node);
node.innerHTML =
'<p><b>Nome Completo:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Email:</b> ' + persons[l].age + '</p>' +
'<p><b>Telemovel:</b> ' + persons[l].phone + '</p>'
for (var key in person) {
var value = person[key];
}
}
showButton.disabled = true;
}
#import "bourbon";
#import "neat";
// Media queries
$desktop: new-breakpoint(min-width 960px 12);
$tablet: new-breakpoint(max-width 959px 12);
$mobile: new-breakpoint(max-width 767px 4);
// Variables
$max-width: 1200px;
form {
padding: 20px 0 40px;
.field {
#include padding(10px 0);
#include margin(5px 0);
#include display(inline-block);
#include fill-parent;
label {
#include span-columns(5);
#include padding(5px 10px);
}
input {
#include span-columns(7);
#include padding(5px 10px);
}
}
}
.container {
#include outer-container;
text-align: center;
}
.search_person {
#include span-columns(6);
}
.add_person {
#include span-columns(6);
}
.all_persons {
#include span-columns(4);
#include shift(4);
#all_list {
list-style-type: none;
margin: 20px 0;
padding: 0;
li {
margin: 0 0 30px;
text-align: left;
}
}
}
<html>
<head>
<title>Desk+ - Grupo 36</title>
<link rel="stylesheet" type="text/css" href="ab.css">
<script src="ab.js"></script>
</head>
<body>
<div class="container">
<h1>Contactos</h1>
<div class="all_persons">
<button id="show_all" type="button">Mostrar todos</button>
<ul id="all_list">
</ul>
</div>
<div class="search_person">
<h3>Insira um nome</h3>
<input type="text" id="search">
<button id="search_button" type="button">Procurar</button>
<p id="result"></p>
</div>
<div class="add_person">
<h3>Adicionar contacto</h3>
<form action="" method="post">
<div class="field">
<label for="firstname">Primeiro Nome: </label>
<input type="text" id="name">
</div>
<div class="field">
<label for="lastname">Último Nome: </label>
<input type="text" id="lastname">
</div>
<div class="field">
<label for="age">Email: </label>
<input type="text" id="age">
</div>
<div class="field">
<label for="phone">Phone: </label>
<input type="number" id="phone">
</div>
<button id="add_button" type="button">Add</button>
</form>
</div>
</div>
</body>
</html>
Here is the compiled css->
html {
box-sizing: border-box;
}
*, *::after, *::before {
box-sizing: inherit;
}
form {
padding: 20px 0 40px;
}
form .field {
padding: 10px 0;
margin: 5px 0;
display: inline-block;
width: 100%;
}
form .field label {
float: left;
display: block;
margin-right: 2.3576520234%;
width: 40.291369653%;
padding: 5px 10px;
}
form .field label:last-child {
margin-right: 0;
}
form .field input {
float: left;
display: block;
margin-right: 2.3576520234%;
width: 57.3509783236%;
padding: 5px 10px;
}
form .field input:last-child {
margin-right: 0;
}
.container {
max-width: 1200px;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.container::after {
clear: both;
content: "";
display: block;
}
.search_person {
float: left;
display: block;
margin-right: 2.3576520234%;
width: 48.8211739883%;
}
.search_person:last-child {
margin-right: 0;
}
.add_person {
float: left;
display: block;
margin-right: 2.3576520234%;
width: 48.8211739883%;
}
.add_person:last-child {
margin-right: 0;
}
.all_persons {
float: left;
display: block;
margin-right: 2.3576520234%;
width: 31.7615653177%;
margin-left: 34.1192173411%;
}
.all_persons:last-child {
margin-right: 0;
}
.all_persons #all_list {
list-style-type: none;
margin: 20px 0;
padding: 0;
}
.all_persons #all_list li {
margin: 0 0 30px;
text-align: left;
}
try this instead the css/scss you are using. It will work. cheers!
It is SCSS and not CSS. You need to convert it to CSS first for it to work. In addition to that, try to move your script to the end of the body tag instead of inside the head tag.
I write some code for to convert svg to inline svg and take screenshot of that div . Please check .Please copy this code int to your local host and test it . Because screen shot is different in different width .
https://jsfiddle.net/7bqukhff/15/
<link href="style.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdn.rawgit.com/canvg/canvg/master/canvg.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="test">
<div class="description-div">
<p>Sample description</p>
</div>
<div class="img-div" id="img-div"></div>
</div>
<form class="cf">
<div class="half left cf">
<input type="text" name="user-name" required>
<select name="design-name" class="desgign-class" required>
<option value="" >select</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<input type="submit" name="submit" value="submit" class="submit">
</div>
</form>
</div>
<div class="new">
<a class="btn btn-success" href="javascript:void(0);" onclick="generate();">Generate Screenshot »</a>
</div>
<script>
$(function() {
$(".desgign-class").on("change",function(){
var op=$(this).val();
if(op!=0){
$('.btn').show();
$('.img-div').html('');
if(op==2){
for(var i = 0;i<op;i++){
$('.img-div').append("<img src='https://istack.000webhostapp.com/1tf.svg'>");
}
}
if(op==3){
for(var i = 0;i<op;i++){
$('.img-div').append("<img src='https://istack.000webhostapp.com/_1tf.svg'>");
}
}
if(op==4){
for(var i = 0;i<op;i++){
$('.img-div').append("<img src='http://svgur.com//i/1yP.svg'>");
}
}
}
else{
$('.btn').hide();
}
$('img').each(function() {
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass + ' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
});
(function(exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function(el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
var wrapper = document.getElementById('img-div');
html2canvas(wrapper, {
onrendered: function(canvas) {
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: el.left + window.scrollX,
top: el.top + window.scrollY
}
}
var cachedCanvas = canvas;
var ctx = canvas.getContext('2d');
var svgs = document.querySelectorAll('svg');
svgs.forEach(function(svg) {
var svgWidth = svg.width.baseVal.value;
var svgHeight = svg.height.baseVal.value;
var svgLeft = getOffset(svg).left - 40;
var svgTop = getOffset(svg).top - 62;
var offScreenCanvas = document.createElement('canvas');
offScreenCanvas.width = svgWidth;
offScreenCanvas.height = svgHeight;
canvg(offScreenCanvas, svg.outerHTML);
ctx.drawImage(cachedCanvas, 0, 0);
ctx.drawImage(offScreenCanvas, svgLeft, svgTop);
});
canvas.toBlob(function(blob) {
saveAs(blob, 'myScreenshot.png');
});
}
});
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function(e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
screenshotPage();
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
});
</script>
html,
body {
background: #f1f1f1;
font-family: 'Merriweather', sans-serif;
padding: 1em;
}
form {
border: 2px solid blue;
float: left;
max-width: 300px;
padding: 5px;
text-align: center;
width: 30%;
}
.img-div {
border: 1px solid black;
display: block;
float: left;
margin-right: 86px;
overflow: hidden;
width: 50%;
padding: 10px;
}
.btn {
display: none;
overflow: hidden;
width: 100%;
}
.new{
display: block;
overflow: hidden;
width: 100%;
}
.description-div {
border: 2px solid green;
float: left;
margin-right: 32px;
padding: 3px;
width: 13%;
}
.submit {
background: wheat none repeat scroll 0 0;
border: 1px solid red;
cursor: pointer;
}
input,
textarea {
border: 0;
outline: 0;
padding: 1em;
#include border-radius(8px);
display: block;
width: 100%;
margin-top: 1em;
font-family: 'Merriweather', sans-serif;
#include box-shadow(0 1px 1px rgba(black, 0.1));
resize: none;
&:focus {
#include box-shadow(0 0px 2px rgba($red, 1)!important);
}
}
#input-submit {
color: white;
background: $red;
cursor: pointer;
&:hover {
#include box-shadow(0 1px 1px 1px rgba(#aaa, 0.6));
}
}
But here (1) when i take screen shot of img-div the screenshot is different from original representation. Why it happen ?
(2) Also in option 4 screenshot the svg is not appearing . Actually i have too many option and too many images . Now i only write 3 options .
(3) Is it possible for to save this screen shot to server[specific folder] when user submitting the form ?
(4) Is there any other method without using html canvas ?
(5) LIKE HOW SCREEN SHOT OPTION IN COMPUTER WORKS ? or browser extension like https://chrome.google.com/webstore/detail/awesome-screenshot-screen/nlipoenfbbikpbjkfpfillcgkoblgpmj?hl=en .
https://www.youtube.com/watch?v=3766n-SDPNc&feature=youtu.be
Short form : i have a website . In which user can select any svg from
the given svg list . When user select one svg then that svg is
converted to inline svg displayed in one div . Also user can move
that svg to any portion of the div . After everything then user will
fill a form and submit . At the time of submit we want to download the
screen shot of that div then we understand user select which colour ,
where the svg imge is place etc
Please check below mentioned solution. I just tried to cover up your issue.
$(function() {
$(".desgign-class").on("change",function(){
var op=$(this).val();
if(op!=0){
$('.btn').show();
$('.img-div').html('');
if(op==2){
for(var i = 0;i<op;i++){
$('.img-div').append("<img src='https://istack.000webhostapp.com/1tf.svg'>");
}
}
if(op==3){
for(var i = 0;i<op;i++){
$('.img-div').append("<img src='https://istack.000webhostapp.com/_1tf.svg'>");
}
}
if(op==4){
for(var i = 0;i<op;i++){
$('.img-div').append("<img src='http://svgur.com//i/1yP.svg'>");
}
}
}
else{
$('.btn').hide();
}
$('img').each(function() {
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass + ' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
});
(function(exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function(el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
var wrapper = document.getElementById('img-div');
html2canvas(wrapper, {
onrendered: function(canvas) {
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: el.left + window.scrollX,
top: el.top + window.scrollY
}
}
var cachedCanvas = canvas;
var ctx = canvas.getContext('2d');
var svgs = document.querySelectorAll('svg');
var sleft = 0;
svgs.forEach(function(svg) {
var svgWidth = svg.width.baseVal.value;
var svgHeight = svg.height.baseVal.value;
var svgLeft = 10;
var svgTop = getOffset(svg).top - 40;
var offScreenCanvas = document.createElement('canvas');
offScreenCanvas.width = svgWidth;
offScreenCanvas.height = svgHeight;
canvg(offScreenCanvas, svg.outerHTML);
ctx.drawImage(cachedCanvas, 0, 0);
ctx.drawImage(offScreenCanvas, svgLeft, svgTop);
});
canvas.toBlob(function(blob) {
saveAs(blob, 'myScreenshot.png');
});
}
});
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function(e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
screenshotPage();
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
});
#import url(https://fonts.googleapis.com/css?family=Merriweather);
$red: #e74c3c;
*,
*:before,
*:after {
#include box-sizing(border-box);
}
html,
body {
background: #f1f1f1;
font-family: 'Merriweather', sans-serif;
padding: 1em;
}
h1 {
text-align: center;
color: #a8a8a8;
#include text-shadow(1px 1px 0 rgba(white, 1));
}
form {
border: 2px solid blue;
float: left;
max-width: 300px;
padding: 5px;
text-align: center;
width: 30%;
}
.img-div {
border: 1px solid black;
display: block;
float: left;
margin-right: 86px;
overflow: hidden;
width: 50%;
padding: 10px;
}
.btn {
display: none;
overflow: hidden;
width: 100%;
}
.new{
display: block;
overflow: hidden;
width: 100%;
}
.description-div {
border: 2px solid green;
float: left;
margin-right: 32px;
padding: 3px;
width: 13%;
}
.submit {
background: wheat none repeat scroll 0 0;
border: 1px solid red;
cursor: pointer;
}
input,
textarea {
border: 0;
outline: 0;
padding: 1em;
#include border-radius(8px);
display: block;
width: 100%;
margin-top: 1em;
font-family: 'Merriweather', sans-serif;
#include box-shadow(0 1px 1px rgba(black, 0.1));
resize: none;
&:focus {
#include box-shadow(0 0px 2px rgba($red, 1)!important);
}
}
#input-submit {
color: white;
background: $red;
cursor: pointer;
&:hover {
#include box-shadow(0 1px 1px 1px rgba(#aaa, 0.6));
}
}
textarea {
height: 126px;
}
}
.half {
float: left;
width: 48%;
margin-bottom: 1em;
}
.right {
width: 50%;
}
.left {
margin-right: 2%;
}
#media (max-width: 480px) {
.half {
width: 100%;
float: none;
margin-bottom: 0;
}
}
/* Clearfix */
.cf:before,
.cf:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.cf:after {
clear: both;
}
.half.left.cf > input {
margin: 5px;
}
#media print {
html, body { padding:0 !important;margin:0 !important; }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdn.rawgit.com/canvg/canvg/master/canvg.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="test">
<div class="description-div">
<p>Sample description</p>
</div>
<div class="img-div" id="img-div"></div>
</div>
<form class="cf">
<div class="half left cf">
<input type="text" name="user-name" required>
<select name="design-name" class="desgign-class" required>
<option value="" >select</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<input type="submit" name="submit" value="submit" class="submit">
</div>
</form>
</div>
<div class="new">
<a class="btn btn-success" href="javascript:void(0);" onclick="generate();">Generate Screenshot »</a>
</div>
As far as I can tell, this is a working version: https://jsfiddle.net/7bqukhff/16/
The difference comes from the way you are drawing onto the offscreenCanvas.
Here's what happens in your code:
You are setting the dimensions of the offscreenCanvas to the width and height of the SVG (instead of the width & height of the wrapper) in lines 108 & 109
You subtract something (40 and 62) from the left & top position of the SVG. This position is referring to the position on the page rather than the relative position of the SVG within the wrapper.
You draw the SVG onto the canvas with page-coordinates instead of relative coordinates
The fix looks like this:
First, set the dimensions of the canvas to the dimensions of the wrapper:
var wrapperRect = wrapper.getBoundingClientRect()
// ...
offScreenCanvas.width = wrapperRect.width;
offScreenCanvas.height = wrapperRect.height;
Then, draw the svg using relative coordinates:
var svgLeft = getOffset(svg).left - wrapper.left;
var svgTop = getOffset(svg).top - wrapper.top;
This seems to work as you need.
P.S.: The option "4" doesn't work but that's due to it using HTTP on an HTTPS site, so it's not loaded due to security restrictions.
I have the following form for lyrics upload. I've changed the design of the form a little bit, and now facing a weird problem.
I've created a fake-datalist using JS. On input focus, a fake-datalist (an ul element) is appended next to the input element. Its position is set to absolute so it shouldn't disrupt the flow of the document when it appears. However, it does. I can't seem to identify the problem. Once the datalist appears, the div next to the table gets pushed down. Table width isn't changing when the datalist appears, so it's not squizing the div and pushing it down.
Code Pen
var artists = [{"artist":"3 Doors Down"},{"artist":"5 Seconds of Summer"},{"artist":"Adele"},{"artist":"Alicia Keys"},{"artist":"Amanda Abizaid"},{"artist":"Avril Lavigne"}];
var albums = [{"album":"The Better Life","year":"2000","cover":"3_doors_down_2000_the_better_life.jpg"},{"album":"Away from the Sun","year":"2002","cover":"3_doors_down_2002_away_from_the_sun.jpg"},{"album":"Seventeen Days","year":"2005","cover":"3_doors_down_2005_seventeen_days.jpg"},{"album":"3 Doors Down","year":"2008","cover":"3_doors_down_2008_3_doors_down.jpg"},{"album":"Time of My Life","year":"2011","cover":"3_doors_down_2011_time_of_my_life.jpg"}];
var songs = [{"song":"Kryptonite","track_no":"1"},{"song":"Duck and Run","track_no":"3"},{"song":"Be Like That","track_no":"5"},{"song":"So I Need You","track_no":"11"}];
function datalist(element) {
return new datalist.prototype.init(element);
}
datalist.prototype = {
init: function(element) {
if (!element) {
this.element = document.createElement("ul");
this.element.classList.add("datalist");;
this.hide();
} else {
this.element = element;
}
},
update: function(queryElement) {
this.clear();
var lookUpArray = queryElement.name + "s";
var results = this.search(window[lookUpArray], queryElement.value, queryElement.name);
for (var i = 0; i < results.length; i++) {
var li = document.createElement("li");
var value = results[i][queryElement.name];
switch (queryElement.name) {
case "album":
li.setAttribute("data-year", results[i].year);
break;
case "song":
li.setAttribute("data-track_no", results[i].track_no);
break;
}
if (queryElement.value != "") {
var re = new RegExp(queryElement.value, "gi");
value = value.replace(re, "<span class=\"highlight\">" + "$&" + "</span>");
}
li.innerHTML = value;
this.element.appendChild(li);
}
return results.length;
},
search: function(lookUpArray, string, queryType) {
var results = [];
for (var i = 0; i < lookUpArray.length; i++) {
if (lookUpArray[i][queryType].toLowerCase().search(string.toLowerCase()) != -1) {
results.push(lookUpArray[i]);
}
}
return results;
},
clear: function() {
this.element.innerHTML = "";
},
hide: function() {
this.element.style.display = "none";
},
show: function() {
this.element.style.display = "";
},
remove: function() {
this.element.parentElement.removeChild(this.element);
},
for: function(sibling) {
sibling.parentElement.appendChild(this.element);
this.hide();
},
};
datalist.prototype.init.prototype = datalist.prototype;
var lastVisitedInput = null;
$("#lyrics-form").on("focus", "input.datalist-input", function() {
if (this.parentElement.children.length == 1) {
this.parentElement.appendChild(datalist().element);
}
if (lastVisitedInput) {
datalist(lastVisitedInput.nextElementSibling).hide();
}
lastVisitedInput = this;
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$(document).on("click", function(e) {
if (lastVisitedInput) {
var exceptions = getExceptions(lastVisitedInput);
if (!contains(exceptions, e.target)) {
datalist(lastVisitedInput.nextElementSibling).remove();
lastVisitedInput = null;
}
}
});
$("#lyrics-form").on("input", "input.datalist-input", function() {
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$("#lyrics-form").on("click", "li", function() {
this.parentElement.previousElementSibling.value = this.innerText;
$(this.parentElement.previousElementSibling).trigger("input");
});
function getRecord(input) {
var lookUpArray = window[input.name + "s"];
for (var i = 0; i < lookUpArray.length; i++) {
if (input.value == lookUpArray[i][input.name]) {
return lookUpArray[i];
}
}
return false;
}
function getExceptions(input) {
var exceptions = [
input,
input.nextElementSibling,
];
for (var i = 0; i < input.nextElementSibling.children.length; i++) {
exceptions.push(input.nextElementSibling.children[i]);
}
return exceptions;
}
function contains(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
return true;
}
}
return false;
}
* { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } *, *:before, *:after { box-sizing: inherit; } body { line-height: 1.5; font-family: sans-serif; } input[type="button"], input[type="submit"] { cursor: pointer; } textarea, input[type="text"], input[type="search"], input[type="number"], input[type="password"] { border: 1px solid rgba(0,0,0,.2); padding: 4px; margin: 1px; } table { border-collapse: collapse; border-spacing: 0; }
body {
background-color: rgb(230, 230, 230);
font-family: Arial, sans-serif;
font-size: 14px;
color: rgba(0, 0, 0, .8);
box-sizing: border-box;
}
#main {
height: 500px;
background: white;
box-shadow: 0 0 2px rgba(0, 0, 0, .1), 0 2px 2px rgba(0, 0, 0, .1);
margin: 20px auto;
display: table;
padding: 20px;
}
#songInput {
overflow: auto;
}
#songTable td {
position: relative;
}
#songTable,
#coverDiv {
float: left;
}
#coverDiv {
margin-left: 20px;
}
#artist,
#album,
#song {
width: 250px;
}
#artist {
width: 300px;
width: 100%;
}
#year,
#track_no {
width: 70px;
}
#songTable td {
padding-bottom: 20px;
}
#songTable td:first-child {
padding-right: 10px;
}
#songTable .int-input {
padding-left: 20px;
padding-right: 10px;
}
#coverDiv > * {
display: block;
}
#coverDiv img {
width: 137px;
height: 137px;
border: 1px solid rgba(0, 0, 0, .2);
margin: 1px;
}
#coverUpload {
margin: 1px;
margin-top: 10px;
width: 250px;
}
#lyricsBox {
width: 100%;
height: 400px;
margin-top: 15px;
}
#submit {
width: 100%;
margin-top: 15px;
}
.datalist {
border: 1px solid silver;
box-shadow: 0 2px 5px rgba(0, 0, 0, .5);
position: absolute;
top: 32px;
left: 1px;
background: white;
padding: 5px;
max-height: 195px;
width: 180px;
width: 100%;
overflow-y: scroll;
z-index: 1000;
}
.datalist li {
padding: 2px 5px;
cursor: default;
}
.datalist li:hover {
background: rgba(0, 0, 0, .05);
color: black;
}
.datalist .highlight {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<form action="addlyrics.php" id="lyrics-form" method="post" autocomplete="off" enctype="multipart/form-data">
<div id="songInput">
<table id="songTable">
<tr>
<td>Artist</td>
<td colspan="3">
<input type="search" name="artist" id="artist" class="datalist-input" placeholder="Artist" required />
</td>
</tr>
<tr>
<td>Album</td>
<td>
<input type="search" name="album" id="album" class="datalist-input" placeholder="Album" required />
</td>
<td class="int-input">Year</td>
<td>
<input type="number" name="year" id="year" class="input-num" placeholder="Year" required />
</td>
</tr>
<tr>
<td>Song</td>
<td>
<input type="search" name="song" id="song" class="datalist-input" placeholder="Name" required />
</td>
<td class="int-input">#</td>
<td>
<input type="number" name="track_no" id="track_no" class="input-num" placeholder="ID" required />
</td>
</tr>
</table>
<div id="coverDiv">
<img src="covers/blank.gif" id="cover" />
<input type="file" name="cover" id="coverUpload" accept="image/*" />
</div>
</div>
<textarea name="lyrics" placeholder="Lyrics" id="lyricsBox" /></textarea>
<input type="submit" id="submit" class="button" />
</form>
</div>
Removing overflow: auto; from #songInput, the parent element of the table and the div, solved the problem. Although, I don't understand why overflow: auto; on the parent would push the div down. Dynamically added ul.datalist's position is set to absolute, and when it appears, the only thing it might do is extend the height of the table, which shouldn't effect the div at the right.
Currently i am able to replicate a form, however i want to set a limit to the number of times it is able to do so(replicate). Is there a way to make it so that when, for example i want the limit to be 5, once the total number of forms hit 5 the "add" button will be disabled(when i click it, its does nothing). However when i remove a form the "add" button becomes functional(can add form) again. I am only allowed to use HTML CSS and Javascript.
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<label>Choose a picture<br><input type="file" ' + i + '" value="" /><img class="target" src="#" alt="Choose and Upload" />Remove</label><br>').appendTo(addDiv);
i++;
$('fieldset input').change(function() {
if (this.files && this.files[0]) {
var $target = $(this).next('.target');
var reader = new FileReader();
reader.onload = function(e) {
$target.attr('src', e.target.result).width(150).height(112);
};
reader.readAsDataURL(this.files[0]);
}
});
return false;
});
$('#remNew').live('click', function() {
if (i > 2) {
$(this).parents('label').remove();
i--;
}
return false;
});
});
.locationsector {
border-radius: 5px;
border: 5px solid black;
width: 30%;
margin-left: 0.79%;
float: left;
padding: 10px;
}
img {
text-align: center;
margin: 2%;
display: inline-block;
border: 10px solid #140E26;
border-radius: 10px;
padding: 5px;
width: 150px;
height: 112px;
}
#addNew {
background: black;
margin-left: 2%;
padding: 5px;
font-size: 15px;
color: white;
display: inline-block;
width: 100px;
border: 1px solid #140E26;
border-radius: 10px;
cursor: pointer;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<fieldset class="locationsector" id="addinput">
<legend>Test</legend>
<p>
<label for="north">Choose a Picture
<br>
<input type="file" required="required" />
<img class="target" src="#" alt="Choose and Upload" />
</label>
<br>
<a id="addNew">Add</a>
</p>
</fieldset>
You already have a counter i and that's good.
This will make it simpler for you to limit the replication:
// ...
$('#addNew').live('click', function() {
if(i > 5) {
alert("Reached maximum number of fields.");
return false;
}
$('<label>Choose a picture<br><input type="file" ' + i + '" value="" /><img class="target" src="#" alt="Choose and Upload" />Remove</label><br>').appendTo(addDiv);
// ...
The alert call is optional (You mentioned doing nothing?)