angularparallax.js

Using Parallax.js in Angular throws error "Cannot read property 'getAttribute' of null"


I am using parallax.js (https://github.com/wagerfield/parallax) for an mouseover parallax effect. I added the script to my angular app via cdn and script tag. In the console it shows this error:

 Uncaught TypeError: Cannot read property 'getAttribute' of null
    at Object.data (parallax.js:23)
    at new t (parallax.js:161)
    at (index):36

I tried to install the library via npm and import it in the ts file but that didnt work.

Here is my index.html:

<body>
  <app-root></app-root>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/3.1.0/parallax.min.js"></script>
  <script type="text/javascript">
  var parallaxInstance = new Parallax(document.getElementById('scene'));
  </script>
</body> 

my component where i use it:

 <ul class="background-video" id="scene">

  <li class="layer" data-depth="0.7"><img src="/assets/parallax/ebene1.png" alt="" srcset=""></li>
  <li class="layer" data-depth="0.5"><img src="/assets/parallax/ebene2.png" alt="" srcset=""></li>
  <li class="layer" data-depth="0.3"><img src="/assets/parallax/ebene3.png" alt="" srcset=""></li>

 </ul>


Solution

  • Might be some things happening in the wrong order due to JS async nature as I'm able to get it running in this example (it's not working on stackblitz due to dependency issue but running it locally on your comp works).

    First of from your html example remove nodes except root node and add your parallax component in it like so:

    index.html:

     <body>
          <app-root></app-root>
     </body>
    

    app.html:

    <parallax></parallax>
    

    Since your using it in a component, in your ng-app you should init the lib in the actual component by injecting it into the app bundle like so in your angular.json:

    "options": {
        "scripts": [
                      "./node_modules/parallax-js/dist/parallax.min.js"
                   ]
    }
    

    and importing/initing it in your .ts file like so:

    import Parallax from 'parallax-js'
    import { Component,AfterContentInit } from '@angular/core';
    
    export class ParallaxComponent implements AfterContentInit {
    
      constructor() { }
    
      ngAfterContentInit() {
    
        const scene = document.getElementById('scene');
        const parallaxInstance = new Parallax(scene, {
          relativeInput: true
        });
    
      }
    
    }