When I load page, change to green button displays.
When I click on that button, change to purple button displays.
But when I click on the button again (based on innherHTML), expected function(onePurple()) is not triggered, but twoGreen() is triggered.
I am trying to execute code based on innerHTML, but looks like it is not happening.
What am I missing?
Here is the html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<ul class="existing-class">
<li>This is li</li>
</ul>
<button id="MyElement">Change to two column - green</button>
<p>red - default</p>
<p>green - two columns</p>
</body>
</html>
<script src="script.js"></script>
Here is the js
const myButton = document.querySelector("#MyElement");
const oneColumnText = `Change to one column - purple`;
const twoColumnText = `Change to two column - green`;
var myClass = document.querySelector(".existing-class");
function twoGreen() {
console.log("twoGreen function")
myClass.classList.add("two");
myButton.innerHTML = oneColumnText;
}
function onePurple() {
console.log("onePurple function")
myClass.classList.remove("two");
myClass.classList.add("one");
myButton.innerHTML = twoColumnText;
}
// window.onload = function() {
if (myButton.innerHTML === twoColumnText) {
myButton.addEventListener('click', twoGreen, false);
}
if (myButton.innerHTML === oneColumnText) {
myButton.addEventListener('click', onePurple, false);
}
// }
CSS:
.existing-class li {
color: red;
}
.existing-class.two li {
color: green;
}
.existing-class.one li {
color: purple;
}
Here is the jsfillde: https://jsfiddle.net/jsfiddleuser2018/etkjv6x6/
Aucun commentaire:
Enregistrer un commentaire