When I click on the reference id of the tag does not call the page I want

2

I can not make it work at all ... help me out!

<script>
    document.getElementById("ClicouNaTag").addEventListener(
        "click",function() {
            window.location.href = "vaiparaessapagina.php";
        }
    );  
</script>
    
asked by anonymous 23.05.2018 / 18:53

1 answer

1

The Question Author reported that it has the following code snippet:

<li class="nav-item">
    <a id="ClicouNaTag" class="nav-link" href="index.php">
        <em class="fa fa-address-card"></em>Vaiparaessapagina</a>

The code for page change is as follows:

document.getElementById("ClicouNaTag").addEventListener(
    "click",function() {
        window.location.href = "vaiparaessapagina.php";
    }
);  

The problem is that the a#ClicouNaTag element has the href attribute that causes the redirect to be made to the page itself. Thus, this redirection will prevent the click event from being processed.

It is important to remember that in many cases where you use event trapping in Javascript, you should prevent the default action of the element using the event.preventDefault() method.

Change your code to:

document.getElementById("ClicouNaTag").addEventListener(
    "click",function(event) {
        event.preventDefault();
        window.location.href = "vaiparaessapagina.php";
    }
);  

And, since you will not use href="index.php" , I would replace this snippet with # or javascript: void(0) .

So:

 <a id="ClicouNaTag" class="nav-link" href="#">...
    
23.05.2018 / 19:06