Question

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>
Was it helpful?

Solution

or this function may help as well :

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

OTHER TIPS

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();
});

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.

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#

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