1

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?

Kevin Young
  • 51
  • 1
  • 9
  • 1
    Ah, I've totally forgotten CSS `attr()` function. See [this answer](https://stackoverflow.com/a/42000085/11695199) in the dup Alex has suggested. @Chiller, that is just what I'd call "unreasonable way" in the context of the mousemove handler. – Teemu Jun 22 '18 at 15:16
  • 1
    I forgot the attr() function too XD, nice catch @Teemu – Chiller Jun 22 '18 at 15:21

1 Answers1

1

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;
}
nvioli
  • 4,137
  • 3
  • 22
  • 38
  • Awesome. Works great in the snippet and fiddle. I'll implement it into the actual project and if it works the same then the answer is yours. – Kevin Young Jun 22 '18 at 15:25