I want to toggle a css class on all elements with the same class, on click of another element.
I had it working with jQuery but need to switch to pure JavaScript.
The jQuery version that works:
$(function() {
$("#logo").click(function() {
$(".grey").toggleClass("white", 1000);
$(".red").toggleClass("orange", 1000);
});
});
When you click on the element with id="logo"
, everything with class="grey"
toggles white
class and everything with class="red"
toggles orange
.
Update with new problem!
I'm using @Vektor's code which works well — except on the iPhone 5 where nothing happens. (It works in my iPhone 12 and 7.) Simplified code for trials:
<body>
<div id="logo" class="grey"><p class="red">Hello.</p>
</div>
<script>
const logo = document.getElementById('logo');
logo.addEventListener('click', () => {
const grey = document.querySelectorAll('.grey');
const red = document.querySelectorAll('.red');
grey.forEach(e => e.classList.toggle('white'));
red.forEach(e => e.classList.toggle('orange'));
}, false);
</script>
</body>
body{background-color: #000000;}
div#logo{
position:fixed;
top:0;
left:0;
height: 100vh;
width:30vw;
cursor: pointer;
}
.red{background-color:#4C0000;}
.orange{background-color:#d69215}
.grey{background-color:#485055;}
.white{background-color:white;}
I read adding cursor:pointer
would fix JavaScript not functioning on non-traditional clickable elements for older iPhone browsers. It didn't.