最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Force click on empty link to not move the page focus - Stack Overflow

programmeradmin1浏览0评论

I've got an empty link:

<a href="#" id="stop-point-btn">+ add stop-point</a>

bound to a JS function:

$("#stop-point-btn").bind("click", addStopPoint);

which simply adds some content in a div:

function addStopPoint() {
    $("#stop-point-content").append(stopPointHtml())
}

Upon click, if I have scrolled a bit down, it moves me back to the top of the page (of course, because of the provided # empty id value). But how can I make it so that the position, of where I am at the page, does not change (meaning the scroll position).

I've got an empty link:

<a href="#" id="stop-point-btn">+ add stop-point</a>

bound to a JS function:

$("#stop-point-btn").bind("click", addStopPoint);

which simply adds some content in a div:

function addStopPoint() {
    $("#stop-point-content").append(stopPointHtml())
}

Upon click, if I have scrolled a bit down, it moves me back to the top of the page (of course, because of the provided # empty id value). But how can I make it so that the position, of where I am at the page, does not change (meaning the scroll position).

Share Improve this question asked Mar 14, 2015 at 13:06 MilkncookiezMilkncookiez 7,40712 gold badges68 silver badges107 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

replace the href value in javascript:void(0); and the click on the link will produce no effect

<a href="javascript:void(0);" id="stop-point-btn">+ add stop-point</a>

Use preventDefault().

 $("#stop-point-btn").bind("click", function(e) {
        e.preventDefault();
        addStopPoint();
    });

And keep in mind:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

Pass event as an argument to your function and add this statement. event.preventDefault() inside of addstoppoint function.

You need to pass href value is javascript:void(0); which return undefined that's why browser stays on the same page and do not scroll page.

<a href="javascript:void(0);" id="stop-point-btn">+ add stop-point</a>
发布评论

评论列表(0)

  1. 暂无评论