views:

73

answers:

4

Hi Guys,

I have a very simple toggleClass that changes the appearance of a link when clicked on. Works great apart from one thing. Every time I click the link, the browser focus shifts right back to the top of the page. This gets quite annoying if a link is at the very bottom of a page.

I could use another element such as span of coarse, but I am curious to know if there is a solution to my question.

Example link used:

<a class="share-this" href="#">Share This</a>
+2  A: 

When you click the link it is going to the '#' specified in the href, which is what is taking your screen to the top.

What you need to do is prevent this default browser action. You can do that by handling the click event and preventing it from bubbling up (which the browser would then handle).

You can prevent the default click action like so:

$('.share-this').toggleClass('some-class-that-is-toggled').click(function(e) {
    e.preventDefault();
});
Jon Erickson
or :`$('.share-this').toggleClass('some-class-that-is-toggled').click(function(e) { return false;});`
Braveyard
@Aaron that will work too, but it is important to note that return false is slightly different http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false
Jon Erickson
@Jon : Thanks for the info again. It is nice to learn such another info :)
Braveyard
+1  A: 

Why use a link if you are not going anywhere? Just add the toggle code to some other element type. Not only will it avoid a work around it will be more semantically correct and clearer to maintain.

AUSteve
A: 

Hi Keith,

Solution -->

<a class="share-this" href="javascript:void(0);">Share This</a> 

This is happen because of href="#" use "javascript:void(0);" instead of #.

it also changes your URL e.g.

http://localhost:8080/appname to http://localhost:8080/appname#

Yashwant Chavan
+1  A: 

or this function may help as well :

$('.share-this').toggleClass('some-class-that-is-toggled').click(function(e) {
    return false;
});
Braveyard