Does anyone know if I can change the size of a: before or: after dynamically with jquery?
Ex:
$('#elemento:before').css({'width':'100px'});
Does anyone know if I can change the size of a: before or: after dynamically with jquery?
Ex:
$('#elemento:before').css({'width':'100px'});
You can not access pseudo-elements via JavaScript because they are not part of the DOM. What you can do is create a specific class with new styles and add it to the element.
In the example below, you see that ::after
has initially 50% of width
, and after adding the class .after
, it has now 10%:
// adiciona a classe que altera o width do ::after
$("#teste").addClass("after");
#teste{
width: 200px;
height: 50px;
background: red;
}
#teste::after{
content: 'after';
display: block;
width: 50%;
height: 50px;
background: yellow;
}
/* classe que irá alterar o ::after */
#teste.after::after{
width: 10%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
principal
</div>
You can inject a dynamic CSS into the page and do the same as in the example above, but now with width
according to that of the child element.
Below ::before
has the same width as the parent element ( 100%
). After adding a child element, the script changes the width
of ::before
by adding the class .before
, which has the same width
of the element added dynamically:
$("button").click(function(){
$("#teste").append('<div id="filho">filho</div>');
var filhoW = $("#filho").width();
$("body").append("<style>#teste.before::before{width: "+filhoW+"px;}</style>");
$("#teste").addClass("before");
});
#teste{
width: 100%;
height: 80px;
background: red;
position: relative;
}
#teste::before{
content: 'before';
display: block;
width: 100%;
height: 30px;
background: yellow;
position: absolute;
bottom: 0;
}
#filho{
width: 80px;
background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
abc
</div>
<button type="button">Adicionar filho</button>