简体   繁体   中英

How can I store an html element class or id in a varibale upon clicking on said element using only javascript (no libraries)?

I have three chunks of text: I have / a white / dog.

Upon clicking on each chunk the words are played as audio.

I want to also toggle the class of each chunk so that a transition is applied when I click on the chunk.

Edit: the issue is that the html element I am clicking on does not toggle its class. Nothing happens at all. No error. Nothing.

<body>
  <div class="chunks">
    <div onclick="play1()" class="chunk1"> 
      <span>I have</span>
    </div>
    <div onclick="play2()" class="chunk2">
      <span>a white</span>
    </div>
    <div onclick="play3()" class="chunk3">
      <span>dog.</span>
    </div>
  </div>

  <audio id="audio1" src="sounds/I have.wav"></audio>
  <audio id="audio2" src="sounds/a_white.wav"></audio>
  <audio id="audio3" src="sounds/dog.wav"></audio>

<script>
function play1() {
      document.getElementById('audio1').play();

// The function below is what I've tried to toggle the class of the element I click on

      addEventListener('click', function(e) {
        const box = document.querySelector(e.target);
        box.classList.add('playing'); // playing is the class that will add the transition
      })

    }
</script>

I think is would be easier just changing the class of the parent and then use it to apply some styles to the corresponding children on your stylesheet. Then you just will need to remove the class name (by setting it to '') when the audio stop playing.

Here is how I would do it:

<body>
  <div id="chunks">
    <div data-audio="audio1" class="chunk1">I have</div>
    <div data-audio="audio2" class="chunk2">a white</div>
    <div data-audio="audio3" class="chunk3">dog.</div>
  </div>
  <audio id="audio1" src="sounds/I have.wav"></audio>
  <audio id="audio2" src="sounds/a_white.wav"></audio>
  <audio id="audio3" src="sounds/dog.wav"></audio>

  <script>
    const container = document.getElementById('chunks');

    document.querySelectorAll('#chunks div').forEach(el => {
      el.addEventListener('click', (e) => {
          const clickedElement = e.target;
          const clickedElementClass = clickedElement.className;
          const relatedAudio = clickedElement.dataset.audio;
          container.className = clickedElementClass;
          document.getElementById(relatedAudio).play();
        })
    });
  </script>

  <style>
    .chunk1 .chunk1,
    .chunk2 .chunk2,
    .chunk3 .chunk3 { background: red; }
  </style>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM