Improve code jQuery

Asked

Viewed 136 times

7

I made a simple code for a button to open a sidebar, but I find this code repetitive, I wonder how I can improve it.

$('.openbtn').click(function(event) {
    event.preventDefault();
    $('.sidebar').css('width', '250px');
    $('#lista-torneios').css('margin-left', '250px');
});
$('.closebtn').click(function(event) {
    event.preventDefault();
    $('.sidebar').css('width', '0');
    $('#lista-torneios').css('margin-left', '0');
});
  • If there are two buttons, I don’t see where "reduce the repeated code" will be worth following this goal...

  • 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

2 answers

13


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>

  • 1

    too much mass!

1

Hello,

It is less readable, but can be done in one line:

$(document).on('click', e => $(e.target).hasClass('menu') ? $('.sidebar').toggle(500): null)

See the example on Codepen.

Browser other questions tagged

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