Evan Sharp
Evan Sharp

Reputation: 2059

Activate an element's :active CSS pseudo-class using Javascript?

Is this possible?

For example, if a user presses the "return" key and I trigger the "mousedown" event, how do I also render the element with :active styles?

I know it is possible to do this using classes, but I'd greatly prefer to use the pre-existing :active styles.

Upvotes: 11

Views: 11480

Answers (1)

RobG
RobG

Reputation: 147413

According to the CSS 2.1 spec, the :active pseudo-class applies while:

an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.

You should be able to dispatch a mousedown event with the subject element as the event target and it should stay active until a matching mouseup event is dispatched. If it works, it likely won't work reliably on enough browsers to make it useful.

It would be much simpler (and more widely supported) to add/remove a suitable class.

Edit

Here is an example of using DOMActivate. You can see that dispatching an activate event on an element fires the associated onactivate listener, but doesn't change the appearance of the element being activated.

Perhaps you can simulate actiation by listening for the activate event, adding a class to highlight the element, then remove it after a few moments using setTimeout or similar.

<style type="text/css">
  p:active {
    background-color: red;
  }
  div:active {
    background-color: green;
  }
</style>

<script type="text/javascript">
  function Init () {
    var p, ps = document.getElementsByTagName('p');
    var d = document.getElementById('div0');

    if (ps.length && ps[0].addEventListener) {

      for (var i=0, iLen=ps.length; i<iLen; i++) {
        p = ps[i];
        p.addEventListener ("DOMActivate", onActivate, false);
      }
      d.addEventListener("DOMActivate", onActivate, false);
    }
  }

  function onActivate () {
    console.log(this.id + ' has been activated');
  }

  function simulateActive(id) {
    var evt = document.createEvent("UIEvents");
    evt.initUIEvent("DOMActivate", true, false, window,1);

    var el = document.getElementById(id); 
    var cancelled = !el.dispatchEvent(evt);

    if(cancelled) {
      console.log("cancelled");

    } else {
      console.log("not cancelled");
    }
  }
</script>

 </head>

<body onload="Init ();">

  <div id="div0">div
    <p id="para0">para0</p>
    <p id="para1">para1</p>
    <button onclick="
      simulateActive('para0');
    ">Activate para</button>
  </div>
  <button onclick="
    simulateActive('para0');
  ">Activate para</button>

</body>

Upvotes: 4

Related Questions