How to check whether or not a rel=""

0

I'm setting up a function for wordpress, where the person can navigate between posts through the keyboard.

With difficulties, I was able to create the following function:

   <script>
        window.onkeydown = function(event) {
            if (event.keyCode === 38) { //Para cima

                if($(window).scrollTop() == 0) { 
                    var href =  $("a[rel='next']").attr("href");                 
                    window.location.href = href;
                }

            }
            if (event.keyCode === 40) { //Para baixo

                if($(window).scrollTop() + $(window).height() == $(document).height()) { 

                    var href =  $("a[rel='prev']").attr("href");                 
                    window.location.href = href;
                }
            }            

        };
    </script>

However, I needed to check first whether there is one in html or to release the keydown function

For example:

If there is a rel="prev" in html, then turn the function to change pages by pressing the button on the keyboard.

Thank you in advance for the help

    
asked by anonymous 09.10.2017 / 20:42

1 answer

0

You can try to get the element using jQuery, if it is not null it is because the element exists.

Example

//para executar apos o DOM ser carregado
$(document).ready(function(){
   let prev = $('[rel="prev"]'),
       next = $('[rel="next"]');

   if (prev.length) console.log("Tem prev");
   if (next.length) console.log("Tem next");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputrel="prev">
    
09.10.2017 / 21:09