EN VI

Javascript - Add an event listener to the first button that changes the text within the <h1> to EITHER uppercase or all lowercase?

2024-03-12 09:00:05
How to Javascript - Add an event listener to the first button that changes the text within the

to EITHER uppercase or all lowercase

Hello code friends I have an assignment, new to this

Add an event listener to the first button that changes the text within the to EITHER all uppercase or all lowercase, depending on current state.

I need to change all paragraph under h1 to lowercase or uppercase, at the click of a button.

in HTML I made an id to p.

I made a button with an id

in JS I used getElementById to bring my button and paragraph.

const textChange = document.getElementById("btnChange1"); console.log(textChange);

const txtChange = document.getElementById("myP");

textChange.addEventListener("click", () => {

} });

that's as far as I can get, thanks in advance!

Solution:

So first off, you'll want a variable, isUpperCase, that will remember if the text is uppercase or lowercase. This variable will change with each click of the button so it cannot be declared as a const.

After this, you just need a simple if else statement within the event listener. This if else statement will check the value of isUpperCase and then will change the text to either upper or lower case depending on its state:

const textButton = document.getElementById("textButton");
const myP = document.getElementById("myP");
let isUpperCase = false;

textButton.addEventListener("click", function() {
    if (isUpperCase) {
        myP.textContent = myP.textContent.toLowerCase();
        isUpperCase = false;
    } else {
        myP.textContent = myP.textContent.toUppperCase();
        isUpperCase = true;
    }
 });
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login