简体   繁体   中英

JQUERY / JS / HTML - Scroll to div not working on JQuery 3.1.1

i've just changed my Jquery version to 3.1.1 and all of sudden some of my scripts stopped working .

I've already worked out most of them but still cannot resolve the issue with the scroll to anchor script ...

Here it is:

$(document).on('click', 'a', function(event){
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
});

It just won't work now, any idea how to work it out?

Here's the html script part too:

<a class="scrolltomain" href="#content-wrapper">
<span>
<img id="scroller" src="img/scrolldown-1.gif"></img>
<center>Kliknij<br>lub<br>przewiń</center>
</span>
</a>

Would be really grateful if someone could help me.

BTW, chrome console wouldn't show any errors.

  • There is no such tag as </img> . Image tags are self closing, a la: <img src=" " />

And you need to define the location before the animation. Simply define a variable before the animate() function and then call the variable within the function.

 $(document).on('click', 'a', function(e) { e.preventDefault(); var thisRef = $(this).attr('href'); $('html, body').animate({ scrollTop: $( thisRef ).offset().top }, 500); }); 
 a { display: block; text-align: center; height: 400px; } #content-wrapper { background: red; height: 300px; margin-top: 500px; color: #fff; font-size: 2em; line-height: 1.6; text-align:center; padding: 20px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="scrolltomain" href="#content-wrapper"><img id="scroller" src="http://placekitten.com/25/25" /><br />Kliknij<br />lub<br />przewiń</a> <div id="content-wrapper"> Content </div> 

try .delegate() instead of .on().... .on() is new to Jquery 1.7 so if you went backwards then you'll need to use delegate or live.

.delegate() vs .on()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM