2

I need to change the margin-top value of p::before dynamically on each image click. Neither of these questions 1 / 2 / 3 / 4 nor this tutorial worked for me since I am changing the margin-top value not content or colors.

I can't use attr() because it's not supported for non-string values according to this. Creating stylesheet or adding scripting the the header isn't a good idea since I can't reach and modify it again so it's creating tens of style tags and rules and it's messing up with my styling.

How can I achieve this?

Thanks in advance

p::after {
    top: auto;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-bottom-color: #f9e8a2;
    border-width: 15px;
    left: 50%;
    margin: 28px 0 0 -15px;
}
Community
  • 1
  • 1
Samer Massad
  • 101
  • 1
  • 11
  • please add a bit html and css – marmeladze Mar 31 '17 at 10:42
  • 1
    images can't have a before element and if you are using jquery, why not just create the element if you need to style it dynamically, it's better than trying to style a before element – Pete Mar 31 '17 at 10:47
  • @Pete my fault buddy.. it's a p not an img. it's now edited I am not creating the element because it's animating and moving across the screen. – Samer Massad Mar 31 '17 at 11:19
  • You sure none of the workarounds in [4] work for you? – BoltClock Mar 31 '17 at 11:21
  • @BoltClock yes i am sure, because the value of the margin-top rule is calculated then added, i can't add a rule with a static value – Samer Massad Mar 31 '17 at 11:23
  • So why can't a created element animate and move across the screen? All an after is, is a pseudo element that is appended to the end of element – Pete Mar 31 '17 at 11:23
  • the element is created at the first click, then it moves by every click using a calculated margin.. until the user closes the div it gets removed. Do you have any suggestion i missed thinking about?? – Samer Massad Mar 31 '17 at 11:26

1 Answers1

2

May I suggest doing like this, where you dynamically create a style element (with a unique id so you can access it over and over) and just update a rule repeatedly

Usage

loadStyle('p.clicker::after { margin-top: ' + calculated-value + 'px; }');

Script

function loadStyle(css) {
  var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
  style.id = 'lastinbody';
  style.type = 'text/css';
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  document.querySelector('body').appendChild(style);
}

At this post of mine is a few more versions (which might be consider as a possible duplicate)

Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165