cppit
cppit

Reputation: 4564

block the hash anchor from scrolling

 <li> <a href="#calculate">Calculate</a></li>
 <li> <a href="#calculate1">Calculate1</a></li>
 <li> <a href="#calculate2">Calculate2</a></li>

this is the code I have, when I click on the link the page scrolls down to where #calculate is,which is understandable. But I need it to not scroll I can remove the value of the href,is there anyway to block it from scrolling WITHOUT removing the value #calculate and without changing the id names?

Upvotes: 0

Views: 441

Answers (4)

Musa
Musa

Reputation: 97717

Just prevent the default action of the link

$('li > a[href^=#calculate]').on('click', function(e){
    e.preventDefault();
    return false;
});

'li > a[href^=#calculate]' selects an a element whose href attribute begins with #calculate that is a child of an li element

More Info

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$('li > a[href*=calculate]').on('click', function(e) {
  e.preventDefault(); // this will prevent the page scroll

  // continue other code

});

Read about .preventDefault()

Here, 'li > a[href*=calculate]' will select those anchor tags which are direct(first level) children of li and contains calculate word in their href attribute.

Upvotes: 2

Oscar Jara
Oscar Jara

Reputation: 14187

Live Demo

In modern jQuery versions:

$('a').on('click', function(e) {
  e.preventDefault();
});

Other jQuery versions:

$('a').click(function() {
  return false;
});

Upvotes: 2

sachleen
sachleen

Reputation: 31141

You can bind a function to the click event and have it return false.

$("a").click(function() { return false; });

DEMO

Upvotes: 1

Related Questions