Pergunta

I don't use jQuery. Can this be solved without it ?

I have only 1 HTML / JavaScript / (CSS) page. It contains links that reference html elements on the very same page. The page has a automatic vertical scrollbar because it is long. I need my event handler for link clicks to check if the referenced element is on the screen at the moment of the click. If it is there the page should not change position. Is that possible and how ?

  1. check if on screen
  2. don't move page

This code is a simple example that the page jumps so that the "hello world 2" is on the very top of the browser window.

<html>
    <head>
        <script type='text/javascript' language='javascript'>
            function onLinkClick(id)
            { }
        </script>
    </head>
    <body>
        <div id="id1">hello world 1</div>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        <div id="id2">hello world 2</div>
        <a href="#id2" onclick="onLinkClick('id2')">link</a>
        <div id="id3">hello world 3</div>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    </body>
</html>
Foi útil?

Solução 2

Ok, I solved it by myself (yes with some help of the referenced duplicate question). Using no jQuery:

function isElementVisible(element)
{
    var posTop = 0;
    var temp = element;
    while (temp)
    {
        posTop += temp.offsetTop;
        temp = temp.offsetParent;
    }
    var posBottom = posTop + element.offsetHeight;
    var visibleTop = document.body.scrollTop;
    var visibleBottom = visibleTop + window.innerHeight;
    return ((posBottom >= visibleTop) && (posTop <= visibleBottom));
}

function onLinkClick(id)
{
    var x = document.getElementById(id);
    if (isElementVisible(x))
        // prevent page to be scrolled up or down
        event.preventDefault();
}

Outras dicas

did you tried

getElementByTagName() ???

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top