Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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.

like image 629
Evan Sharp Avatar asked Nov 12 '11 01:11

Evan Sharp


1 Answers

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>
like image 197
RobG Avatar answered Oct 15 '22 17:10

RobG