How to change the size of a :before or :after dynamically with Jquery?

Asked

Viewed 1,062 times

2

Can anyone tell me if it is possible to change the size of a :before or :after dynamically with jquery?

Ex:

$('#elemento:before').css({'width':'100px'});
  • Could be more complete in your question, I couldn’t understand

  • @Juliohenrique, let’s say that before is a parent element that is with its width at 100%, but before needs to be with the width of a child element that is added adinamicamente. I hope I could explain.

1 answer

1


You can’t get access to 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 to the element.

In the example below, see that the ::after has initially 50% of width, and after adding the class .after, He went on to be 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>
<div id="teste">
   principal
</div>

Edit

You can inject a dynamic CSS into the page and do the same as in the example above, but now with the width according to the child element.

Below the ::before has the same width as the main element (100%). After adding a child element, the script changes the width of ::before adding the class .before, that has the same width of the element dynamically added:

$("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>
<div id="teste">
   abc
</div>
<button type="button">Adicionar filho</button>

  • Thanks @dvd for the clarification, for my case this solution is not feasible but for some companion here this medium should help, even so I thank the help.

  • Got it. But I edited the answer with a new solution. Create a dynamic style using the same technique as the first example.

  • Thanks, that solved the problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.