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;
}
7
  • please add a bit html and css Commented Mar 31, 2017 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 Commented Mar 31, 2017 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. Commented Mar 31, 2017 at 11:19
  • You sure none of the workarounds in [4] work for you? Commented Mar 31, 2017 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 Commented Mar 31, 2017 at 11:23

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect ! I didn't know that script tags could have an ID That solved my problem. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.