Search code examples
javascripthtmlcsshref

Prevent page refreshing after clicking a selector, but be able to run scripts


I would like to ask. I have an element

<a href='...' data-href='...'>

The problem is to prevent page redirecting after clicking this element, but still be able to run JavaScript functions by onClick action. I was trying to set

pointer-events: none;

in my CSS, but this is blocking my elements from onClick action.

Has anybody any idea how to slove that problem?


Solution

  • If i understand, you would like to prevent the link from following the url.

    If this is the case you could give it an id

        <a id="myLink" href="...">...</a>
    

    and then control the event using javascript

        <script>
                document.getElementById("myLink").addEventListener("click",function(event){
                     event.preventDefault();
                     /* your code here */
                });
        </script>
    

    More info: http://www.w3schools.com/jsref/event_preventdefault.asp