0

I'm working on changing the color of some text using a separate .js file. I am a newbie at HTML and JavaScript, please be detailed. Thank you.

This is what I got so far:

htmlfile.html

<html>
<body>
    <p id="demo"> Click the button to change the text in this paragraph. </p>
</body>
</html>

jsfile.js

    var button = document.createElement("button")
    button.innerHTML = "Red or green"
    // Sets or returns the content of an element

    // 2. Append somewhere
    var body = document.getElementsByTagName("body")[0]
    body.appendChild(button)
    // Adds a new child node, to an element, as the last child node

    // 3. Add event handler
    button.addEventListener("click", function () {
        state = !state
        // Attaches an event handler to the specified element

        //var led = document.createElement('LED')
        if (state = 1) {
            document.getElementById("demo").style.color = "red"
        } else {
            document.getElementById("demo").style.color = "green"
        }
        //body.appendChild(led)
    })
}
1

2 Answers 2

1

status = 1;
function switchStyle() {
x = document.getElementById("text");
if(status==1) {
    x.style.color = 'blue';
    status = 2;
}
else if(status==2) {
    x.style.color = 'red';
    status = 1;
}
}
<p id="text">This text color will change.</p><br>
<button type="button" onclick="javascript:switchStyle();">Switch Style</button>

Sign up to request clarification or add additional context in comments.

Comments

0

a couple of advices:

  1. use document.body instead of getElementsByTagName('body')
  2. use semicolons at the end of lines (instructions)
  3. create state var outside addEventListener function
  4. if you compare values in if() condition, use == or === instead =

var button = document.createElement('button');
button.innerHTML = 'Red or green';

document.body.appendChild(button);

var state = 0;

button.addEventListener('click', function (){
   var demo =  document.getElementById("demo");

   if (state === 1) {
     demo.style.color = 'red';
     state = 0;
     } else {
       demo.style.color = 'green';
       state = 1;
    }
});
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.