Onclick "run a function" using external javascript - javascript

I created a simple project in which I click on a button then another button should be created(button 2) and the previous button should be disappeared and this works fine.
But when I click on button 2 then a particular function should be executed. I am stuck here.
It says cannot set property to null.
function myFunction1() {
var x = document.createElement("BUTTON");
var t = document.createTextNode("button 2");
x.setAttribute('id','bt2');
x.appendChild(t);
document.body.appendChild(x);
var a= document.getElementById('bt1');
a.style.display='none';
}
var item = document.getElementById('bt2');
item.onclick = myFunction;
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "lime";
}
<button id= 'bt1' onclick="myFunction1();">
button 1
</button>

You are trying to set the onclick property to an element when it doesn't exist yet in the DOM (it will be created after you click the button 1), so move the final code inside the myFunction1, after the creation of the second button.
function myFunction1() {
var b = document.body;
var x = document.createElement("button");
var t = document.createTextNode("button 2");
x.id = 'bt2';
x.appendChild(t);
b.appendChild(x);
var btt1 = document.getElementById('bt1');
btt1.style.display='none';
var btt2 = document.getElementById('bt2');
btt2.addEventListener('click', function() {
b.style.backgroundColor = "lime";
});
}
<button id= 'bt1' onclick="myFunction1();">
button 1
</button>

Related

onclick excecutes does not work, only when creating DOM

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];

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

Range of variables or sth else? very beginning JS

Sorry for mistakes - my first post. I'd like to click on the 'Try it' button and change the type of the first 'ok' input. After this change I'd like to click the 'Try it' button again and change the type of the element with id="inputt" to INPUT again. I think it's sth wrong with the range of my variable done which tells if i have 2 buttons or input and button.
//JS
window.onload = function Load(){
var done = false;
var foo = document.getElementById('g');
if(!done){
foo.onclick = Change1;
}else{
foo.onclick = Change2;
}
};
function Change1(){
inp = document.getElementById('inputt');
inp.setAttribute('type', 'button');
done = true;
}
function Change2(){
but = document.getElementById('inputt');
but.setAttribute('type','input');
}
//HTML
<input value="ok" id="inputt">
<p>Click the button below to set the type attribute of the button above.</p>
<button id="g">Try it</button>
The window.onload event is not going to get executed again, it only happens once when the window...loads
see if this is what you want.
http://jsfiddle.net/7W4Xw/1/
//JS
window.onload = function Load(){
var foo = document.getElementById('g');
foo.onclick = Change1;
};
function Change1(){
inp = document.getElementById('inputt');
inp.setAttribute('type', 'button');
var foo = document.getElementById('g');
foo.onclick = Change2;
}
function Change2(){
but = document.getElementById('inputt');
but.setAttribute('type','input');
}

Categories

Resources