dfg123
dfg123

Reputation: 3

How can i prevent from link to send me to the top of the page

I am trying to prevent <a href="#id">link</a> from scrolling the page to (0,0).

I have to use the "#" (I have to stay in the same page).

What is the proper way to prevent the page from scrolling (jQuery/JavaScript/HTML/CSS)?

Note: (Scrolling to the top only happens when I am on the iPad; I am using jQuery mobile 1.3.2).

Upvotes: 0

Views: 375

Answers (4)

gespinha
gespinha

Reputation: 8477

You have various ways of getting this through Javascript (which is the easiest way).

Here is an example using JQuery:

$('#myLink').click(function(e) { e.preventDefault(); });

Here is an example using pure Javascript in the HTML:

<a href='javascript:void(0);'>click here</a>

To make it scroll to the top on your iPad, you should first determine whether the browser is a desktop application or a mobile application, and make this a conditional href on the link, executing the behaviour only when on the iPad browser, which can be much more complicated.

Upvotes: 4

Milan and Friends
Milan and Friends

Reputation: 5610

To prevent all empty links like <a href="#">Link</a> on page add this.

$(function() {
  $( 'a[href$="#"]' ).each(function() {
    $( this ).attr( 'href','javascript:void(0);' )
  });
});

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

Just return false in the click handler which will prevent the browser to redirect to the link. Other way to do is by calling preventDefault() method on the event object.

$('#myLink').click(function(e) {  

//Do what you want to do here

return false; 

});

Upvotes: 1

Jeff Storey
Jeff Storey

Reputation: 57172

It doesn't scroll to (0,0), it scrolls to the element with the id id

See this fiddle http://jsfiddle.net/HnC3L/ for an example

Upvotes: 0

Related Questions