Shortcut key for PHP and Mysql pagination

0

I have a pagination made in PHP and Mysql:

$sqlVisualizarContar = mysqli_query($this->conexao,"SELECT * FROM tabela;");

$maximo = 10;

if($pagina >= 1){

   $inicio = $pagina * $maximo;

   $totalPag = mysqli_num_rows($sqlVisualizarContar) / $maximo;

}else{

  $inicio = 0;

  $maximo = 10;

}
if($pagina < 1){

    $paginacao = "<a href=\"?pag=".($pagina + 1)."\" class='btn btn-warning btn-xs' style='background-color: #DA9139; color: #fff'>Próximo <i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> </a>";

}else{

$anterior = ($pagina - 1);

    if($anterior == 0){

       $pgAnterior = "visualizar-produtos.php";

    }else{

       $pgAnterior = "\"?pag=".$anterior."\"";

    }

    $proximo = ($pagina + 1);

    $pgProximo = "\"?pag=".$proximo."\"";


$paginacao = "<a href='visualizar-produtos.php' class='btn btn-warning btn-xs' style='background-color: #DA9139; color: #fff'> Primeira Página </a>&nbsp;";

    $paginacao .= "<a href=".$pgAnterior." class='btn btn-warning btn-xs' style='background-color: #DA9139; color: #fff'> <i class=\"fa fa-angle-double-left\" aria-hidden=\"true\"></i> Anterior </a>&nbsp;";

if($pagina != ceil($totalPag - 1)){

      $paginacao .= "<a href=".$pgProximo." class='btn btn-warning btn-xs' style='background-color: #DA9139; color: #fff'> Próximo <i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> </a> &nbsp;";

      $paginacao .= "<a href=\"?pag=".ceil($totalPag - 1)."\" class='btn btn-warning btn-xs' style='background-color: #DA9139; color: #fff'> Última Página </a>&nbsp;";

    }
}

sqlVisualizar = mysqli_query($this->conexao,"SELECT * FROM tabela LIMIT ".$inicio.",".$maximo.";");

As a result, I get this way:

But the user to change pages, he has to click on the numbers, arrow or the word Last . I would like to know you can also use shortcut keys to change pages. If so, how would I do that?

    
asked by anonymous 23.01.2018 / 12:15

1 answer

3

You can add a listener to the event onkeydown in document and validate whether the key pressed has code 37 (left arrow) or 39 (right arrow). 38 and 40 are, respectively, the up and down arrow codes.

const ultimaPagina = 4;

document.onkeydown = function(e) {
  e = e || window.event;
  
  const elemento = document.querySelector('#atual');
  let pagAtual = parseInt(elemento.innerHTML);
  
  if(e.keyCode == 37 && pagAtual > 1) {
    elemento.innerHTML = --pagAtual;
    console.log('Página anterior');
  } else if (e.keyCode == 39 && pagAtual < ultimaPagina) {
    elemento.innerHTML = ++pagAtual;
    console.log('Próxima página');
  }    
};
<div id="pagina">
  Página atual: <span id="atual">1</span>
</div>
    
23.01.2018 / 12:20