0

I have several elements which have I would like to add a class to their pseudo :before element when they are clicked on. Currently I have the class added to the elements, but am having trouble figuring out how to attach the listener to to the element and add the class to the pseudo-element.

Here is my HTML:

<div class="locked-item"></div>

SCSS:

.locked-item{
  &:before {
    content: '';
    background-image: url(../../images/lock.svg);
    background-position: center center;
    background-size: cover;
    background-size: 37%;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  background-color: @brand-green;
  transition: all .2s;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 100%;
  left: 0;
}

Javascript:

setTimeout(function() {

    var lockItems = document.getElementsByClassName('locked-item');

    for (var i = 0; i < lockItems.length; i++) {
      lockItems[i].addEventListener('click',handleClick,false);
    }

}, 100);

function handleClick(){
    addClass(this, 'jiggle-click');
    setTimeout(function() { 
        removeClass(this, 'jiggle-click');
    }.bind(this), 820);
}


function hasClass(el, className) {
  if (el.classList)
    return el.classList.contains(className)
  else
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

function addClass(el, className) {
  if (el.classList)
    el.classList.add(className)
  else if (!hasClass(el, className)) el.className += " " + className
}

function removeClass(el, className) {
  if (el.classList)
    el.classList.remove(className)
  else if (hasClass(el, className)) {
    var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
    el.className=el.className.replace(reg, ' ')
  }
}
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
byrdr
  • 5,197
  • 12
  • 48
  • 78
  • `:before` and `:after` can't have additional classes, because they're not actually part of the DOM. If you want to add a listener, you need to create a child element instead. – Blazemonger Nov 20 '15 at 20:47
  • 1
    Possible duplicate of [Only detect click event on pseudo-element](http://stackoverflow.com/questions/7478336/only-detect-click-event-on-pseudo-element) – Asons Nov 20 '15 at 20:54

1 Answers1

0

You can't. A pseudo-element is just rendered if it has content (given from CSS). You can style it, but you can't add event handlers to it or otherwise approach it from Javascript. That also means you can't give them classes.

However, you can add classes to the (parent) element as you already figured out. That class doesn't need to have any effect on the element itself and can be used just for styling the peudo-elements it contains.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210