SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Jan 2009
    Posts
    144
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript:void or "#" or ...

    I have a list of links on the same page. If user clicks on the link, it opens ajax window with msg.

    HTML Code:
    $(".openMsg").click(function(){
    //some code here
    }
    
    <a class="openMsg" href="#">More info</a>
    I am wondering what is the best option to use in those cases. I used "#", but this is not ok because it scrolls the page to top. I want to stay scroller on the same place.
    Maybe I should use the following?
    HTML Code:
    <a href="javascript:void(0)" onclick="openMsg();">More info</a>
    Or maybe I even shouln't use <a> element?

    Thank you

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Using what you had before is fine.

    Code html4strict:
    <a class="openMsg" href="#">More info</a>

    You can return false from the event function, to tell the web browser to not perform its default action. That prevents the web browser from trying to follow the link.

    Code javascript:
    $(".openMsg").click(function() {
        //some code here
        ...
        // and at the end
        return false;
    }

    That will work in most cases.

    In the rare cases when you also require that the event continues to bubble up to parent elements as well (as I said, it's rarely a problem), you can use jQuery's preventDefault method from the event.


    Code javascript:
    $(".openMsg").click(function(evt) {
        //some code here
        ...
        // and at the end
        evt.preventDefault();
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •