Home > database >  How can I control CSS with a button in JS
How can I control CSS with a button in JS

Time:01-23

I Can not find the right code for the JS to control CSS. Upon opening link I need the "transform" to be off , and then turn on and toggle back and forth "transform" with the button. It started as an on/off mute button needing no css , so my paths ?

The buttons ( play/pause/etc)are in a div . Their function are in JS and all work, except, I need this one to reach into CSS but can't find my brain. A delete of the CSS and it opens and runs everything else and runs the way I would like. Thanks.

    <button onclick="transform()">mirror</button> 

    #myplayer {
  
      transform: rotateY(180deg);
    }
  
 var player = document.getElementById("myplayer");

    function transform() { 
        if (player.transform)
            player.transform = false
        else
            player.transform = true
    }
        

CodePudding user response:

Get the button element, add a click event handler to it, within the handler once the button is clicked, grab the video element then use .classList.toggle('class-name') to toggle a class.

document.getElementById("transformPlayer").addEventListener("click", function() {
  document.getElementById("player").classList.toggle('transform180')
});
.transform180 {
  transform: rotateY(180deg);
}
<button id="transformPlayer">mirror</button>


<video id="player" controls width="250">
    <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
            type="video/webm">
    <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
            type="video/mp4">
</video>

CodePudding user response:

Use a class

const player = document.querySelector('#myplayer')
const button = document.querySelector('button')

button.addEventListener('click', () => {
  player.classList.toggle('rotate')
})
#myplayer {
  background: red;
  height: 100px;
  width: 100px;
  color: white;
}

#myplayer.rotate {
  transform: rotateY(180deg);
}
<button>mirror</button>
<div id="myplayer">:)</div>

  • Related