Search code examples
javascriptcsspseudo-class

Changing the 'content' property in a ::before pseudo class


JSFiddle

In my JS I'm trying to access the 'content' property of the dislpay_object::before class. I need to set the 'content' (text) to the placement of the div on the page.

I've done tons of searching but haven't found anything this in depth on these types of pseudo classes.

  .display_object {
  position: absolute;
  border: thin solid black;
  width: 15cm;
  white-space: nowrap;
}

.display_object:active::before {
  content: "x,y";
  /*needs to be changed to actual values*/
  display: block;
  position: absolute;
  background: rgba(0, 0, 0, 0.48);
  padding: 1em 3em;
  color: white;
  font-size: .8em;
  bottom: 1.6em;
  left: -1px;
  white-space: nowrap;
}

How can I reference the .content of the :active::before through JS, to set it to its current position?


Solution

  • Via this answer, you can set the before pseudo-element's content property to an attribute of the parent div by using attr():

    content: attr(data-before);
    

    Then just update that attribute in your event handler:

    div.setAttribute('data-before',`x: ${mousePosition.x}, y: ${mousePosition.y}`);
    

    Working snippet:

    		var mousePosition;
    		var offset = [0, 0];
    		var div;
    		var isDown = false;
    
    		div = document.createElement("div");
    
    		div.className = "display_object";
    		div.innerHTML = "Draggable box:  ";
    
    		document.body.appendChild(div);
    
    		div.addEventListener('mousedown', function(e) {
    		  isDown = true;
    		  offset = [
    		    div.offsetLeft - e.clientX,
    		    div.offsetTop - e.clientY
    		  ];
    		}, true);
    
    		document.addEventListener('mouseup', function() {
    		  isDown = false;
    		}, true);
    
    		document.addEventListener('mousemove', function(event) {
    		event.preventDefault();
    		if (isDown) {
    
    		  mousePosition = {
    
    		    x: event.clientX,
    		    y: event.clientY
    
    		  };
    
    		  div.style.left = (mousePosition.x + offset[0]) + 'px';
    		  div.style.top = (mousePosition.y + offset[1]) + 'px';
    
    			div.setAttribute('data-before',`x: ${mousePosition.x}, y: ${mousePosition.y}`);
    
    		}
    		}, true)
    		;
    .display_object {
      position: absolute;
      border: thin solid black;
      width: 15cm;
      white-space: nowrap;
    }
    
    .display_object:active::before {
      content: attr(data-before);
      display: block;
      position: absolute;
      background: rgba(0, 0, 0, 0.48);
      padding: 1em 3em;
      color: white;
      font-size: .8em;
      bottom: 1.6em;
      left: -1px;
      white-space: nowrap;
    }