Since the two elements use the same event, you can group the two in the same selector, and use a ternary to change the values by checking with $(this)
which element triggered the event and whether it has the class .openbtn
: if the first argument of the ternary applies, otherwise the second.
$('.openbtn, .closebtn').click(function(event) {
event.preventDefault();
// quem disparou o evento tem a classe .openbtn?
var el = $(this).hasClass('openbtn');
$('.sidebar').css('width', el ? '250px' : '0');
$('#lista-torneios').css('margin-left', el ? '250px' : '0');
});
Note that in the variable el
I’m checking if the button that triggered the event has the class .openbtn
. Hence the value of el
will be a boolean true
or false
, which will be used later in the ternary (if you do not know what a ternary operation is, click here).
Example:
$('.openbtn, .closebtn').click(function(event) {
event.preventDefault();
// quem disparou o evento tem a classe .openbtn?
var el = $(this).hasClass('openbtn');
$('.sidebar').css('width', el ? '250px' : '0');
$('#lista-torneios').css('margin-left', el ? '250px' : '0');
});
.sidebar{
background: red;
width: 0;
transition: width .5s;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">div</div>
<button class="openbtn">Abre</button>
<button class="closebtn">Fecha</button>
If there are two buttons, I don’t see where "reduce the repeated code" will be worth following this goal...
– LipESprY
The only way I see to improve this is associating with some CSS class and doing a toggleClass(), but there would not even need 2 buttons as already commented
– hugocsl