0

I am trying to dynamically change the width of an element in :after. But it is not reflecting. Can someone please help!

$(function(){
var a=20;
$(".progress:after").width(a+"%"); 
// This is not showing 20%. Still shows 50% which was coded in CSS
});
.progress {
    width:200px;
    height:50px;
    border:1px solid black;
    position:relative;
}
.progress:after {
    content:'\A';
    position:absolute;
    background:black;
    top:0; bottom:0;
    left:0; 
    width:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress"></div>

Here is the Link to JSFidle

Kshri
  • 414
  • 3
  • 16
  • 1
    You cannot use `$(".progress:after")` as a selector. – Twisty May 30 '17 at 16:10
  • Question.. What is the purpose of the psuedo? Do you have dynamic content? – Cam May 30 '17 at 16:12
  • Look this https://stackoverflow.com/questions/29260296/modify-pseudo-select-after-in-javascript – Freelancer May 30 '17 at 16:13
  • Even better option: https://stackoverflow.com/questions/17788990/access-the-css-after-selector-with-jquery – Twisty May 30 '17 at 16:14
  • @Cam: I am trying to change the width so as to make it function like a progress bar. – Kshri May 30 '17 at 16:14
  • @Kshri you could simply adjust the class name, and have unique classes. Or you could have a proper element and change it's width instead of using a pseudo element. – Twisty May 30 '17 at 16:15
  • @All: I have tried all of the ones in stackoverflow! None of them actually worked! – Kshri May 30 '17 at 16:15
  • @Kshri then try something like this: http://jsfiddle.net/Twisty/huw9c3n6/ – Twisty May 30 '17 at 16:19
  • @Twisty: That really helped! Thank you so much – Kshri May 30 '17 at 16:21
  • @Kshri welcome, Some more thought on it: http://jsfiddle.net/Twisty/huw9c3n6/1/ – Twisty May 30 '17 at 16:24
  • @Twisty: Looks brilliant :) – Kshri May 30 '17 at 16:29
  • @Kshri also consider jQuery UI: http://jqueryui.com/progressbar/ – Twisty May 30 '17 at 16:33
  • @Twisty: I did think about that but the whole logic is already implemented using . But it looks like is not supported in Safari browser. So this is an alternate solution which runs just in safari without complicating existing things much. – Kshri May 30 '17 at 16:37

1 Answers1

1

You should use the, now available, html5 progress element.

$(function() {
  var a = 20;
  $("progress").prop('value', a);
});
progress {
    width:200px;
    height:50px;
    border:1px solid black;
    position:relative;
    background:transparent;
}
::-webkit-progress-bar{background:transparent;}

::-moz-progress-bar{background-color:black;}
::-ms-fill{background-color:black;}
::-webkit-progress-value{background-color:black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress value="50" max="100"></progress>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317