V
V
venaf342282020-04-17 15:26:40
JavaScript
venaf34228, 2020-04-17 15:26:40

How to change its class and content when clicking on an element, and return it back when clicked again?

Good afternoon!

<span class="badge bg-danger" style="cursor: pointer;">150</span>
<span class="badge bg-danger" style="cursor: pointer;">250</span>
<span class="badge bg-danger" style="cursor: pointer;">350</span>
<span class="badge bg-danger" style="cursor: pointer;">450</span>

How to bind 2 numbers to each span (each element has its own numbers), for example, display 150 by default and 200 when clicking on this element, as well as change the class to badge bg-success, and when you click on the element again, return the class and content default?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lorem Ipsum, 2020-04-17
@venaf34228

As an option))

<span class="badge bg-danger" onclick="changeBadge(150, 200)" style="cursor: pointer;">150</span>
  <span class="badge bg-danger" onclick="changeBadge(250, 255)" style="cursor: pointer;">250</span>
  <span class="badge bg-danger" onclick="changeBadge(350, 235)" style="cursor: pointer;">350</span>
  <span class="badge bg-danger" onclick="changeBadge(450, 225)" style="cursor: pointer;">450</span>
  <script>

    const changeBadge = (oldContent, newContent) => {
      
      const badge = event.target

      if (badge.classList.contains('bg-danger')) {
          badge.classList.add('bg-success')
          badge.classList.remove('bg-danger')
          badge.innerHTML = newContent
      } else {
          badge.classList.remove('bg-success')
          badge.classList.add('bg-danger')
          badge.innerHTML = oldContent
      }
    }
  </script>

E
ettychel, 2020-04-17
@ettychel

for me, this is the most correct option if you use jQuery . It is
most correct to store its state in the data of the element itself and, based on its value, take any actions
. You can play here)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question