简体   繁体   中英

Only disable scrolling to onclick href element

I've got some elements on a page with a accordion/tab UI thing behind it, and when a user clicks one, it opens and also scrolls it to the top of the page due to the anchor in the href . I want to stop that jumping behavior only . This is an example of such an element;

<a class="data switch" tabindex="-1" data-toggle="trigger" href="#description" id="tab-label-description-title">
More info
</a>

Because this element is tied up in all kinds of CMS and UIX related things I cannot change the href value as most answers to similar questions suggest.

So I tried with JavaScript/jQuery something like this;

$('.data.switch').on('click', function(e) {
    e.stopPropagation();
});

This does stop the jumping to the element, but it also stops everything else making the element not functional at all. So my question is; is there some sort of variant of stopPropagation action that only disables jumping to an anchor element?

edit I'm thinking aloud here; like stopPropagation or preventDefault stops all bubbling actions, isn't there a way to specify just the scrolling? Or maybe a workaround where onclick it reads thew current scrollposition and forces to stay at that position (though this feels very hacky)..?

You can achieve you result by doing follow things

In you HTML code add id tag like

<a class="data switch" id="dataSwitch" tabindex="-1" data-toggle="trigger" href="#description" id="tab-label-description-title">
    More info
</a>

and in your jquery use document ready function

$(document).ready(function () {
    $('#dataSwitch').on('click', function (e) {
        e.stopPropagation();
    });
});

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