Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
clieee

ScrollTrigger to trigger background color change

Recommended Posts

Hi,

 

I have a page where I have x number of containers/divs. Some of these have defined background colors, and should thereby change body background color once they getting visible as you scroll down. But also change back to their color if user scrolls back up.

 

I'm using React and my thought was to create a custom hook that I connect to the node/container/div that should be used as trigger. That is all working fine, if that seems to be a good approach, I basically create a new ScrollTrigger every time that hook is being used.

 

However, some questions:

- I guess I have to use the callbacks for onEnter and onEnterBack in order to add/remove the body background color class?

- What should my start values be? "top top" (=if top of element hits top of viewport) if a "colored" section is a top of page? And for other sections "top bottom" (=if top of element reaches bottom of viewport)?

- If the first section on the page should set a specific background color, and then the user scrolls down a bit, the next section becomes visible = trigger color change, but then the user scrolls back up again, how can I tell if it should transition back to it's color again then? onEnterBack wont get triggered in this case..?

Link to comment
Share on other sites

1 hour ago, clieee said:

I guess I have to use the callbacks for onEnter and onEnterBack in order to add/remove the body background color class?

Sure, that works. Or you could animate the backgroundColor directly (not use classes).

 

1 hour ago, clieee said:

What should my start values be? "top top" (=if top of element hits top of viewport) if a "colored" section is a top of page? And for other sections "top bottom" (=if top of element reaches bottom of viewport)?

That makes sense. It depends on when you want it to happen :) 

 

1 hour ago, clieee said:

If the first section on the page should set a specific background color, and then the user scrolls down a bit, the next section becomes visible = trigger color change, but then the user scrolls back up again, how can I tell if it should transition back to it's color again then? onEnterBack wont get triggered in this case..?

It'd probably make more sense to use the onEnter and onLeaveBack for this sort of thing. You can save the colors to a list and use that.

 

I did this same sort of thing in this thread (without React):

This thread is very similar as well:

 

  • Like 3
Link to comment
Share on other sites

  • 1 year later...

guys, can you help me?
I want to change the background color when I click

I use the code: 

gsap.utils.toArray(".section").forEach(function (elem) {

    var color = elem.getAttribute('data-color');

    ScrollTrigger.create({
        trigger: elem,
        start: 'top 30%',
        end: 'bottom 30%',
        markers: false,
        onEnter: () => gsap.to('main', {
            backgroundColor: color,
            duration: 1.4
        }),
        onLeave: () => gsap.to('main', {
            backgroundColor: '#fef9ef',
            duration: 1.4
        }),
        onLeaveBack: () => gsap.to('main', {
            backgroundColor: '#fef9ef',
            duration: 1.4
        }),
        onEnterBack: () => gsap.to('main', {
            backgroundColor: color,
            duration: 1.4
        }),
    });
});


this is to change the background color when switching to another section

Now I want to use simple code: 

const elem = document.querySelector(".section.hero");
const switcher = document.querySelector(".switch-theme");

switcher.addEventListener('click', function() {
  if (elem.hasAttribute == ('data-color', "#FEF9EF") {
    this.setAttribute = ('data-color', "#000000");
  }
});

To click on the element to change the color of my section, but I get an error instead

Is it possible to change the data-color dynamically somehow?

 

Link to comment
Share on other sites

This is definitely wrong:

// BAD
if (elem.hasAttribute == ('data-color', "#FEF9EF") {
  this.setAttribute = ('data-color', "#000000");
}

// GOOD (maybe? I'm not sure what your intent is)
if (elem.getAttribute('data-color') === "#FEF9EF") {
  elem.setAttribute('data-color', "#000000");
}

You could also simplify your ScrollTrigger:

// OLD
ScrollTrigger.create({
  trigger: elem,
  start: 'top 30%',
  end: 'bottom 30%',
  markers: false,
  onEnter: () => gsap.to('main', {
    backgroundColor: color,
    duration: 1.4
  }),
  onLeave: () => gsap.to('main', {
    backgroundColor: '#fef9ef',
    duration: 1.4
  }),
  onLeaveBack: () => gsap.to('main', {
    backgroundColor: '#fef9ef',
    duration: 1.4
  }),
  onEnterBack: () => gsap.to('main', {
    backgroundColor: color,
    duration: 1.4
  }),
});


// NEW
ScrollTrigger.create({
	trigger: elem,
	start: 'top 30%',
	end: 'bottom 30%',
	onToggle: (self) => gsap.to('main', {
		backgroundColor: self.isActive ? color : '#fef9ef',
		duration: 1.4
	})
});

If you need more help, please provide a minimal demo in CodePen or something like that. 

 

Happy tweening!

Link to comment
Share on other sites

On 1/16/2022 at 1:07 AM, OSUblake said:

Hi @GeorgeErshov

 

Can you create a new topic with your question and include a minimal demo? Thanks!

 

Hi, sorry it took so long

Here's a simple demonstration. I want to click-me button (class='change-color') to change the color of all sections that have data-color, to a different color (the designer came up with a dark theme)
 

See the Pen RwLXmwB by GeorgeDesign2020 (@GeorgeDesign2020) on CodePen

Link to comment
Share on other sites

Hi George,

 

I'm still not sure what you are trying to do. You have ScrollTrigger code that is changing the background, but now you you are saying you want a button to change to background, so which is it?

Link to comment
Share on other sites

14 hours ago, OSUblake said:

Привет Джордж,

 

Я все еще не уверен, что вы пытаетесь сделать. У вас есть код ScrollTrigger, который меняет фон, но теперь вы говорите, что хотите, чтобы кнопка менялась на фон, так что же это?

I want to change the attributes of the sections by clicking on this button, I want the data-color to change

For example: class='section s-1' has data-color='#838C8B'.
By clicking on the button, I want to change the data-color='#000000'
make the background black, and in the section class='section s-2' make the data-color='#ffffffff'

Here's the site I'm working on, here the designer wants me to change the colors to contrasting (black and white) for the visually impaired when I click on the eye

https://function-x-siberia-site.webflow.io/

 

 

Снимок экрана 2022-01-25 в 11.25.21.png

Link to comment
Share on other sites

Hi George! 

 

You haven't got any logic in place for the button at all. What have you tried so far?

 

You'll likely need to toggle a boolean like so.

 

let contrastMode
button.addEventListener(click, (e) => {
 contrastMode = !contrastMode;
  
 if(contrastMode) {
   // make sections black and white
 } else {
   // make sections original colors
 }
})

 

If you give it a go we can help to nudge you in the right direction, but unfortunately we don't offer free custom solutions in these forums.

 

The GSAP part would be similar to what you have here already - just a tween that changes color. The tricky bit will be the logic of what happens with the scrollTrigger when the state changes - if you need scrollTriggered sections that change color too you'll need to use variables for the colors, update them in your logic loop and call scrollTrigger.refresh() to update the values
 

 

  • Like 2
Link to comment
Share on other sites

7 hours ago, Cassie said:

Hi George! 

 

You haven't got any logic in place for the button at all. What have you tried so far?

 

You'll likely need to toggle a boolean like so.

 

let contrastMode
button.addEventListener(click, (e) => {
 contrastMode = !contrastMode;
  
 if(contrastMode) {
   // make sections black and white
 } else {
   // make sections original colors
 }
})

 

If you give it a go we can help to nudge you in the right direction, but unfortunately we don't offer free custom solutions in these forums.

 

The GSAP part would be similar to what you have here already - just a tween that changes color. The tricky bit will be the logic of what happens with the scrollTrigger when the state changes - if you need scrollTriggered sections that change color too you'll need to use variables for the colors, update them in your logic loop and call scrollTrigger.refresh() to update the values
 

 

Hi, yes i already tried to do different things with both jquery and javascript
Please look now, I added some very simple code

$('.change-color').click(function() {
  $("#id").attr("data-color","#000000"); 
  console.log('change dark-mode');
  scrollTrigger.refresh()
})

 

 

See the Pen RwLXmwB by GeorgeDesign2020 (@GeorgeDesign2020) on CodePen

 

But nothing happens, I seem to be calling the scrolltrigger.refresh() method incorrectly

Link to comment
Share on other sites

Hi George,

 

This is will be only read 1 time. That's just how JavaScript works.

 

var color = elem.getAttribute('data-color');

 

If you need it to update, you're going to have to provide a way to update the value inside of the forEach. I just used map to create an array of functions that will update the color value and set the background if the trigger is active.

 

See the Pen mdqdqNV by GreenSock (@GreenSock) on CodePen

 

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

11 hours ago, OSUblake said:

 

Thank you so much! 
It works great!

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

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

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×