I have tried so many examples but none of them works
t
(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>
here is a code which is working good but i need to download automatically without using link
is it possible?
You could use the following script to create and save automatically a file from the browser to your operating system. This code works only on latest version of Chrome.
What the script does?
It creates a temporary URL containing the specified File object or Blob object - Programmatically click the link just created so the file will be download by the browser.
Immediately after remove the link from the page.
var saveDataToFile = function (data, fileName, properties) {
window.URL = window.URL || window.webkitURL;
var file = new File(data, fileName, properties),
link = document.createElement('a');
link.href = window.URL.createObjectURL(file);
link.download = fileName;
document.body.appendChild(link);
link.click();
var timer = setTimeout(function () {
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
clearTimeout(timer);
}, 100);
};
If you deconstruct this problem, there's a few key points:
Initially, when the user hasn't typed text into the textarea, the button should not be visible. (I may be wrong here though)
When the user starts typing, the button has to appear.
Whatever is inside the textarea after that, has to be downloadable per click on the button.
So, it's a matter of two event listeners.
The first one is "focus": when the textarea received focus, its value is an empty string, and the button appears. The user hasn't yet started typing, but there's actually no need to force them to.
The second one is "change": per every change in the field, we need to update the value of href attribute of the link, so that when the user clicks that element, file download happens, and the content is precisely what's inside the textarea. Good thing, a function passed to "change" event listener is executed with the first argument instance of Event, which means you can do event.target.value to get the new value per every change. It means, the whole text from within textarea.
Summing up, it's
<textarea id="textbox" placeholder="Type something here"></textarea>
<a download="info.txt" id="create" href="#" style="display: none;">Create file</a>
and
(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');
var textbox = document.getElementById('textbox');
textbox.addEventListener('focus', function (event) {
create.style.display = 'block';
create.href = makeTextFile(''); // initially, the text is empty.
});
textbox.addEventListener('change', function (event) {
create.href = makeTextFile(event.target.value); // per every change, update value of href attribute of #create
});
})();
Take note that only a element can have href assigned with Blob value. Using a button element would be a little bit more complicated, so it might be easier to just make the a element look like a button.
See the Codepen to make sure it works as you expect, or feel free to edit it otherwise.
Related
I am creating a website builder using React and I want to be able to download the content of this component under the preview-container class.
MainWebsite contains multiple descendants and components.
export default function PreviewContainer({
selectItem
}) {
return (
<div className="preview-container" >
<div className="preview">
<MainWebsite selectItem={selectItem}/>
</div>
</div>
)
}
I tried using
function onClick() {
var pageHTML = document.querySelector('.preview-container');
var tempEl = document.createElement('a');
tempEl.href = 'data:attachment/text,' + encodeURI(pageHTML);
tempEl.target = '_blank';
tempEl.download = 'thispage.html';
tempEl.click();
}
This downloads a page that just says [object HTMLDivElement] in its content
Note though that I want to download this component with the css and js included
You can't download an abstract element.
You'll need the inner or outer HTML of the element, depending on your requirements. (You could also use ReactDOMServer.renderToString().)
Additionally, you should use a blob URL, since the HTML could be quite large and thus awkward to put in a data URL.
If you use a blob URL, it needs to be revoked (to release memory). Some browsers require an anchor element to be in the DOM when "clicked", so that needs to be removed too. Since there's no event for "download complete", there's a simple timeout for 2 seconds.
function onClick() {
const pageHTML = document.querySelector(".preview-container").outerHTML;
const blob = new Blob([pageHTML], { type: "text/html" });
const url = URL.createObjectUrl(blob);
const tempEl = document.createElement("a");
document.body.appendChild(tempEl);
tempEl.href = url;
tempEl.download = "thispage.html";
tempEl.click();
setTimeout(() => {
URL.revokeObjectUrl(url);
tempEl.parentNode.removeChild(tempEl);
}, 2000);
}
*update here is my code edit as you see working) https://codeshare.io/a3ZJ9g
i need to pass on a javascript varible to a html link...
my original question was here HTML5 video get currentTime not working with media events javscript addEventListener
working code:
<script>
var media = document.getElementById('myVideo');
// durationchange
var isdurationchange = function(e) {
$("#output").html(media.currentTime);
var x = document.createElement("a");
};
media.addEventListener("timeupdate", isdurationchange, true)
</script>
that code works
but i need it to echo the currentTime value to the html page such as
document.write("<a href=/time.htm?currentTime='.media.addEventListener("timeupdate", isdurationchange, true).'>link</a>;);
so it would print out
<a href=time.htm?currentTime=currenttimefromjavascript>link</a>
thank you
i did read:
how to pass javascript variable to html tag
How can I pass value from javascript to html?
someone suggested:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
but where does that go?
document.write tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
If, for an element you create dynamically, you want to change its href on every timeupdate, you would do:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
I have a very simple javascript which turns book isbns in to clickable URL links to Amazon.com. What I am trying to do is add a function that when "clicked" opens all the URL links in new tabs. This saves me the time of clicking every single link.
Is this doable? =)
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div>
<textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea>
<div><b>Hyperlinked text:</b></div>
<div id="output" style="white-space: pre"></div>
<script>
//the input box.
var input = document.getElementById('numbers');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
handler(); // run on load
</script>
</html>
You can trigger a click event manually, like:
container.appendChild(link);
link.click();
But that's just an example to show you easily that it would work with your given code. I would suggest having a button like "Open All Links" and having that button use a selector to gather up all the links and then loop through them and call the click method on each one. You would be making things easier on yourself giving the outer container (the output div) an ID that you could use as the initial outer selector.
I am very new to Javascript, I am making a HTML website.
Since I am new to Javascript, I do not know how to show an image, and when the image is clicked make it link to a page.
I know how to do it in HTML, but due to my free host if I wasn't to make a single change to how many images there are (which I will do a lot), or where it links to (which will be shown on every page) I will need to go through every page.
All I need it to do is open the page on the same tab.
Try this:
var img = new Image();
img.src = 'image.png';
img.onclick = function() {
window.location.href = 'http://putyourlocationhere/';
};
document.body.appendChild(img);
Without more information, I'm going to offer this as a relatively cross-browser approach, which will append an img element wrapped in an a element. This works with the following (simple) HTML:
<form action="#" method="post">
<label for="imgURL">image URL:</label>
<input type="url" id="imgURL" />
<label for="pageURL">page URL:</label>
<input type="url" id="pageURL" />
<button id="imgAdd">add image</button>
</form>
And the following JavaScript:
// a simple check to *try* and ensure valid URIs are used:
function protocolCheck(link) {
var proto = ['http:', 'https:'];
for (var i = 0, len = proto.length; i < len; i++) {
// if the link begins with a valid protocol, return the link
if (link.indexOf(proto[i]) === 0) {
return link;
}
}
// otherwise assume it doesn't, prepend a valid protocol, and return that:
return document.location.protocol + '//' + link;
}
function createImage(e) {
// stop the default event from happening:
e.preventDefault();
var parent = this.parentNode;
/* checking the protocol (calling the previous function),
of the URIs provided in the text input elements: */
src = protocolCheck(document.getElementById('imgURL').value);
href = protocolCheck(document.getElementById('pageURL').value);
// creating an 'img' element, and an 'a' element
var img = document.createElement('img'),
a = document.createElement('a');
// setting the src attribute to the (hopefully) valid URI from above
img.src = src;
// setting the href attribute to the (hopefully) valid URI from above
a.href = href;
// appending the 'img' to the 'a'
a.appendChild(img);
// inserting the 'a' element *after* the 'form' element
parent.parentNode.insertBefore(a, parent.nextSibling);
}
var addButton = document.getElementById('imgAdd');
addButton.onclick = createImage;
JS Fiddle demo.
I'm going to develop a firefox extension which adds a button beside the file input fields (the <input type="file"> tag) when a file is selected.
The file overlay.js, which contains the extension's logic, manages the "file choose" event through this method:
var xpitest = {
...
onFileChosen: function(e) {
var fileInput = e.explicitOriginalTarget;
if(fileInput.type=="file"){
var parentDiv = fileInput.parentNode;
var newButton = top.window.content.document.createElement("input");
newButton.setAttribute("type", "button");
newButton.setAttribute("id", "Firefox.Now_button_id");
newButton.setAttribute("value", "my button");
newButton.setAttribute("name", "Firefox.Now_button_name");
parentDiv.insertBefore(newButton, fileInput);
}
}
...
}
window.addEventListener("change", function(e) {xpitest.onFileChosen(e)},false);
My problem is that, everytime I choose a file, a new button is being added, see this picture:
http://img11.imageshack.us/img11/5844/sshotn.png
If I select the same file more than once, no new button appears (this is correct).
As we can see, on the first file input, only one file has been selected.
On the second one I've chosen two different files, in effect two buttons have been created...
On the third, I've chosen three different files.
The correct behavior should be this:
when a file is chosen, create my_button beside the input field
if my_button exists, delete it and create another one (I need this, beacuse I should connect it to a custom event which will do something with the file name)
My question is: how can I correctly delete the button? Note that the my_button html code does not appear on page source!
Thanks
Pardon me if I'm thinking too simply, but couldn't you just do this?
var button = document.getElementById('Firefox.Now_button_id')
button.parentNode.removeChild(button)
Is this what you were looking for? Feel free to correct me if I misunderstood you.
Solved. I set an ID for each with the following method:
onPageLoad: function(e){
var inputNodes = top.window.content.document.getElementsByTagName("input");
for(var i=0; i<inputNodes.length; i++){
if(inputNodes[i].type=="file")
inputNodes[i].setAttribute("id",i.toString());
}
}
I call this method only on page load:
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", xpitest.onPageLoad, true);
Then I've modified the onFileChosen method in this way:
onFileChosen: function(e) {
var fileInput = e.explicitOriginalTarget;
if(fileInput.type=="file"){
var parentDiv = fileInput.parentNode;
var buttonId = fileInput.id + "Firefox.Now_button_id";
var oldButton = top.window.content.document.getElementById(buttonId);
if(oldButton!=null){
parentDiv.removeChild(oldButton);
this.count--;
}
var newButton = top.window.content.document.createElement("input");
newButton.setAttribute("type", "button");
newButton.setAttribute("id", buttonId);
newButton.setAttribute("value", "my button");
newButton.setAttribute("name", "Firefox.Now_button_name");
parentDiv.insertBefore(newButton, fileInput);
this.count++;
}
}