I need to create a new <a> element with the download property and target blank. This link must not be visible in html and will be clicked with JavaScript.
let a = document.createElement("a");
document.body.appendChild(a);
a.setAttribute("style", "display: none");
a.href = blobUrl;
a.target = "_blank";
a.download = "MyFileName.pdf";
a.click();
Result in HTML:
The problem is that the target blank seems to be ignored. It worked until recently and there have been no changes. What could be the problem?
Try this, and also please move the document.body.appendChild(a); to the end just like what I have done.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function createA(){
let a = document.createElement("a");
a.setAttribute("style", "display: none");
a.href = "#";
a.target = "_blank";
a.download = "MyFileName.pdf";
a.click();
a.innerHTML = "SomeText";
document.body.appendChild(a);
}
createA();
</script>
</body>
</html>
Please let me know if your problem has been solved by voting the answer :)
Related
If I assign a text input tag to the id stored_data1 in the code below, would I be able to save my data client-side (such as saving it on a flash drive)?
HTML
Data that is retrieved will appear here
<div id="dataStore"></div>
JS
<script>
if (typeof Storage !== 'undefined') {
localStorage.setItem('stored_data1', 'Blue Box');
document.getElementById('dataStore').innerHTML =
localStorage.getItem('stored_data1');
} else {
// in case web storage is not supported
document.getElementById('dataStore').innerHTML =
'Web storage not supported.';
}
</script>
The code above is a web storage API for HTML. I'm hoping to find a way to eventually fit it into some programs I made.
You can download the information on the tag using the following code
//create a function to download text to textfile
function downloadText(text, filename){
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
//get Text Value then download
var textValue = document.getElementById("test").innerText;
download(textValue, "store_data");
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>Data that is retrieved will appear here</p>
<div id="dataStore"></div>
</body>
<script>
if (typeof(Storage) !== "undefined") {
window.localStorage.setItem("stored_data1", "Blue Box");
document.getElementById("dataStore").innerHTML = window.localStorage.getItem("stored_data1");
} else {
document.getElementById("dataStore").innerHTML = "Web storage not supported.";
}
</script>
</html>
I'm trying to convert some jQuery into vanilla JavaScript, but this one just stumped me:
$('<span>[Add]</span>')
It's not a selector, it creates the DOM elements from this markup and wraps it in a jQuery object. See the docs.
const $el = $('<span>[Add]</span>');
console.log( $el.html() );
$("body").append( $el );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So the vanilla equivalent would be
const span = document.createElement("span");
const a = document.createElement("a");
a.href = "#";
a.id = "addlink";
a.textContent = "Add";
span.append( "[", a, "]" );
document.body.append( span );
The Vanilla Javascript approach for the same could also be achieved using setAttribute() , createTextNode() and appendChild() as follows. Just another way to do this.
const span = document.createElement("span");
const a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("id", "addlink");
const text = document.createTextNode("Add");
a.appendChild(text);
span.append("[", a, "]");
document.body.appendChild(span);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<script src="./script.js"></script>
</body>
</html>
I want change at runtime the favicon. My code works when the page is opened in a tab, but doesn't works when the page is opened in a popup
demo online
I have tested on latest Chrome, Firefox and Edge and doesn'works, but works on Internet Explorer 11.
this is the code used for change the favicon:
function changeFavicon(src) {
// delete the current favicon from the DOM
var oldLink = document.getElementById('appFavicon');
if (oldLink) {
document.head.removeChild(oldLink);
}
// add the new favicon
var link = document.createElement('link');
link.id = 'appFavicon';
link.rel = 'shortcut icon';
link.href = src;
document.head.appendChild(link);
}
this is the full favicon.html made for the gif:
<!doctype html>
<html>
<head>
<link rel="shortcut icon" id="appFavicon" href="favicon.ico">
</head>
<body>
<script>
function popUp(url,windowName) {
newwindow=window.open(url,windowName,'height=200,width=350');
if (window.focus) {newwindow.focus()}
return false;
}
function changeFavicon(src) {
var oldLink = document.getElementById('appFavicon');
if (oldLink) {
document.head.removeChild(oldLink);
}
var link = document.createElement('link');
link.id = 'appFavicon';
link.rel = 'shortcut icon';
link.href = src;
document.head.appendChild(link);
}
</script>
<p><button onclick="changeFavicon('https://c5-excel-15.cdn.office.net/x/_layouts/resources/FavIcon_Excel.ico')">Excel</button></p>
<p><button onclick="changeFavicon('https://c5-powerpoint-15.cdn.office.net/p/resources/1033/FavIcon_Ppt.ico')">Power Point</button></p>
<p><button onclick="changeFavicon('https://c5-word-view-15.cdn.office.net/wv/resources/1033/FavIcon_Word.ico')">Word</button>
<br /><br />
<button onclick="popUp('favicon.html')">Open this page in a PopUp</button></p>
</body>
</html>
I have a code in javascript and return [object NodeList]
how i could correct this
please help me
<!DOCTYPE html>
<html lang="en" class="no-js">
<head lang="en">
<script>
function downloadDiv(filename, elementId, mimeType) {
var elementHtml = document.querySelectorAll('div1');
var link = document.createElement('a');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elementHtml));
link.click();
}
var fileName = 'divContents.html';
</script>
var elementHtml = document.querySelectorAll('div1');
document.querySelectorAll returns a NodeList object, which is a collection of DOM nodes.
You want the HTML content, presumably, of the first of them:
var elementHtml = document.querySelectorAll('div1')[0].innerHTML;
If there may be more (or indeed less!) than one, the sensible option is to do this as a loop:
var elementHtml = [].map.call(document.querySelectorAll('div1'), function(el) {
return el.innerHTML;
}).join();
I want to create text file (notepad type file) using javascript. My code is given below but it is not working plz. Suggest me any solution for creating text file.
var txt = new ActiveXObject("Scripting.FileSystemObject");
var s = txt.CreateTextFile("D:\\test.txt", true);// means file is store in my D drive.
s.WriteLine('Hello');
s.Close(); `
you can try this:
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
Also you can show this DEMO
The following code snippet demonstrate create a text files using the jQuery and HTML5 file API. For the sake of simplicity, in this example I am using Bootstrap CSS framework for building the page.
$('#btnSave').click(function() {
if ('Blob' in window) {
var fileName = prompt('Please enter file name to save', 'Untitled.txt');
if (fileName) {
var textToWrite = $('#exampleTextarea').val().replace(/n/g, 'rn');
var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
if ('msSaveOrOpenBlob' in navigator) {
navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
var downloadLink = document.createElement('a');
downloadLink.download = fileName;
downloadLink.innerHTML = 'Download File';
if ('webkitURL' in window) {
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.click(function(){
document.body.removeChild(event.target);
});
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
}
} else {
alert('Your browser does not support the HTML5 Blob.');
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Your HTML, CSS, and JavaScript playground.">
<title>HTML, CSS, JS Playground</title>
<meta content="width=device-width, initialscale=1" name="viewport">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" type="text/javascript"></script>
<script>
$(document ).ready(function() {
//Put your java script here
});
</script>
</head>
<body>
<div class="container">
<h1>Reading and Creating Text Files Using the HTML5 File API and jQuery</h1>
<div class="form-group">
<button type="button" class="btn btn-default" id="btnOpen">Open...</button>
<button type="button" class="btn btn-default" id="btnSave">Save</button>
</div>
<input type="file" id="exampleInputFile" accept=".txt,.csv,.xml" class="hidden">
<div class="form-group">
<textarea class="form-control" rows="15" id="exampleTextarea"></textarea>
</div>
</div>
</body>
source