// (main.js)
const themechange = document.querySelector('button');
// const text = document.getElementById('text');
themechange.addEventListener('click', () => {
if (document.getElementById('text').style.color == 'black') {
document.getElementById('text').style.color = 'red';
} else if (document.getElementById('text').style.color == 'red') {
document.getElementById('text').style.color = 'blue';
}
})
<head>
<script src="main.js" defer></script>
</head>
<body class="chapter-3">
<h2 id="title"></h2>
<article id="mission">
<p></p>
<p>(#ff0000) -> (#0000ff) -> (#ff0000) -> (#0000ff) </p>
</article>
<div id="container">
<button></button>
<div id="text"></div>
</div>
</body>
I don't know why this code did not working. similar code is working, but I think I missed code or idea of javascript. but I can't find..help
You're original text does not contains a defined color. So both if and else if are ignored.
Here a working example by defining the color first.
const themechange = document.querySelector('button');
const text = document.getElementById('text');
text.style.color = 'black'
themechange.addEventListener('click', () => {
if (document.getElementById('text').style.color == 'black') {
document.getElementById('text').style.color = 'red';
}
else if (document.getElementById('text').style.color == 'red') {
document.getElementById('text').style.color = 'blue';
}
})
<head>
<script src="main.js" defer></script>
</head>
<body class="chapter-3">
<h2 id="title">토글을 구현해보자</h2>
<article id="mission">
<p>JS를 이용해서 색변경 버튼을 누를때마다 버튼 아래에 있는 "안녕" 텍스트의 색이 빨강(#ff0000)와 파랑(#0000ff)로 번갈아가면서 변하도록 만들어주세요</p>
<p>빨강(#ff0000) -> 파랑(#0000ff) -> 빨강(#ff0000) -> 파랑(#0000ff) 의 순서가 되게 해주세요</p>
</article>
<div id="container">
<button>색변경</button>
<div id="text">안녕</div>
</div>
</body>
</html>
On the other hand, you may want to define a default behavior.
For example, the color start with black, then becomes blue but there is no case after that.
As the text color is not set initially you could simply assume that the original color is black. Changing your code to the following changes the initial (unset) color also to red first, on next button click the text-color is updated to blue:
// (main.js)
const themechange = document.querySelector('button');
// const text = document.getElementById('text');
themechange.addEventListener('click', () => {
let textColor = document.getElementById('text').style.color;
console.log({textColor}); //initially gives ''!
if (textColor == 'black' || textColor == '') {
document.getElementById('text').style.color = 'red';
} else if (textColor == 'red') {
document.getElementById('text').style.color = 'blue';
}
});