-1

I want to move an image from the very left side of the screen as soon as it appears and while scrolling, it should move to the right side of the screen. I need to achieve this in pure JavaScript or CSS.

Exactly like this, https://jsfiddle.net/PvVdq/ except no JQuery.

$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * ($(document).width() - $horizontal.width()));
    
    $horizontal.css({
        'left': position
    });
  });
});

1 Answer 1

2

Using the document object of javascript would help you achieve your goal.

You can use it in the following way:

document.addEventListener("DOMContentLoaded", function() {
  var horizontal = document.getElementById('horizontal');

  window.addEventListener("scroll", function() {
    var s = window.scrollY,
      d = document.documentElement.scrollHeight,
      c = window.innerHeight;

    var scrollPercent = (s / (d - c));

    var position = scrollPercent * (document.documentElement.scrollWidth - horizontal.offsetWidth);

    horizontal.style.left = position + "px";
  });
});
#horizontal {
  position: fixed;
  width: 50px;
  background: red;
  left: 0;
  top: 50px;
}

span {
  font-size: 2em;
}
<span>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum! Provident similique accusantium nemo autem.
</span>

<div id="horizontal">test</div>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.