Javascript code optimization (Jquery)

Asked

Viewed 78 times

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 only now I started with Jquery.

  • What is the reason for writing/doing this in jQuery? This native Javascript code does not work?

  • It works, but they recommended that I start using only Jquery...

  • This recommendation may have false background. jQuery is done in Javascript and will do the same as this code does basically. If there is no specific reason then native JS is preferable. It may be that for stylistic reasons you do not want to mix JS with jQuery, but in general the less jQuery the better... take a look here: https://pt.stackoverflowcom/q/200809/129

  • Even so, how could I improve (shorten) the question code line?

2 answers

1


As a general rule I would say the less jQuery the better.
There’s a interesting question with pros and cons here.

But to answer your question, you can do it like 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>
<div id="jogador" style="top: 200px; position: absolute;">Jogador</div>

If you need to do this often you can do so, avoiding reading the value in the DOM, and so 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>
<div id="jogador">Jogador</div>

0

If you call "better" a way more dry, then would be this:

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

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

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

Browser other questions tagged

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