[whatwg] classList.toggle()

Maciej Stachowiak mjs at apple.com
Tue May 1 08:08:27 PDT 2007


On May 1, 2007, at 12:05 AM, Martin Atkins wrote:

> Maciej Stachowiak wrote:
>> How about about adding a toggle() operation to classList? Adds the  
>> token if not present, removes it if present. This would be useful  
>> for script code that dynamically manipulates classes to cause  
>> style changes.
>
> It's been my experience that toggles are troublesome. In order for  
> a call to toggle() to be successful -- where by successful I mean  
> that it makes the change you intended -- you need to know the state  
> ahead of time. If you have two distinct scripts "toggling" the same  
> value, they're going to get out of step and think they're turning  
> on when they're turning off.
>
> Or did you have a use-case in mind where it doesn't matter what the  
> end result is as long as it's not what it was before?

Yes, cases where you have a UI action that is supposed to always  
toggle the current state, and the class is used for styling so  
appearance can't be out of sync with the state. Here's a simple  
example. The images would zoom out and fade when you click on them,  
and return to their normal state when clicked again.

<style>
.container {
    margin: 75px;
}
.picture {
    width: 50px;
    height: 50px;
    display: inline-block;
}
.picture img {
     width: 50px;
     height: 50px;
}
.picture.zoomed img {
    width: 200px;
    height: 200px;
    position: relative;
    left: -75px;
    top: -75px;
    opacity: 0.8;
}
</style>

<section class="container">
<h1>Bridge Gallery</h1>

   <div class="picture" onclick="classList.toggle('zoomed')">
     <img src="goden-gate-bridge.jpg">
   </div>

   <div class="picture" onclick="classList.toggle('zoomed')">
     <img src="bay-bridge.jpg">
   </div>

   <div class="picture" onclick="classList.toggle('zoomed')">
     <img src="san-mateo-bridge.jpg">
   </div>

   <div class="picture" onclick="classList.toggle('zoomed')">
     <img src="benicia-bridge.jpg">
   </div>

   <div class="picture" onclick="classList.toggle('zoomed')">
     <img src="dumbarton-bridge.jpg">
   </div>

</section>



More information about the whatwg mailing list