How do i toggle text on and off?

How do i toggle text on and off?
0

#1

Is there any way i can toggle X inside of these circles with a simple toggle in JS? I tried it multiple times half of a day but couldnt make it work in any way.
HTML:

<div class="wrapper">
       <ul>
            <li><p>X</p></li>
            <li><p>X</p></li>
            <li><p>X</p></li>
            <li><p>X</p></li>
       </ul>
       </div>

CSS:

ul li {
    display: inline-block;
    border: 1px solid black;
    border-radius: 50%;
    height: 150px;
    width: 150px;
    margin-left: 10px;
    margin-right: 10px;
}

p {
    font-size: 50px;
    display: none;
}

.turning {
    display: block;
}

JS:

var li = document.getElementsByTagName("p");
var text = li.innerHTML;
li.addEventListener("click", function() {
    var g = this.classList.toggle("turning");
    text = g;
});

#2

One error I can see is you can’t simply do this. li is multiple nodes and this statement is valid for only one element. I would run a loop to add eventlisteners to each element.


#3

What is the better way to do it but with circles that isnt using unordered list?


#4

HTML

    <li><p>X</p></li>
    <li><p>X</p></li>
    <li><p>X</p></li>
    <li><p>X</p></li>
  </ul>

CSS

ul li {
    display: inline-block;
    border: 1px solid black;
    border-radius: 50%;
    height: 150px;
    width: 150px;
    margin-left: 10px;
    margin-right: 10px;
}

p { 
    text-align: center;
    font-size: 50px;
    visibility: hidden;
}

.turning {
    visibility: visible;
}

JS

const liElems = document.getElementsByTagName("li");
for (let i = 0; i < liElems.length; i++) {
  liElems[i].addEventListener("click", event => {
    event.target.children[0].classList.toggle("turning");
  });
}

#5

However, if you add an id=“circles” to the ul element, you could use the following JavaScript:

circles.addEventListener("click", ({target}) => {
  const change = target.tagName === 'LI'
    ? target.children[0]
    : target
  change.classList.toggle("turning");
});

Also, I would add the following to your CSS so, there is a pointer showing when the mouse is over the li or the p element.

p:hover, li:hover {
  cursor: pointer;
}

#6

What is a difference between const, let and var? And what do arrow => and “event” do?


#7

A quick google search will answer your questions but here are good articles.


#8

I recommend you study the ES6 part of the curriculum which will help you better understand the keywords and syntax used in my code.


#9

Ok, im slowly working on one game im planning out, this right one is my initial step untill the next time. It’ll be worth it. Once im done with some more Udemy i’ll get back to freecodecamp’s curriculum again, i miss it already. Thanks for your answers.


#10

The arrow syntax => is similar to writing:

circles.addEventListener("click", function({target}) {
  const change = target.tagName === 'LI'
    ? target.children[0]
    : target
  change.classList.toggle("turning");
});