onclick excecutes does not work, only when creating DOM - javascript

I have the following HTML and javascript.
I can create the buttons without any problem, but the onclick function does not work when clicking the button. It does not do anything.
If I put the method without the ' it excecutes when generating the form, one after the other generating 3 dialogs
function makeUL(array) {
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
var btn = document.createElement("BUTTON");
/*
btn.onClick = function () {
buttonClicked(array[i]);
};*/
var t = document.createTextNode(array[i]); // Create a text node
btn.appendChild(t); // Append the text to <button>
btn.type = "button"
btn.onClick = 'buttonClicked()';
list.appendChild(btn); // Append <button> to <body>
var nextLine = document.createElement("td");
list.appendChild(nextLine);
}
return list;
}
/*
function buttonClicked(buttonName){
alert(buttonName);
}*/
function buttonClicked() {
alert("algo");
}
self.onInit = function() {
var boton = [];
for (var g = 0; g < self.ctx.settings.Botones.length; g++) {
boton[0] = self.ctx.settings.Botones[g].btnId;
boton[1] = self.ctx.settings.Botones[g].method;
boton[2] = self.ctx.settings.Botones[g].params;
document.getElementById('myList').appendChild(makeUL(boton));
}
self.ctx.$scope.sendCommand = function() {
var timeout = self.ctx.settings.requestTimeout;
var rpcMethod = self.ctx.settings.method;
var rpcParams = self.ctx.settings.params;
var commandPromise;
commandPromise = self.ctx.controlApi.sendTwoWayCommand(rpcMethod, rpcParams, timeout);
commandPromise.then(
function success(response) {
//alert("Comando recibido exitosamente\n Respuesta:" + angular.toJson(response));
alert("Comando recibido exitosamente");
},
function fail(rejection) {
alert("ERROR AL ENVIAR COMANDO");
}
);
};
};
<form name="rpcForm">
<md-content class="md-padding" layout="column">
<div id="myList"></div>
</md-content>
</form>

The problem is:
btn.onClick = 'buttonClicked()';
It looks like you were trying to assign to the onclick attribute of the HTML, in which case the proper syntax would be
btn.setAttribute('onclick', 'buttonClicked()');
But since you already have a reference to the element, there's no need to resort to attributes; inline handlers are pretty bad practice anyway. Change to:
btn.onclick = buttonClicked;
(note the lower-case c in onclick), or
btn.addEventListener('click', buttonClicked);
Also, you might consider simply assigning to the button's textContent rather than creating a text node explicitly, it's a bit easier to read and write: change
var t = document.createTextNode(array[i]); // Create a text node
btn.appendChild(t); // Append the text to <button>
to
btn.textContent = array[i];

Related

How can I select a dynamically created button?

I want to select a button from a list item that I created using the previous function in the script. It is showing its class name when I inspect the elements but when I console the element itself it is undefined. How can I select this element so as to attach an event listener to it? Thanks for your help!
var journalListEl = document.querySelector("#journal-list")
var journalTextInputEl = document.querySelector("#journal-text");
var journalEntryImageURLEl = document.querySelector("#journal-image-url")
var journalImage = document.querySelector("#journal-image")
var journalEntrySubmitButton = document.querySelector("#journal-entry-submit-button")
journalEntryImageURLEl.addEventListener("input", displayJournalPhoto)
function displayJournalPhoto() {
var journalEntryImageURL = journalEntryImageURLEl.value
journalImage.setAttribute("src", journalEntryImageURL)
}
journalEntrySubmitButton.addEventListener("click", handleSubmitJournalEntry)
function handleSubmitJournalEntry() {
event.preventDefault()
var journalEntryListItemEl = document.createElement("li")
var journalEntryTextEl = document.createElement("p")
var journalEntryImageEl = document.createElement("img")
var journalEntryUpdateButton = document.createElement("button")
var journalEntryDeleteButton = document.createElement("button")
journalEntryUpdateButton.textContent = "Edit";
journalEntryDeleteButton.textContent = "Delete";
journalEntryListItemEl.classList.add("journal-list-entry")
journalEntryUpdateButton.classList.add("edit-journal-entry")
journalEntryDeleteButton.classList.add("delete-journal-entry")
journalEntryTextEl.innerHTML = journalTextInputEl.value
var journalEntryImageURL = journalEntryImageURLEl.value
journalEntryImageEl.setAttribute("src", journalEntryImageURL)
var newJournalEntryObj = {
journalText: journalEntryTextEl,
journalImage: journalEntryImageEl,
journalImageURL: journalEntryImageURL
}
journalEntryListItemEl.appendChild(newJournalEntryObj.journalText)
journalEntryListItemEl.appendChild(newJournalEntryObj.journalImage)
journalEntryListItemEl.appendChild(journalEntryUpdateButton)
journalEntryListItemEl.appendChild(journalEntryDeleteButton)
journalListEl.appendChild(journalEntryListItemEl)
}
var updateJournalEntryButton = document.querySelector(".journal-list-entry")
updateJournalEntryButton.addEventListener("click", handleUpdateJournalEntry)
function handleUpdateJournalEntry() {
alert("updated journal entry!")
}
Use event delegation on the nearest static ancestor.
For example:
journalListEl.addEventListener('click', e => {
if (e.target.matches('.journal-list-entry')) {
// handle update journal entry
}
});

Remove dynamically created elements by class name Javascript

So, in plain terms I am creating a Chrome Extension that so far can only save links from the internet but not delete them. What I want to add is a "remove" button for deleting unwanted links. So far I haven't got that to work.
The buttons I want to remove are added using JavaScript. Each new block of HTML features a "remove" button but clicking that button does nothing. I have tried binding listeners to each element using a for loop but that doesn't seem to work.
The code runs without errors and I'm certain that the issue is a slight oversight but I have only just started using JavaScript so I'm lost for solutions at the moment.
I have included all the code because I don't want to leave out anything that might be imperative to finding a solution.
It starts with the code for adding a link, followed by removing a single link and then removing all links at once. Thank you all for any help, really want to get this working.
https://github.com/mmmamer/Drop Repository for the rest of the code. Mainly popup.html and popup.css.
var urlList = [];
var i = 0;
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
// event listener for the button inside popup window
document.getElementById('save').addEventListener('click', addLink);
});
function addLink() {
var url = document.getElementById("saveLink").value;
addUrlToListAndSave(url);
addUrlToDom(url);
}
function getUrlListAndRestoreInDom() {
chrome.storage.local.get({
urlList: []
}, function(data) {
urlList = data.urlList;
urlList.forEach(function(url) {
addUrlToDom(url);
});
});
}
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
//removeButton.createElement('button');
removeButton.type = "button";
removeButton.className = "remove";
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink)
newEntry.appendChild(removeButton);
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function addUrlToListAndSave(url) {
urlList.push(url);
saveUrlList();
//}
}
function saveUrlList(callback) {
chrome.storage.local.set({
urlList
}, function() {
if (typeof callback === 'function') {
//If there was no callback provided, don't try to call it.
callback();
}
});
}
// remove a single bookmark item
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
var allButtons = document.getElementsByClassName('remove');
function listenI(i) {
allButtons[i].addEventListener('click', () => removeMe(i));
}
for (var i = 0; i < allButtons.length; i++) {
listenI(i);
}
});
function removeMe(i) {
var fullList = documents.getElementsByClassName('listItem');
listItem[i].parentNode.removeChild(listItem[i]);
}
//remove all button
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("remove-all").addEventListener('click', function() {
var removeList = document.getElementsByClassName("listItem");
while(removeList[0]) {
removeList[0].parentNode.removeChild(removeList[0]);
}
})
});
chrome.storage.local.get() is asynchronous. So when you try to add the event listeners to the Remove buttons, they're not in the DOM yet.
You can add the listener in the addUrlToDom() function instead. That way you'll also add the event listener when you create new buttons.
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
//removeButton.createElement('button');
removeButton.type = "button";
removeButton.className = "remove";
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink)
newEntry.appendChild(removeButton);
removeButton.addEventListener("click", function() {
var anchor = this.previousElementSibling;
var url = anchor.getAttribute("href");
removeUrlAndSave(url);
this.parentNode.remove();
});
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function removeUrlAndSave(url) {
var index = urlList.indexOf(url);
if (index != -1) {
urlList.splice(index, 1);
saveUrlList();
}
}

Javascript button toggle

I am trying to write a javascript function so that when a button is clicked, all HTML paragraph elements "p" will be highlighted yellow, the HTML buttons text will then change to "Click to unhighlight" (the code below before the else statement is fully functional, all paragraphs are highlighted and the buttons text changes). I am trying to reload the page using "location.reload();" but it doesn't seem to work.
window.onload = function() {
var button = document.getElementsByTagName("button");
button[0].onclick = changeBackground;
}
function changeBackground() {
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var firstClick = true;
var b = document.getElementById("button");
if (firstClick) {
b.innerHTML = "Click to unhighlight";
firstClick = false;
} else {
location.reload();
firstClick = true;
}
}
Any advice on how to properly call the "location.reload();" function would be much appreciated. Thanks in advance.
Your main issue is that you have:
var firstClick = true;
inside the click event handler so every time the button is clicked, it thinks it's the first click. You'd need to have that set outside of the event handler and inside, you'd want to toggle it to the opposite of its current value:
var firstClick = true;
function changeBackground() {
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var b = document.getElementById("button");
if (firstClick) {
b.textContent = "Click to unhighlight";
} else {
location.reload();
}
firstClick = !firstClick; // Toggle the first click variable
}
But, really instead of reloading the document, just un-highlight the paragraphs. Reloading takes more resources.
Avoid using getElementsByTagName() as it returns a "live node list", which has performance implications.
Also, rather than set up an explicit onload event handler, just position your code at the bottom of the HTML body.
Lastly, use modern standards for event handling (.addEventListener), rather than event properties (onclick).
See comments inline below:
// Place all this code inside of a `<script>` element and place that
// element at the bottom of the code, just before the closing body tag.
let btn = document.querySelector("button");
// Modern, standards-based way to set up event handlers
btn.addEventListener("click", changeBackground);
function changeBackground() {
// Use .querySelectorAll() and convert the results to an array
var myParas = Array.prototype.slice.call(document.querySelectorAll("p"));
// Loop over all the paragraphs
myParas.forEach(function(par){
// Toggle the CSS class to highlight/or unhighlight them
par.classList.toggle("highlight");
});
// Set the button text accordingly
btn.textContent = myParas[0].classList.contains("highlight") ? "Click to unhighlight" : "Click to highlight";
}
.highlight { background-color:yellow; }
<p>This is a test</p>
<h1>This is a test</h1>
<p>This is a test</p>
<p>This is a test</p>
<div>This is a test</div>
<p>This is a test</p>
<p>This is a test</p>
<button>Click to highlight</button>
the problem is that the else sentence never be call, because the "firstClick" variable always will be true each time you call the changeBackGround method you're setting the variable to true.
to avoid this, just declare the variable out of the method, example:
var firstClick=true;
function changeBackground(){
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var b = document.getElementById("button");
if (firstClick){
b.innerHTML = "Click to unhighlight";
firstClick = false;
}else{
location.reload();
firstClick = true;
}
}
A different approach is to use switch case.
<button id="changeButton">Make my paragraphs Yellow</button>
<script>
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementsByTagName("p");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'yellow'; }
theToggle.textContent = "Make my paragraphs White";
break;
case "off":
toggleMe.toggleStatus="on";
for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'white'; }
theToggle.textContent = "Make my paragraphs Yellow";
break;
}
}
</script>
Hope that solve it.

JS: after creating new element and assigning it to a variable, it gives me null

Despite the code is working, i just want to understand why it gives me this error.
After clicking the buttons, when i try to call the variable "home", the console tells me it's "null". Why?
var menu = document.getElementById("menu");
var botoes = document.getElementsByTagName("button");
var home = document.getElementById("home");
for(var i = 0; i < botoes.length; i++) {
botoes[i].addEventListener("click", function() {
shrink();
if(botoes[3]) {
} else {
createButton();
}
});
}
function shrink() {
menu.style.margin = "10px";
menu.style.width = "140px";
}
function createButton() {
var newButton = document.createElement("button"); //creates button element
var newButtonText = document.createTextNode("home"); //creates a text node
newButton.appendChild(newButtonText); //appends the text to button
var insertButton = menu.appendChild(newButton); //append button to body
insertButton.className = "botoes"; //adds class to button
newButton.id = "home"; //adiciona um id ao botao recentemente criado
}
you did
var home = document.getElementById("home");
but if the document wasn't loaded yet, the home variable would equate to null as there would be no home element
I think the most relevant thing to take away is to add:
home = newButton
which actually switches the variables
If the home button already exists, wrap your logic in a onload function:
window.addEventListener('load', function() {
var menu = document.getElementById("menu");
var botoes = document.getElementsByTagName("button");
var home = document.getElementById("home");
for(var i = 0; i < botoes.length; i++) {
botoes[i].addEventListener("click", function() {
shrink();
if(botoes[3]) {
} else {
createButton();
}
});
}
function shrink() {
menu.style.margin = "10px";
menu.style.width = "140px";
}
function createButton() {
var newButton = document.createElement("button"); //creates button element
var newButtonText = document.createTextNode("home"); //creates a text node
newButton.appendChild(newButtonText); //appends the text to button
var insertButton = menu.appendChild(newButton); //append button to body
insertButton.className = "botoes"; //adds class to button
newButton.id = "home"; //adiciona um id ao botao recentemente criado
// change buttons
home = newButton;
}
});
then at the end set home to the new button
In case the button isnt created yet, when you manupulate it check it exists:
if (home) {
// continue
}
Javascript is executed in order it is written.
Meaning the moment your javascript loads it will execute:
var home = document.getElementById("home");
At that point the element with the home id isn't created yet.
Resulting in the home variable being null.
Later on when you call it again it hasn't been changed yet, therefor returning you null.
If you would call document.getElementById("home") in your console it would however return your created element.
After your comment:
I think you misunderstand how your Javascript is called.
You do not reference the document.getElementById("home") function to the home variable, what you do is get the value returned by the function and keep that in your variable. Which at that point happens to be null.

Why does this javascript function activate at the wrong time?

Here's the code I'm currently using
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function submitButton() {
var btn = document.createElement('Button');
document.body.appendChild(btn);
btn.onClick = testFunction_2();
}
function testFunction_2() {
alert("foo");
}
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
As you can see, if childrenResponse (the user's response to a previous query) is equal to 1, both functions are activated. The attempted goal is to create a text node, an input, and a button. The button as of right now, should active testFunction2() which alerts us that it is working. But, testFunction2() activates before the text node or input even shows up. I can find the reason for this, and if anyone can help me out I'd greatly appreciate it. Thank you.
Also, on a side note, how can I add text to the button created in submitButton() ? Thanks!
You have called the testFunction_2, instead of assigning it. This should work out fine.
function submitButton() {
var btn = document.createElement('Button');
btn.onclick = testFunction_2;
document.body.appendChild(btn);
}
You are calling the function testFunction_2() in onClick. You need to add event listener to button as shown below
btn.addEventListener('click', testFunction_2);
To add text to button use
var txt = document.createTextNode("CLICK ME");
btn.appendChild(txt);
Check the snippet below
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function submitButton() {
var btn = document.createElement('Button');
var txt = document.createTextNode("CLICK ME");
btn.appendChild(txt);
document.body.appendChild(btn);
btn.addEventListener('click', testFunction_2);
}
function testFunction_2() {
alert("foo");
}
childrenResponse = 1;
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
You are calling the function testFunction_2 in onClick. You need to provide reference.
That also won't work. You need to add event listener to button.
And for setting the text, just set innerHTML of button.
var btn = document.createElement('Button');
btn.innerHTML = "click";
btn.addEventListener('click', testFunction_2);
document.body.appendChild(btn);
btn.onclick = testFunction_2; // in place of addEventListener.
// if you want to use onclick. use small case 'c' in onclick.
There were 2 problems:
onClick should've been onclick.
You were executing the function and assigning the result of that function to the onclick. btn.onClick = testFunction_2(); should be btn.onClick = testFunction_2;
See working snippet below.
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function testFunction_2() {
alert("foo");
}
function submitButton() {
var btn = document.createElement('button');
btn.innerHTML = "Some button name";
btn.onclick = testFunction_2;
document.body.appendChild(btn);
}
var childrenResponse = 1;
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
In javascript you can use the innerHTML set the button's HTML contents.
See Setting button text via javascript
btn.innerHTML = "This is a button name";
The Mozilla Developer Network is a good resource. Here's two links for the above mentioned snippets.
MDN innerHTML
MDN HTML Button element

Categories

Resources