I am using Jquery UI Dialog. Within the dialog there is textarea that have some text. And I need to save that text as textfile like data.txt when I click the button in the dialog.
<div id = 'metaDataDialog' title='Meta Data' >
<textarea id = 'metaText'>
Some Text
</textarea>
</div>
and this is the jquery ui dialog
$("#metaDataDialog").dialog({ //Jquery UI Dialog Intialization
autoOpen: false,
modal: true,
width: 400,
height: 300,
buttons: {
Save: function() {},
Cancel: function() { $(this).dialog( "close" ); }
},
});
and I need to save/download the text in the local machine, when the save button is clicked
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
function saveTextAsFile() {
// grab the content of the form field and place it into a variable
var textToWrite = document.getElementById("content").value;
// create a new Blob (html5 magic) that conatins the data from your form feild
var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
// Specify the name of the file to be saved
var fileNameToSaveAs = "myNewFile.txt";
// Optionally allow the user to choose a file name by providing
// an imput field in the HTML and using the collected data here
// var fileNameToSaveAs = txtFileName.text;
// create a link for our script to 'click'
var downloadLink = document.createElement("a");
// supply the name of the file (from the var above).
// you could create the name here but using a var
// allows more flexability later.
downloadLink.download = fileNameToSaveAs;
// provide text for the link. This will be hidden so you
// can actually use anything you want.
downloadLink.innerHTML = "My Hidden Link";
// allow our code to work in webkit & Gecko based browsers
// without the need for a if / else block.
window.URL = window.URL || window.webkitURL;
// Create the link Object.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
// when link is clicked call a function to remove it from
// the DOM in case user wants to save a second file.
downloadLink.onclick = destroyClickedElement;
// make sure the link is hidden.
downloadLink.style.display = "none";
// add the link to the DOM
document.body.appendChild(downloadLink);
// click the new link
downloadLink.click();
}
function destroyClickedElement(event) {
// remove the link from the DOM
document.body.removeChild(event.target);
}
$("#download").click(function (e) {
e.preventDefault();
saveTextAsFile();
});
});
</script>
</head>
<body>
<input type="button" id="download" value="Download" />
<textarea id="content">In trying to keep this plugin as simple as possible, all four states are always assumed to be present. You should prepare your button image as a single image the width you want your button, and four times the height of the button. All four states should then live in that one image in the same order as the previous list from top to bottom.</textarea>
</body>
</html>
Related
I know there are other ways of creating a button in JavaScript but below code works for me. However, can somebody help me on how I can make this clickable and browse a file inside Windows and select that file?
Also, this button is positioned at lower left part of the screen. I would appreciate if you can teach me how I can make it somewhere middle or how to position it properly.
Pardon my lack of knowledge in JavaScript, I just started learning 2 days ago :) Thank you very much in advance.
// ==UserScript==
// #name Test Tampermonkey Script
// #version 0.1
// #description Test
// #author Me
// #match https://test.com/*
// #grant GM_xmlhttpRequest
// #grant GM_info
// ==/UserScript==
(function() {
'use strict';
/*--- Create a button in a container div. It will be styled and
positioned with CSS.
*/
var zNode = document.createElement('div');
zNode.innerHTML = '<button id="myButton" type="button">' +
'Browse a file:</button>';
zNode.setAttribute('id', 'myContainer');
document.body.appendChild(zNode);
//--- Activate the newly added button.
document.getElementById("myButton").addEventListener(
"click", ButtonClickAction, false
);
})();
Let's be clear...
If you need to just let the user choose from his files and give you one or more of them, you can just use the input with type="file" and it will do the full job to you, and if you need to have a full access throw the file system of the user and navigate through it yourself from the root directory, then you can use the file system api which you can file more information about it here: MDN FileSystem API
Now let's talk about the first idea which I think it's what you need.
You need a button to click, and when clicking, the user needs to be able to choose a file from his computer, and when he finish choosing a file, you will take this file and use it.
First you will create three elements, a label contains a button and an input, and the input will be hidden but the button will be shown:
function createButton() {
let label = document.createElement("label")
let input = document.createElement("input")
input.setAttribute("type", "file")
input.style.display = "none"
input.addEventListener("change", getFile)
let button = document.createElement("button")
button.innerText = "Browse a file:"
button.addEventListener("click", () => input.click())
label.append( input, button )
document.body.append( label )
}
Now you have the button in your web page, and it's ready to listen for changes, now let's create the getFile function that will be run whenever the input changes:
function getFile( evt ) {
let reader = new FileReader()
reader.onload = () => {
let url = reader.result
// now you have access to the url of the file
// you can use it as you want
}
reader.readAsDataURL( evt.target.files[0] )
}
And now you have access to the url of the file entered to you from the user.. and you can use it as you want..
Now let's create a real working one to try here.
We will build an image uploader here:
createButton()
function createButton() {
let label = document.createElement("label")
let input = document.createElement("input")
input.setAttribute("type", "file")
input.style.display = "none"
input.addEventListener("change", getFile)
let button = document.createElement("button")
button.innerText = "Browse a file:"
button.addEventListener("click", () => input.click())
label.append( input, button )
document.body.append( label )
}
function getFile( evt ) {
let reader = new FileReader()
reader.onload = () => {
let url = reader.result
let img = document.createElement("img")
img.src = url
img.style.width = "150px"
img.style.height = "100px"
img.style.objectFit = "contain"
img.style.objectPosition = "center"
document.body.append(img)
}
reader.readAsDataURL( evt.target.files[0] )
}
Now you can run this code and try the result.
hey there i'm making a simple webpage which requires to download an output image file at the last step..
but i don't know how can i add download button dynamically at correct time, because at starting of a page there is no need of download button..
so i have main.js file:
which looks something looks like this:
let img_code=document.getElementById('img_code');
let textbox=document.getElementById('textbox');
let gen_button_img=document.getElementById("img_button");
gen_button_qr.addEventListener("click",()=>
{
var trailer=textbox.value;
var url='www.example.com';
var result= url.concat(trailer);
if (navigator.onLine)
{
if(trailer.length<=1725 && trailer.length>0)
{
if((trailer !="0")&& (trailer.replace(/\s/g, '').length))
{
image_code.src=result;
alert("Image Generated successfully");
/**/
}
else
{
alert("You cannot create this file spaces only or only with single 0");
}
}
else
{
alert("Maximum charecter limit is exceeded!! ");
}
}
else
{
alert("No Internet Connection");
}
});
So, i have the question is there any way to dynamically add the button which takes file URL as input and download that file through web browser's downloader?
Note=>
I can easily save the result by right click on the picture and save image option; but i want to add an extra button to download the same file.
Most of the things explained in comments so read it first
// arrow function to create and append download button into any element
// it only takes url of file that will download.
const createBtn = (URL) => {
// create button element
const downloadBtn = document.createElement("button");
// you can set any name of id according to your choice
downloadBtn.setAttribute("id", "downloadBtn");
// create anchor element
const downloadLink = document.createElement("a");
// set any thing in inner text
downloadBtn.innerText = "Download Image";
// set download attribute to true
downloadLink.setAttribute("download", true);
// set url with URL
downloadLink.setAttribute("href", URL);
// append button element into anchor element
downloadLink.appendChild(downloadBtn);
// get that element in which download button will append
const container = document.getElementById("container");
// append download button into any element of your choice
container.appendChild(downloadLink);
};
// url of file
const URL = "https://images.pexels.com/photos/863963/pexels-photo-863963.jpeg?cs=srgb&dl=pexels-blaque-x-863963.jpg&fm=jpg"
// call createBtn function with URL
createBtn(URL);
<!-- The element in which download button will be appended -->
<div class="container" id="container"></div>
I am not 100% sure that this will work!
It also not work in stack snippet because iframe tag.
Try to use it locally.
How is it possible to upload a file directly without clicking file upload button(I want to click Add Widget Button which should give file upload dialog box)
I have a button declared as follows:
<button class="add-button" style="float:top;">Add Widget</button>
On clicking the button the following function is invoked
$(".add-button").on("click", function() {
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($('<img src="abc.png" height="60px" width="60px">'));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
});
But I first want a upload box to appear where in user can upload the image as soon as the button is clicked then the above code should get executed
I did something like this
$(".add-button").on("click", function() {
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
x.setAttribute("onclick","previewFile()");
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($('<img src="abc.png" height="60px" width="60px">'));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
});
But this does not brings any dialog box where user can upload the image
This uploaded image I want to then use in the place of
.append($('uploaded image'));
Preview File Function (This also needs to be modified)
function previewFile() {
var preview = document.createElement('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader(); //API for reading file stored on user computer
reader.addEventListener("load", function () { //"load" :This eventlisterner "listens" loading of file. Once it is loaded function is triggered
preview.src = reader.result;
});
if (file) {
reader.readAsDataURL(file); // helps in reading the content of "file"
}
document.body.appendChild(preview);
}
My aim is that preview file function should return an image which I can put in
.append($('image from preview file'));
A version of code is at Fiddle
The way to do this is to have some hidden input with file type somewhere on the dom. You might be able to programatically put it there, but really no point in that. Once the add widget button is clicked, you can simulate a click for the hidden input. This will initiate a prompt to pick a file. Then what you want to do is, wait until the file has been "picked" by the user. This is done via the onchange event. Within that, you can grab the file, read it, and then when it's done you can have a callback via the onload method. I put up a working example here. I imagine you wanted to have the file picked as the image set on the src, so I did that as well.
hidden input
<input id="test" type="file" style="position: absolute; top: -10; left: -10; height: 0; width: 0;" />
button click function (this is what will wait until the file has been chosen), the call back method is used on the onload event of the filereader.
$(".add-button").on("click", function() {
$('#test').click();
$('#test').on('change', function(e) {
var test = document.getElementById('test');
if (!test) {
alert("Um, couldn't find the fileinput element.");
}
else if (!test.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!test.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = test.files[0];
console.log(file);
fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = function() {
var data = fr.result; // data <-- in this var you have the file data in Base64 format
callbackAddButton(data);
test.value = ''; //here we are resetting the file input's files
$('#test').replaceWith($('#test').clone()); //here we are resetting the input, if we clone the input with the files then it wont trigger the onchange event if you upload same image. So we need to make sure we have these 2 calls.
};
}
})
});
And finally, the callback method. Which is simply exactly what you had before but now only gets called once the file has been done (done as in, you read it via filereader and have access to contents if needed). The only difference here is now you have a base64 representation of the image the user uploaded. Which I am setting to the new image widget you created.
function callbackAddButton(file) {
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($(`<img src="${file}" height="60px" width="60px">`));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
}
EDIT
Once you're done with the input file element, it's good practice to now clear it because you dont need the file anymore (from the input at least, since you have a base64 representation). Just append a $('#test').replaceWith($('#test').clone()) after the you make the callback call.
I want to make a dialog box where the user can see the image that he/she has just uploaded. The file uploading systems works fine but when I want to put the image into the dialog box dynamically only an empty box appears.
HTML Code:
<div id="dialogbox">{I want to change this conetent here to an image}</div>
jQuery/Javascript Code:
function completeHandler(event){
var data = event.target.responseText;
var datArray = data.split("|");
if(datArray[0] == "upload_complete_msg"){
hasImage = datArray[1];
$(function() {
$("#dialogbox").dialog();
$("#dialogbox").html('sadasdasd');
});
} else {
_("uploadDisplay_SP_msg_"+datArray[2]).innerHTML = datArray[0];
_("triggerBtn_SP_"+datArray[2]).style.display = "block";
}
The datArray[] is a response text from the PHP validation. datArray[0] is equal to upload_complete_msg if it succeeded, datArray[1] is the image file name and extension like filename123.jpg and darArray[2] is just an id. So as I said if the user has successfully uploaded the image a dialog box should appear. I tried to add more content with the .html() function but it didn't show me anything again just an empty dialog box. How would it be possible to put an image into this dialog box like $("#dialogbox").html('<img src="imgfolder/myimage.jpg">');?
Try something like this?
function completeHandler(event) {
var data = event.target.responseText;
var datArray = data.split("|");
if (datArray[0] == "upload_complete_msg") {
hasImage = "tempUploads/"+datArray[1];
// Create a jQuery image object, and assign the src attribute.
var imgEl = $("<img>").attr("src", hasImage);
// stick that imgEl into the dialog.
$("#dialogbox").html(imgEl);
$("#dialogbox").dialog();
} else {
_("uploadDisplay_SP_msg_" + datArray[2]).innerHTML = datArray[0];
_("triggerBtn_SP_" + datArray[2]).style.display = "block";
}
}
I am trying to display a button if the src attribute of an iframe on the same page contains a certain text.
See jsFiddle for example.
I am basically trying to only show the "download MP3" button if the iframe has a valid soundcloud url as src attribute.
The one thing all valid soundcloud iframes have in common is: all src urls start with
//w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F
You can get the dom element, and check it's src attribute.
Something like that:
const src = document.getElementById('ifrm').src;
if (src.indexOf('some')) {
console.log('YAY');
} else {
console.log('Not Yay')
}
<iframe src="https://some-site.com" id="ifrm" />
consider the following code snippet:
var btn = document.getElementById("buttonId");//get the button
var src = document.getElementById("iframeId").src; // get the src
var url = "//w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F"
if(src.indexOf(url) !=-1){ //this will return -1 if false
btn.style.display = "inline-block";//show the button
}else{
btn.style.display = "none";//hide the button
}
or you can use regular expression test function :
var btn = document.getElementById("buttonId");//get the button
var src = document.getElementById("iframeId").src; // get the src
var patt = //"/w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F"/;
if(patt.test(src)){ // will return true if found
btn.style.display = "inline-block";//show the button
}else{
btn.style.display = "none";//hide the button
}
hope it helps