Search code examples
javascripthref

href="javascript:;" or href="javascript:void(0)", the difference?


I read about the href="#" and href="javascript:void(0)"comparison, I also want to know about the comparison about

href="javascript:;" or href="javascript:void(0)",

ps: I use href="javascript:;" all the time instead of href="javascript:void(0)", have not find any trouble.


Solution

  • Using javascript: in hyperlinks in either form is bad. Your JavaScript design should be unobtrusive.

    If you're going to attach event listeners to your anchors, you should use the # anchor or even an actual URL, e.g.:

    <a href="/delete/post/123">delete</a>
    ...
    <script>
    jQuery(function($) {
         $('a').on('click', function(event) {
             event.preventDefault();
             // do ajax stuff
         });
    });
    </script>
    

    This way, old browsers (or those with JavaScript disabled) will follow a regular link to delete an item whereas JavaScript enabled browsers will do this via AJAX so that the page doesn't have to refresh.

    If your link is really meant to do nothing at all, you shouldn't use anchors at all; just style a <span> for that purpose.