0

I have the following JavaScript code:

const cardWrapper = document.querySelectorAll('.card__wrapper');

cardWrapper.forEach((cont) => {
    const cards = cont.querySelectorAll('.card');
    const cardBg = cont.querySelectorAll('.card-bg');
    const cardText = cont.querySelectorAll('.card__text');
    
    cardBg.style.transition = 'all .3s ease-out';
    cardText.style.transition = 'all .3s ease-out';
  
    cards.forEach((el, i) => {
        el.addEventListener('mouseenter', () => {
            cardBg[i].style.maxHeight = '100%';
            cardText[i].style.maxHeight = '100%';
        });

        el.addEventListener('mouseleave', () => {
            cardBg[i].style.maxHeight = '56px';
            cardText[i].style.maxHeight = '56px';
        });
    });
});

I need to take these 2 styles out of events and leave them in the JS code, not put them in the CSS file.

cardBg.style.transition = 'all .3s ease-out';
cardText.style.transition = 'all .3s ease-out';

The way I did in the code above doesn't work. What's wrong with it?

2
  • This is not an 'answer' to your question, so just leaving a comment: it really looks like what you're doing (basically a hover effect?) could be achieved with plain css? Commented Mar 2, 2022 at 11:50
  • Yes, that's right. But I needed to achieve this with JS. Commented Mar 2, 2022 at 12:23

1 Answer 1

2

It's because your cardBg and cardText are arrays. You need to loop over them like you did for cards if you want to change their CSS style. Or if you sure you only have one element you can do the following:

cardBg[0].style.transition = 'all .3s ease-out';
cardText[0].style.transition = 'all .3s ease-out';

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.