pietà
pietà

Reputation: 770

How to scroll up and down on page with jQuery?

I added a link into my page to scroll down:

<div class="scroll">
    <a onclick="scroll_down()" href="#" id="'scroll_id"> 
        click me 
    </a>
</div>

<script>
    function scroll_down() {
        var y = $(window).scrollTop(); //current position
        $("html, body").animate({scrollTop: y + $(window).height()}, 600);
    }

    function scroll_top() {
        window.scrollTo(0, 0);
    }
</script>

I want to set onclick attribute when bottom is reached to scroll_top.

scroll down is working but when bottom is reached , the attribute of theonclick of <a> tag is not changed.

<script>
    window.onscroll = function (ev) {
        if ((window.innerHeight + window.scrollY) >= $(document).height()) {
            console.log('bootom')
            $('#scroll_id').attr('onClick', '');
            $('#scroll_id').attr('onClick', 'scroll_top()');
        }
    }
</script>

do some body tell me where is the error ? why it's not working?

Upvotes: 0

Views: 94

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337700

Using the on* event attributes is considered bad practice - and amending them at runtime is worse.

A much better solution is to use a single unobtrusive event handler which determines the current scroll position of the page and moves up/down as necessary, like this:

$(function() {
  $('#scroll_id').click(function(e) {
    e.preventDefault();
    var $win = $(window);
    var scrollTarget = $win.height() + $win.scrollTop() >= $(document).height() ? 0 : $win.scrollTop() + $win.height()
    $("html, body").animate({
      scrollTop: scrollTarget
    }, 600);
  });
});
.scroll {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
}

#content {
  height: 1000px;
  position: relative;
}

#content div {
  position: absolute;
}

#content .top {
  top: 20px;
}

#content .middle {
  top: 500px;
}

#content .bottom {
  bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll">
  <a href="#" id="scroll_id">click me</a>
</div>
<div id="content">
  <div class="top">top</div>
  <div class="middle">middle</div>
  <div class="bottom">bottom</div>
</div>

Upvotes: 1

test_124
test_124

Reputation: 1403

Syntax Error:

<a onclick="scroll_down()" href="#" id="'scroll_id"> 

it should be

     id="scroll_id"> 

(removed extra ')

Upvotes: 0

Related Questions