1

I'm currently developing a website for an university course (Link: http://divedesigns.com/demo/btw17) and there's an issue I'm not able to solve on my own. I have a "back-to-top" button. With jQuery it lets the page scroll up smoothly.

HTML

<a id="back-to-top" href="#"><i class="fa fa-chevron-circle-up" aria-hidden="true"></i></a>

The following code in my script.js file works fine on the homepage of my website. Unfortunately this doesn't work on any of my subpages.

jQuery

$("#back-to-top").click(function(e){
    e.preventDefault();
    $("html, body").animate({scrollTop: "0"});
});

Do you have any suggestions?

j08691
  • 204,283
  • 31
  • 260
  • 272
Niklas Buschner
  • 354
  • 1
  • 3
  • 19
  • I'm not sure but, your first page include `subpages-script.js` and not the others. Can you test that ? Also, it is better to put your scripts in the bottom of the page (before the closing `

    ` tag)

    – Dipiks Jan 27 '17 at 15:46
  • The
    content seems to be injected dynamically in subpages (look at original html sources of main and sub pages). Do you maybe just have to attach the event again after the injection, is it maybe just detached or not attached?
    – Gunnar Jan 27 '17 at 15:50
  • Along the same lines as @GilleQ., try moving the scroll functionality to `subpages-script.js`. When I just inspect full source in Chrome, the `#back-to-top` element doesn't show up as `
    ` and `
    – Alexander Staroselsky Jan 27 '17 at 15:51

2 Answers2

2

The click-listener seems to be attached to this link-element too early (#back-to-top), because when you attach this event-listener in your console afterwards, it works. Have you already tried on method?:

$( document ).on( "click", "#back-to-top", function(e) {
  e.preventDefault();
  $("html, body").animate({scrollTop: "0"});
});

In this example it is explained why you have to use this approach.

Hope this helps as well!

Community
  • 1
  • 1
Blauharley
  • 4,186
  • 6
  • 28
  • 47
1

Ok, I've tried to run your code manually in the console and it works fine, just as in the main page. So I went to the HTML structure and I can see that you are loading the footer after loading the script.js which contains

$("#back-to-top").click(function(e){
   e.preventDefault();
   $("html, body").animate({scrollTop: "0"});
});

So basically when the browser runs the code above the element #back-to-top doesn't exist yet and that's why it doesn't work, all you have to do is put your script.js after the subpages-script.js.

Hope it helps!

EAragon
  • 38
  • 6