Javascript, have links all auto open in new tabs - javascript

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.

Related

javascript pass media EventListener to html (html5) media.currentTime

*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 need to keep element reference to pass on

When the user clicks on <a> tag it calls a function like the following:
<a href="#" onclick="func1(this)">;
This function generates HTML for a modal that needs to reference the first button.
func1(elem) {
html='<div class="modaldiv">' +
'<a href="#" onclick="func2(e.srcElement)">'+
'</div>';
}
When the link inside the modal is clicked, func2() should save text into a data attribute inside the first link, but this is not working, returning:
"Uncaught SyntaxError: Unexpected identifier "
First, don't use inline HTML event handling attributes (onclick, onmouseover, etc.), here's why.
But, your actual problem is that you are not properly declaring your function.
This: func1(elem)
Needs to be this: function func1(elem)
Next, you <a> elements must have some content for someone to see and click on and they must then be closed, which you didn't have.
function func1(elem) {
html='<div class="modaldiv">' + 'click me too'+ '</div>';
document.body.innerHTML += html;
}
click me
If you rework your answer to use modern standards, the proper modern way to do this would be:
// Get references to DOM elements
var a1 = document.getElementById("firstAnchor");
a1.addEventListener("click", func1);
// Callback for first link:
function func1(e) {
// Store original source element
var src = e.srcElement;
// Formally create new elements and configure them
var d = document.createElement("div");
d.classList.add("modaldiv");
var a = document.createElement("a");
a.href = "#";
a.textContent = "Click me too!";
// By hooking up to a wrapper function, we can have that function
// pass arguments to the actual callback function:
a.addEventListener("click", function(){
func2(src);
});
// Add new elements to the document
d.appendChild(a);
document.body.appendChild(d);
}
function func2(firstSrc){
console.log("func2 invoked and e.srcElement from first link is: ", firstSrc);
}
click me

How to get input values from html to text file

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.

Google Apps Script - Move Cursor onclick

I would like to implement a Table of Contents in the sidebar of a Google Docs document which will take you to the appropriate sections when clicked. I am generating the HTML for the sidebar element by element, and I see that there is a moveCursor(position) function in Document class, but I can't see how to actually call it using onclick. Not the full code but shows the problem:
function generateHtml() {
var html = HtmlService.createHtmlOutput('<html><body>');
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
//Iterate each document element
var totalElements = body.getNumChildren();
for(var i = 0; i < totalElements; ++i) {
var element = body.getChild(i);
if(element.getType() == DocumentApp.ElementType.PARAGRAPH) {
var text = paragraph.getText();
if(text.trim()) { //Not blank paragraph
var position = document.newPosition(element, 0);
/**Would like to have <a onclick=document.moveCursor(position)> here**/
//Show first 20 chars as preview in table of contents
html.append('Detected paragraph ')
.append(text.substring(0, 20))
.append('<br />');
}
}
}
html.append('</body></html>');
return html;
}
How can I accomplish this in Apps Script? The code can be completely restructured as needed.
This line:
/**Would like to have <a onclick=document.moveCursor(position)> here**/
Change to:
<div onmouseup="myClientFunction()">Text Here</div>
Add a <script> tag to your HTML:
<script>
var valueToSend = code to get value;
window.myClientFunction = function() {
google.script.run
.myGsFunctionToMoveCursor(valueToSend);
};
</script>
Then you need a myGsFunctionToMoveCursor() function in a script file (.gs extension)
function myGsFunctionToMoveCursor(valueReceived) {
//To Do - Write code to move cursor in Google Doc
. . . Code to move cursor
};

Element onclick event does not show data

I have the following script to create some hyperlinks which are numbers stored in an array. I want to be able to click those numbers and get the particular number to be shown in the alert box. I am able to see the links but when I click them I don't see any data.
<html>
<body>
<script type="text/javascript">
var str="732176086,732176085,735219154,735219155,23948614,23948629,23948628,764488973,764488974,764488975,23948631,732164301,732164304,732164305,732164303,732164302,732168040,832567989,832567988,807573121,807573120,765867299,831150154,831150153,23951065,23952295";
var str_array=str.split(',');
for(var i=0;i<str_array.length;i++)
{
controlRef = document.createElement('a');
var newLine=document.createElement('br');
document.body.appendChild(newLine);
controlRef.href = '#';
controlRef.innerHTML = str_array[i];
document.body.appendChild(controlRef);
}
controlRef.onclick = function () { alert(controlRef.innerHTML); };
</script>
</body>
</html>
Place the click handler inside of the for loop.
You also need to break the closure to controlRef. Otherwise the controlRef will point to the last element.
controlRef.onclick = (function(element) {
return function() {
alert(element.innerHTML);
};
})(controlRef);
jsFiddle.

Categories

Resources