Search code examples
javascriptjqueryframeworkscode-snippets

Convert snippet Jquery to JS


any help I can get to convert this Jquery snippet to JS vanilla? I've been trying to do it but always get error. Thanks in advance for any reply.

Edit: function move_player is what I am trying to translate, the rest is already done.

$(document).ready(function() {
  var end_of_track = 15;
  var players = [
    {
      id: 1,
      position: 0,
      keycode: 80,
      css_locator: '#player1_strip',
    },
    {
      id: 2,
      position: 0,
      keycode: 81,
      css_locator: '#player2_strip',
    },
  ];

  function advancePlayer(keyCode) {
    players.forEach(function(player) {
      if (
        keyCode == player.keycode &&
        players[0].position < end_of_track &&
        players[1].position < end_of_track
      ) {
        move_player(player.css_locator);
        player.position++;
        winner(player.position, player.id);
      }
    });
  }

  $(document).keyup(function(e) {
    advancePlayer(e.keyCode);
  });
});

function move_player(strip) {
  $(strip)
    .find('td.active')
    .removeClass('active')
    .next()
    .addClass('active');
}

function winner(player, num) {
  if (player > 14) {
    alert('Player ' + num + ' has won!');
  }
} ```



Solution

  • Assuming ES6 is allowed, you could use the querySelector to find the current active td element and then remove its active class from the elements classList then use nextElementSibling to get its sibling td element and add the the active class to it.

    ES6:

    function move_player(strip)
    {
        var activeElement = document.querySelector(`${strip} td.active`);
        activeElement.classList.remove('active');
    
        var nextElement = activeElement.nextElementSibling;
        nextElement.classList.add('active');
    }
    

    Example

    Before ES6:

    function move_player(strip)
    {
        strip = strip.replace('#', '');
        var stripElement = document.getElementById(strip);
        var activeElements = stripElement.getElementsByClassName('active');
    
        if(activeElements.length > 0)
        {
            var active = activeElements[0]
            active.classList.remove('active');
            var nextElement = active.nextElementSibling;
            nextElement.classList.add('active');
        }
    }
    

    Example