Javascript button toggle - javascript

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.

Related

Onclick "run a function" using external 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>

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

How to make a toggle function

I’m somewhat new to JavaScript and I made a function that changes text when clicked but how can I make the text change back if you click it again? I would include a screenshot but I don’t have sufficient reputation.
Simple. Just use a toggle variable.
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
var toggle = 0;
function myFunction() {
var el = document.getElementById("demo");
if(toggle == 0){
el.innerHTML = "ZERO";
toggle = 1;
}
else{
el.innerHTML = "ONE";
toggle = 0;
}
}
</script>
Run it Here
the most basic and simplest way is to use three variables-
programming in scala in fun
<script type="text/javascript">
var $elem = $('#para');
var text1 = $elem.text();
var text2 = 'Rust is trending language of 2017';
var toggled = false;
$elem.on('click', function()) {
if(!toggled) {
$elem.text(text2);
toggled = true;
}
else {
$elem.text(text1)
toggled = false;
}
});
</script>

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

javascript addEventListener in for loops uses last variable for event

here's my code
<body>
<div id = "elementbox">
</div>
<script>
var container = document.getElementById("elementbox");
function item_select() {
alert("e");
var selected_element = document.getElementsByClassName("on");
selected_element.className = "off";
alert(selected_element);
}
for (var i = 0; i < 20; i++) {
dive = document.createElement("div");
dive.id = i+1;
dive.className = "off";
if (dive.id === 8) { dive.className = "on"}
dive.innerHTML = "<p>E</p>;
(function(i) {
dive.addEventListener("click", function(i) {
document.getElementById(i).className = "on";
item_select();
}, true)
})(i);
container.appendChild(dive);
}
</script>
</body>
</html>
As you can see my addEventListener uses the incremented variable (i) to change the className of a specific div, so when the event is called i is equal to 20.
how can I avoid this ?
No, I don't believe that is what is going on. You already have immediate-invocation to close the value of i.
I think the problem is that i is the event object:
(function(i) {
dive.addEventListener("click", function(i) {
^-- i should not be here
document.getElementById(i).className = "on";
item_select();
}, true)
})(i);
It seems your click handler sets the class on to the next <div>. Consider using dive.nextSibling. This avoids the need to use id and i. It's possible that more complex behaviour is required so maybe having the id is useful.

Categories

Resources