JavaScript code optimization (JQuery)

2

What is the best way to write the following code in JQuery?

document.getElementById("jogador").style.top = parseInt(document.getElementById("jogador").style.top) - v;

Since the beginning of the year I have been programming in JavaScript, but I have only started with JQuery.

    
asked by anonymous 01.10.2017 / 00:11

2 answers

2

In general I would say that the less jQuery the better. There's an interesting question with pros and cons here .

But to answer your question, you can do this in jQuery:

var v = 100;
$('#jogador').css('top', function() {
  return parseInt($(this).css('top'), 10) - v;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="jogador" style="top: 200px; position: absolute;">Jogador</div>

If you need to do this many times you can do this, avoiding reading the value in the DOM, and therefore faster:

var moverJogador = (function(jogador) {
  var styles = window.getComputedStyle(jogador)
  var current = {
    left: parseInt(styles.left, 10),
    top: parseInt(styles.top, 10)
  }
  return function(coords) {
    for (var coord in coords) {
      current[coord] += coords[coord];
      jogador.style[coord] = current[coord] + 'px';
    }
  }
})(document.getElementById('jogador'));

moverJogador({
  top: -150,
  left: 200
});
#jogador {
  top: 200px;
  left: 10px;
  position: absolute;
  transition: left 3s, top 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="jogador">Jogador</div>
    
01.10.2017 / 00:33
0

If you call a "better" a more "lean" form, then this would be:

$("#jogador").css("top",parseInt($("#jogador").css("top"))-v);

Or you can assign the element to a variable, and the code is still quite short:

e = $("#jogador");
e.css("top",parseInt(e.css("top"))-v);
    
01.10.2017 / 01:37