pixelcog / parallax.js

Simple parallax scrolling effect inspired by Spotify.com implemented as a jQuery plugin
MIT License
3.53k stars 840 forks source link

Only works from <script> tags directly on the page #283

Closed matronator closed 4 years ago

matronator commented 5 years ago

I have the following folder structure:

├─ assets
│  ├─ css
│  │  └─ main.css
│  ├─ img
│  │  └─ parallax-bg.jpg
│  └─ js
│     ├─ main.js
│     └─ parallax.min.js
├─ about
│  └─ index.php
├─ footer.html
├─ header.html
└─ index.php

I want the parallax background on index page in the about folder. When I try to call the .parallax({imageSrc: "/assets/img/parallax-bg.jpg"}); from main.js in the document.ready() function, the image always loads as undefined.

I figured it must be a path issue, but I tried copying the parallax-bg.jpg to every single folder and modifying the path to the image in every way I could think of, but it still resolved as undefined.

However, when I removed the parallax() function from main.js and put it directly at the bottom of the page in <script> tags, now it finally worked and the image loaded. I don't mind having the parallax function in the script tags, but would prefer to call it from within the main.js.

What could be the issue? Only thing (other than bad path to image) I can think of is that the .parallax-window element is in header.html which is being loaded with PHP via include().

Luckyfella73 commented 4 years ago

Yes it looks like a path issue. Without knowing this library I guess you could solve the problem by setting the base-directory by script like this:

var bgImagePath = window.location.protocol + '//' + window.location.hostname + '/assets/img/';`

// or es6
const bgImagePath = ${window.location.protocol}//${window.location.hostname}/assets/img/`;

// and then use the variable here:
.parallax({
    imageSrc: bgImagePath + 'parallax-bg.jpg'
});
matronator commented 4 years ago

Great, this solved it. I didn't even thought about using the location variables. Thank you!