How to change this <a> link into a button? - javascript

In the following code there is a link:
<textarea placeholder="input" id="input"></textarea><br>
<input type="text" placeholder="file name" id="filename"/><br>
Export
<script>
var container = document.getElementById('input');
var anchor = document.getElementById('export');
anchor.onclick = function() {
anchor.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(container.value);
anchor.download = document.getElementById('filename').value;
};
</script>
How can I change the Export link into a button with the same id and fuction?

var hello = () => { // this is equal to write " var hello = function() { " and to write " function hello() { "
alert('hello')
}
.link {padding: 10px; color: white; background: #00ced1; text-decoration: none; border-radius: 5%}
.link:hover {opacity: 0.8}
<a class="link" href="#" onclick="hello()">Hello</a>
u can do something like this, (this is very simple, just an example)
however this is a very basic thing, please, first of posting a question consider reading the documentation

Change your anchor tag to a button.
<button id="export">Export</button>
Now, inside the onclick handler, create a anchor with the desired attributes, and invoke the click method on it. This way you gonna activate an anchor click when you click the button.
<script>
var container = document.getElementById('input');
var button = document.getElementById('export');
button.onclick = function() {
var anchor = document.createElement('a');
anchor.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(container.value);
anchor.download = document.getElementById('filename').value;
anchor.click();
};
</script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<textarea placeholder="input" id="input"></textarea><br>
<input type="text" placeholder="file name" id="filename"/><br>
Export
<script>
var container = document.getElementById('input');
var anchor = document.getElementById('export');
anchor.onclick = function() {
anchor.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(container.value);
anchor.download = document.getElementById('filename').value;
};
</script>

Related

Combine userinput and predefined phrase into url (to write into dom)

I want to combine userinput from a textfield with a preset url,
to then form a new url that is to be written into the dom below after pressing a button
My current code looks like this:
<body>
<form>
<input type="text" id="pixivurl" value="4165980"/>
<input type="button" id="btn" value="pixivuserid"/>
</form>
<html>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('pixivurl').value,
src = ' val,
var link = document.getElementById("link");
var a = document.createElement('a');
var linkText = document.createTextNode("pixivuser");
a.appendChild(linkText);
a.title = "pixivuser";
a.href = "https://rsshub.app/pixiv/user/" + pixivuser";
document.body.appendChild(a);
}
</script>
</body>
</html>
The base url here is: https://rsshub.app/pixiv/user/
and it is supposed to have a numeral added right after, defined by userinpu.
(the default result in this case is https://rsshub.app/pixiv/user/4165980 )
I can't quite figure out the part to combine and then write into the dom below,
something might be missing ?
You just have some typing mistakes and then your code will work. The input with the id pixivurl has the user id. And you are getting it and assigning it to the href property of the link element. If you want the url to be also the text of the link element then put it in the textNode you have created.
<form>
<input type="text" id="pixivurl" value="4165980"/>
<input type="button" id="btn" value="pixivuserid"/>
</form>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('pixivurl').value;
var url = "https://rsshub.app/pixiv/user/" + val;
var a = document.createElement('a');
var linkText = document.createTextNode(url);
a.appendChild(linkText);
a.title = "pixivuser";
a.href = url;
a.style.display = 'block';
document.body.appendChild(a);
}
</script>

Using javascript to add an image to a list and then deleting that list item when the image is clicked

Firstly I know I can make things a lot easier by creating the ul in HTML. I'm not supposed to be doing that.
My HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body id="body">
<form id="form" >
<input id="userInput" placeholder="Enter your list item here">
<button type="button" onclick="inputFunction()">Add</button>
</form>
<script src="A4.js"></script>
</body>
</html>
My Javascript so far:
// Creating Array
var listData = ["Crab","Lobster","Scallops"];
// Creating initial List
function listFunction(){
var ul = document.createElement("ul");
ul.id = 'ulId';
document.getElementById('body').appendChild(ul);
listData.forEach(liFunction);
function liFunction(element){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML+=element;
}
}
listFunction();
// Adding user input to the list
function inputFunction() {
var input = document.getElementById("userInput").value;
listData.push(input);
var newLi = document.createElement("li");
document.getElementById('ulId').appendChild(newLi);
newLi.innerHTML=input;
}
var liImg = document.getElementsByTagName('li');
for (var i = 0; i < liImg.length; i++) {
liImg[i].addEventListener('mouseover', handlerFunction, false);
}
function handlerFunction(e) {
var img = document.createElement("img");
img.setAttribute("src","https://cdn1.iconfinder.com/data/icons/nuove/128x128/actions/fileclose.png");
img.setAttribute("height","10");
img.setAttribute("width", "10");
document.getElementsByTagName('li').innerHTML += "img";
}
So what I'm supposed to be doing is first create a list using the listData array, and displaying it on the page. Then I take the user input and add it to the list. This part is working fine
The part I am stuck on is having to create/display an image next to each list item when it is mouseover'ed. Then having to delete that specific list item if the image is clicked. I've created the eventListener, but the img part doesn't seem to be working.
The problem is when you're appending the image to the li element.
Solution:
e.target.appendChild(img);
// Creating Array
var listData = ["Crab", "Lobster", "Scallops"];
// Creating initial List
function listFunction() {
var ul = document.createElement("ul");
ul.id = 'ulId';
document.getElementById('body').appendChild(ul);
listData.forEach(liFunction);
function liFunction(element) {
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += element;
}
}
listFunction();
// Adding user input to the list
function inputFunction() {
var input = document.getElementById("userInput").value;
listData.push(input);
var newLi = document.createElement("li");
document.getElementById('ulId').appendChild(newLi);
newLi.innerHTML = input;
}
var liImg = document.getElementsByTagName('li');
for (var i = 0; i < liImg.length; i++) {
liImg[i].addEventListener('mouseover', handlerFunction);
}
function handlerFunction(e) {
var img = document.createElement("img");
img.setAttribute("src", "https://cdn1.iconfinder.com/data/icons/nuove/128x128/actions/fileclose.png");
img.setAttribute("height", "10");
img.setAttribute("width", "10");
e.target.appendChild(img);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body id="body">
<form id="form">
<input id="userInput" placeholder="Enter your list item here">
<button type="button" onclick="inputFunction()">Add</button>
</form>
<script src="A4.js"></script>
</body>
</html>
Hope this helps!
img is not string, it is a variable, so remove the surrounding double quotes from that. Since img is a node element, instead of using innerHTML you should use appendChild(). You also should use the e.target to refer the specific li element:
Change:
document.getElementsByTagName('li').innerHTML += "img";
To
e.target.appendChild(img);
I will suggest you to use mouseenter instead of mousemove. I think you need to attach the mouseleave event as well. You also have to attach the events to the newly created li elements.
Try the following way:
// Creating Array
var listData = ["Crab","Lobster","Scallops"];
// Creating initial List
function listFunction(){
var ul = document.createElement("ul");
ul.id = 'ulId';
document.getElementById('body').appendChild(ul);
listData.forEach(liFunction);
function liFunction(element){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML+=element;
}
}
listFunction();
// Adding user input to the list
function inputFunction() {
var input = document.getElementById("userInput").value;
listData.push(input);
var newLi = document.createElement("li");
newLi.addEventListener('mouseenter', handlerFunction, false);
newLi.addEventListener('mouseleave', removeImage, false);
document.getElementById('ulId').appendChild(newLi);
newLi.insertAdjacentHTML('beforeend', input);
}
var liImg = document.getElementsByTagName('li');
for (let i = 0; i < liImg.length; i++) {
liImg[i].addEventListener('mouseenter', handlerFunction, false);
liImg[i].addEventListener('mouseleave', removeImage, false);
}
function handlerFunction(e) {
var img = document.createElement("img");
img.setAttribute("src","https://cdn1.iconfinder.com/data/icons/nuove/128x128/actions/fileclose.png");
img.setAttribute("height","30");
img.setAttribute("width", "30");
img.addEventListener('click', function(){
this.closest('li').remove();
});
e.target.appendChild(img);
}
function removeImage(e){
e.target.querySelector('img').remove();
}
<body id="body">
<form id="form" >
<input id="userInput" placeholder="Enter your list item here">
<button type="button" onclick="inputFunction()">Add</button>
</form>
<script src="A4.js"></script>
</body>

How to get javascript `this` element properties?

I have been learning javascript to get clear of the jquery that's why I'm gonna show you an example with jquery and how to write same code with js
I have to do list like this:
var addText = document.querySelector("#addText"),
addButton = document.querySelector("#addButton");
addText.addEventListener("keyup", function() {
if (addText.value.trim().length > 0) {
addButton.removeAttribute("disabled", false)
} else {
addButton.setAttribute("disabled", true);
}
});
var ul = document.createElement("ul");
addButton.addEventListener("click", function() {
var textVal = addText.value;
var li = document.createElement("li");
li.innerHTML = textVal + " - <span class='removeTodo' onclick='removeTodo()'>Remove</span>";
ul.appendChild(li);
addText.value = '';
addText.focus();
addButton.setAttribute("disabled", true);
});
document.body.appendChild(ul);
function removeTodo(event) {
//
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" name="" id="addText">
<input type="button" value="Add" id="addButton" disabled>
</body>
</html>
and as you see on snippet I have removeTodo() function.. I want to remove li which I clicked but before do this I have to ask how can I get clicked properties (id,class,text,parent,child bla bla) and how can I remove or addClass (for example) ?
it was very simple with jquery like this
$(element).on("click", function() {
$(this).attr("id");
$(this).text();
$(this).remove();
$(this).hide();
$(this).parents().attr("class");
})
With the method you're using - where you expect the event to be passed as an argument to the function - you can use event.target to access the clicked element. Note that you will need to amend the onclick to include the event in the arguments, though.
However, a much better solution would be to use an unobtrusive event handler on the li as you are on all the other elements in your code. Then you can use the this keyword to reference the clicked element, similar to the jQuery example in your second code block. Try this:
var addText = document.querySelector("#addText"),
addButton = document.querySelector("#addButton");
addText.addEventListener("keyup", function() {
addButton.disabled = addText.value.trim().length == 0;
});
addButton.addEventListener("click", function() {
var textVal = addText.value;
var li = document.createElement("li");
li.innerHTML = textVal + ' - <span class="removeTodo">Remove</span>';
li.addEventListener('click', removeTodo);
ul.appendChild(li);
addText.value = '';
addText.focus();
addButton.setAttribute("disabled", true);
});
var ul = document.createElement("ul");
document.body.appendChild(ul);
function removeTodo() {
// read properties here...
console.log(this.innerHTML);
// then remove the element...
this.remove();
}
<input type="text" name="" id="addText">
<input type="button" value="Add" id="addButton" disabled>
Your event object is going to have an event.target field that will hold the DOM object you are looking for.
innerHTML is not the best practice. You should for example add another element for span, addEventListner on it and append span to your li.
var addText = document.querySelector("#addText"),
addButton = document.querySelector("#addButton");
addText.addEventListener("keyup", function() {
if (addText.value.trim().length > 0) {
addButton.removeAttribute("disabled", false)
} else {
addButton.setAttribute("disabled", true);
}
});
var ul = document.createElement("ul");
addButton.addEventListener("click", function() {
var textVal = addText.value;
var li = document.createElement("li");
li.innerText = textVal + ' - ';
var span = document.createElement("span");
span.innerText = 'Remove';
span.className = 'removeTodo'
li.appendChild(span)
ul.appendChild(li);
span.addEventListener('click', removeTodo);
addText.value = '';
addText.focus();
addButton.setAttribute("disabled", true);
});
document.body.appendChild(ul);
function removeTodo(event) {
console.log (event.target) // this is a span
console.log (event.target.parentElement) // this is a li
event.target.parentElement.remove(); // remove li
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" name="" id="addText">
<input type="button" value="Add" id="addButton" disabled>
</body>
</html>

Dynamic HTML page not using css

I'm trying to dynamically set the content of a popup.
Here is a first HTML page where everything is defined statically :
<html>
<head>
<meta charset='utf-8'>
<link href='css/font-awesome.css' rel='stylesheet'>
<link href='css/myStyle.css' rel='stylesheet'>
</head>
<body>
<div id="data">
<ul class='links-list'>
<li><a target='_blank' href='siteURL'><i class='myButton'>TEXT</i></a></li>
<li><a target='_blank' href='twitterURL'><i class='myButton'>TEXT</i></a></li>
</ul>
</div>
</body>
</html>
Now I need to dynamically set my buttons, so I've removed everything which will be dynamically created :
<html>
<head>
<meta charset='utf-8'>
<link href='css/font-awesome.css' rel='stylesheet'>
<link href='css/myStyle.css' rel='stylesheet'>
</head>
<body>
<div id="data">
</div>
<script type="text/javascript" src="script.js">
</script>
</body>
</html>
My content script "script.js" receive data (array of links) and have to create buttons in my HTML document :
self.port.on("liste", function(list)
{
var div = document.getElementById('data'); // Get <div id="data">
var ul = document.createElement('ul'); // Create <ul class='links-list'>
ul.class = 'links-list';
for (var i = 0; i < list.links.length; ++i)
{
var site = list.links[i];
var li = document.createElement('li'); // Create <li>
var link = document.createElement('a'); // Create <a>
var button = document.createElement('i'); // Create <i>
button.class = "myButton";
link.text = site.text;
link.href = site.url;
link.target = '_blank';
link.appendChild(button);
li.appendChild(link);
ul.appendChild(li);
}
div.appendChild(ul);
});
Issue is links created dynamically aren't using "myStyle.css", here is a comparaison :
Static vs dynamic load :
Could anyone help me resolving this? Thank you.
The correct way to give an item a class using javascript is - unintuitively enough - className, or setAttribute. So either of these will add the correct class:
button.className = 'myButton'
button.setAttribute('class', 'myButton')
Using just .class does not work in Javascript:
document.getElementById('a1').class = 'aClass';
document.getElementById('a2').className = 'aClass';
document.getElementById('a3').setAttribute('class', 'aClass');
.aClass { color: red; }
<pre id="a1">.class</pre>
<pre id="a2">.className</pre>
<pre id="a3">.setAttribute</pre>
Looks to me like the comment from CBroe is the answer. In your javascript you're putting the text into the link instead of your button. That means that the button will essentially be invisible. That's why it looks different from your hard-coded example. Try this javascript instead.
var div = document.getElementById('data'); // Get <div id="data">
var ul = document.createElement('ul'); // Create <ul class='links-list'>
ul.className = 'links-list';
for (var i = 0; i < 4; ++i){
var url = i;
var li = document.createElement('li'); // Create <li>
var link = document.createElement('a'); // Create <a>
var button = document.createElement('i'); // Create <i>
button.className = "myButton";
button.innerHTML = 'text'+i;
link.text = "ab ";
link.href = url;
link.target = '_blank';
link.appendChild(button);
li.appendChild(link);
ul.appendChild(li);
}
div.appendChild(ul);

document.getElementById returns null on a dynaimcally created div

Something weird is happening here.
My website is using javascript to create dynamic divs, but although they are entered into the DOM (at least this is what I think), javascript returns null when calling that div.
This is the javscript code which is loaded before </body>
function AddPlayer(){
var name = document.getElementById('name').value;
createBox(name);
};
function createBox(name){
var span = document.createElement('span');
span.id = name;
span.innerHTML = name;
document.getElementById("gameArea").appendChild(span);
var span = document.createElement('span');
span.id = "score-" + name;
span.innerHTML = "0";
document.getElementById("gameArea").appendChild(span);
var inputSText = document.createElement('input');
inputSText.type = "button";
inputSText.value = "Add Points";
inputSText.onclick = function(){AddPoints(name);};
document.getElementById("gameArea").appendChild(inputSText);
};
function AddPoints(player){
document.load(document.getElementById("#score-"+ player).innerHTML = "Please work");
};
<html>
<head>
<title>Game Score Keeper</title>
</head>
<body>
<h2>Game Score Keeper</h2>
<input type="text" id="name" />
<input type="button" value="Add Player" onclick="AddPlayer()" />
<div id="gameArea">
</div>
<script src="index.js"></script>
</body>
</html>
Here is the jsfiddle of this project http://jsfiddle.net/jwmm6rk7/
You need to pass the id of the element to document.getElementById. That is, without the hash (#) symbol.
function AddPoints(player) {
document.load(document.getElementById("score-" + player).innerHTML = "HELLO");
};
lookslike you were jQuery user, you used # and name instead of player
function AddPoints(player) {
document.getElementById("score-" + player).innerHTML = "HELLO";
};

Categories

Resources