Jump to content

applying a .js file parallax animation to a background image?

Recommended Posts

Site URL: https://www.byhutch.com

Hi,  

I designed a site on Cargo for an artist and I would like to use the same .js file to animate a background image on squarespace but I am not sure how to implement it.  I have added the image as a background, added the script to the footer injection and i have this code in the css. 

 

///testing parallax 
section[data-section-id="629bd39be10a3e30d5e26b57"] {
  .section-background img {
    ???????
  }
}

 

here's the script....

 

const sections = document.querySelectorAll("section")
const bodyTag = document.querySelector("body")

const addMovement = function () {
  const topViewport = window.pageYOffset
  const midViewport = topViewport + (window.innerHeight / 2)
  
  // lets find the middle of each section
  // (section, index) => {}
  sections.forEach((section, index) => {
    const topSection = section.offsetTop
    const midSection = topSection + (section.offsetHeight / 2)
    
    // how far away is the section from the visible area of the page
    const distanceToSection = midViewport - midSection
    
    // pick the tags to parallax
    const image = section.querySelector("img")
    const contentTag = section.querySelector("div")
    
    // weight down this distance
    let rotation = distanceToSection / 100
    let contentDist = -1 * distanceToSection / 2
    
    // for all the even sections, rotate the other way
    // is the index divisible by two
    // is the index's remainder zero?
    // the modulo operator 5 % 2 = 1, 4 % 2 = 0
    if (index % 2 == 1) {
      rotation = rotation * -1
    }
    
    // apply some parallax
    image.style.transform = `rotate(${rotation}deg)`
    
    contentTag.style.top = `${contentDist}px`
    contentTag.style.transform = `rotate(${-1 * rotation}deg)`
    
    // check the background
    if (distanceToSection > -100) {
      const dataBackground = section.getAttribute("data-background")
      bodyTag.style.backgroundColor = dataBackground
    }
  })
}

addMovement()

document.addEventListener("scroll", function () {
  addMovement()
})

window.addEventListener("resize", function () {
  addMovement()
})

any ideas? @tuanphan @creedon  

The url I am trying to implement is just a trial site 

https://radish-hexaflexagon-chhx.squarespace.com/parallax

pw:demo 

 

Edited by failbetter
forgot to tag
Link to comment
  • Replies 1
  • Views 219
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.