Disable click() from scrolling the page

Viewed 41

I'm working on a Chrome extension and am trying to use JavaScript to click on an element on the page when a certain condition is met, which works just fine.

The problem is, if the element to be clicked on is off screen, the browser will automatically scroll so that the element is then on the screen. I'd like to have my code click on the element without having the screen scroll automatically.

Here is the code that triggers the click event.

function isHidden(users, comment, sticky) {
    let userElement = comment.querySelector(`[data-testid="comment_author_link"]`);
    let currName = userElement.getAttribute("href");

    let shouldHide = users.includes(currName);

    let isStickied = comment.querySelector("._2wd-K5Djdc9TGPRGDgmkpX") !== null;

    if(shouldHide || (isStickied && sticky !== null)) {
        blockIndex = users.indexOf(currName);

        let level = comment.querySelector("._1RIl585IYPW6cmNXwgRz0J").innerHTML;
        level = parseInt(level.replace(/^\D+/g, ""), 10) - 1;

        let threadlines = comment.querySelectorAll(".threadline");
        threadlines[level]?.click();

        return true;
    }

    return false;
}

I can provide other code snippets if needed, or explain more about what I'm trying to do.

1 Answers

The browser doesn't usually scroll to clicked elements unless the link has a hash like '#myelement' and the element id is id='myelement. If that's the case you may need to e.preventDefault() or return false on all js events.

<button onclick="javascript: document.getElementById('myelement1').click()">Simulate el 1 click
</button>

<button onclick="javascript: document.getElementById('myelement6').click()">Simulate el 6 click - NO EFFECT
</button>

<a href='#myelement6' > 
<h1 id='myelement1'>1. Click me to sroll down - no js</h1>
</a>

<h1>2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1>

<h1>3. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1>

<h1>4. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1>

<h1>5. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1>

<h1 id='myelement6'>6. Last element.</h1>

Hard to say without working example.

Edit:

If nothing works you can store the scrollTop value before the click and set it back to what it was right after that (on scroll event maybe or with setTimeout)

Related