简体   繁体   中英

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).

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.

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; 

});

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM