Question

I have this HTML code (JSFiddle)

There I have used an < a > tag with href=""

I cannot get the expected functionality(simply show and hide a div). But when I changed it to href="#" it works fine.

Why is it acting like that when I use href=""?

Can anybody please explain this behavior ?

Was it helpful?

Solution

Your click event is also ending up triggering the href. In the case of the empty link, this is causing a page refresh, whereas in the case of the # it simply goes to a page anchor. In your click method, use preventDefault() to stop the link from getting followed. See documentation:

http://api.jquery.com/event.preventdefault/

To specifically answer with relation to your code, you would change to this:

    $(document).ready(function(){
    $('#inboxHeaderLink').click(function(e) {
        e.preventDefault();
        $('#newMessage').show();
        $('#viewMessage').hide();
    });
});

OTHER TIPS

With empty href in <a href=""> will Reload the page.

You can use href="javascript:void(0);"

Fiddle Demo

or

you can use event.preventdefault on click of the anchor tag .

Fiddle Demo

The href="" reloads the page

The href="#" part is a commonly used way to make sure the link doesn't lead anywhere on it's own.

The #-attribute is used to create a link to some other section in the same document. So if you specify # without any name like in your case, the link leads nowhere.

You can also use href="javascript:;"

you have 2 option.if you want to prevent a tag default event through html then write like this

<div id="inboxHeader">                  
    <div id="inboxNewMessage"><a id="inboxHeaderLink" href="javascript:void(0);">Click</a></div>
</div>

And if you want to stop it through jquery then write it like this

$('#inboxHeaderLink').click(function(e) {
    e.preventDefault();
    $('#newMessage').show();
    $('#viewMessage').hide();
});

As Stated in RFC 2396: A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document.

So, to avoid this you either have to set href="#" OR href="javascript:void(0)".

You should do a preventDefault():

fiddle

href="" is a hyperlink to the current page. In other words: it will refresh the page. href="#" is a "hyperlink" that gets you to the top of your page, but without refreshing which is what you need. If you refresh, the green square will be reloaded and reset after the JS code fires.

empty href="" will navigate to the page , so stop the default event using

event.preventDefault();

Demo : http://jsfiddle.net/Lp7e7/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top