0

I have created span element <span id="scroll-top"></span> which displays a Top-arrow image when the user scrolls down and scrolls the user to top when clicked, My JS function works perfectly when you run it as an HTML project but angular 9 does not pick it up(I'm converting my HTML project to angular if you're wondering ), I double-checked my links(css and js to angular) and they are fine, strangely I have used many js functions but this is the only one angular 9 skips. What could be the issue?

CSS-

 scroll-top{width:40px;height:40px;z-index:99;position:fixed;bottom:100px;right:30px;display:none;cursor:pointer;background:url(../images/slider/top.png) no-repeat}

JS-

$(document).ready((function(){$(window).scroll((function(){$(this).scrollTop()>40?$("#scroll-top").fadeIn():$("#scroll-top").fadeOut()})),$("#scroll-top").click((function(){$("html, body").animate({scrollTop:0},1e3)}))}));

Have I used a syntax that angular 9 doesn't support?

  • Well, the element `#scroll-top` may not be rendered when the `ready` event fires. Angular is working off a different rendering life cycle. This is a common issue when trying to put jQuery into Angular projects. At minimum instead, make the scroll to top button/element an angular component and use a click event to scroll to top. Also you should consider using [DOCUMENT](https://stackoverflow.com/questions/37521298/how-to-inject-document-in-service) – Alexander Staroselsky May 14 '20 at 16:42
  • Otherwise, if you must use jQuery, you could consider using [Event Delegation](https://learn.jquery.com/events/event-delegation/) to delete from an element such as body that will for sure exist on `ready`. – Alexander Staroselsky May 14 '20 at 16:49
  • If convert the button to an angular component, does that mean I can execute the scroll to top function through js ? – Ashen Jayawardena May 14 '20 at 17:38
  • Taking a step back, do you understand the issue trying to query `#scroll-top` in this Angular application? Considering that Angular renders component HTML in it's own life cycle? The issue being, the element may and probably does not exist at the moment jQuery `ready` (different lifecycle) executes? – Alexander Staroselsky May 14 '20 at 18:08
  • Short answer: yes. That's jQuery, not Angular. You'd need to declare the $ in your component: `declare var $: any;` and include the path to jQuery in the scripts block of your angular.json. – ColemanTO Aug 18 '21 at 19:00

0 Answers0