0

HTML

<section id="imag" class = "paral-1 image-contain">         
</section>

JAVAScript

var g = 0;
    //var myImage = document.getElementById("imag");
    window.addEventListener('scroll', pageScrolled);

    function pageScrolled() {
        g = g + 10;
        document.getElementById("imag").style.top = -g+"px" ;
    }
  1. First, the function should be called on scrolling but when page loads it is called.
  2. Second, When I scroll the function should update the variable "g" with 10 but it is increased by like 100. What is this weird beahviour. You can open console and check. Here's the fiddle - https://jsfiddle.net/LuLt0mh0/
0

2 Answers 2

1
  1. this will only happen if the document is scrolled on load (e.g. because of an anchor, or on a reload if the page was already scrolled)

  2. For each emmited scroll event g is increased by 10. But it is a continues event that is fired multiple times while scrolling.

    Adding a console.log(g) to the pageScrolled will show you that it is increased by 10 multiple times: jsfiddle.net/LuLt0mh0/1

    See MDN scroll for more details:

    [...]Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications.[...]

Sign up to request clarification or add additional context in comments.

2 Comments

Can we control this scroll behavior because if i have to apply any function on scroll, it could be a disaster.. Iam trying to add parallax scroll
@ShahRukhK You should never increase the values step-wise by a fixed value for each event that is fired, for classical paralax you tie your values to the scroll-offset, using something like the Scroll optimization with window.requestAnimationFrame shown on the MDN page. Or depening on the effect you want to have start a smooth animation if a certain scroll offset is reached. But as you don't mention what effect you want to achieve it is not possible to tell.
0

You have 2 problems with the following line:

  document.getElementById("imag").style.top = -g + "px";
  1. Every time the scroll event happens, that line executes--the result being #imag top decreases by x10px. Of course the reason why nothing happens is because...

  2. #imag has no position property assigned to it. In order for the property top to work is if the element has position: relative, absolute, or fixed. But even if you did have this corrected, that line of code will drive your #imag off of your viewport never to be seen again and will continue going north until you refresh the page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.