Search code examples
javascriptjqueryhref

$.on, click doesn't work when href attribute is empty


<a href="">i am a link</a>
<script src="jquery.js"></script>
<script>
    $("a").on('click', function(){
        console.log("the a link is clicked")
    })
</script>

doesn't print anything, when i click on the link.

Whereas, when i initialise href with hash symbol, it works.

this works,

<a href="#">i am a link</a>
<script src="jquery.js"></script>
<script>
    $("a").on('click', function(){
        console.log("the a link is clicked")
    })
</script>

Solution

  • Your first code example will work fine, you just need to prevent the page refresh that is happening when the link is clicked:

    <a href="">i am a link</a>
    <script src="jquery.js"></script>
    <script>
        $("a").on('click', function(e){
            e.preventDefault(); // < stop the link behaviour
            console.log("the a link is clicked")
        })
    </script>
    

    That said, it is better practice to always include a value on the href parameter, even if it is just a # - but still use preventDefault() if it's needed.