Home > OS >  javascript slide in div on image click?
javascript slide in div on image click?

Time:01-06

I'm trying to get the yellow div to slide up when clicking on the tree icon in the modal possibly without jQuery but I can't get it to work.

You can see the page I'm building here by clicking the first icon from left https://vivere-albero-verona.netlify.app/

I've tried different solutions but here's the code I have right now

html:

<div id="alberi" >
      <div id="acero">
          <img src="./images/tree.png">
          <h1>ACERO CAMPESTRE</h1>
          <h2>Altezza: 7,0m</h2>
          <h2>Ingombro: 2,0m</h2>
          <h2>Fornitore</h2>
      </div>
</div>

css:

.alberi{
    background-color: green;
    display: flex;
    height: 0px;
    width: 90.9%;

    position: absolute;
    bottom: 0;
    border-bottom-left-radius: 30px;
}

.slided{
    height: 270px;}

js:

const sezionealberi = document.querySelector('#alberi')
const pulsantealberi = document.querySelector('#m-tree')

pulsantealberi.addEventListener('click', primavera)

let mezzastagione = 1;

function primavera()
{
    if(mezzastagione == 1) 
    { 
        sezionealberi.innerHTML = `<class = "alberi slided">`;
        mezzastagione = 0;
    }
    
    else{
        sezionealberi.innerHTML = `<class = "alberi">`;
        mezzastagione = 1;
    }
}

CodePudding user response:

You shouldn't be assigning to innerHTML to change a class attribute, and should be using classList instead:

function primavera()
{
    if(mezzastagione == 1) 
    { 
        sezionealberi.classList.add('slided');
        mezzastagione = 0;
    }
    
    else{
        sezionealberi.classList.remove('slided')
        mezzastagione = 1;
    }
}

CodePudding user response:

The other answer has provided great insights about your code, but I would like to help you solve the "Cannot read property 'classList' of null" problem.

You're trying to get the element before it's loaded, use DOMContentLoaded to get the element after it's loaded on the page. Refer to the code bellow:

window.addEventListener('DOMContentLoaded', () => {
    const sezionealberi = document.querySelector('#alberi')
    const pulsantealberi = document.querySelector('#m-tree')

    // mezzastagione == 1 is redundant use a boolean instead
    let mezzastagione = true;

    const primavera = () => {
        if(mezzastagione) { 
            sezionealberi.classList.add('slided');
            mezzastagione = false;

        } else {
            sezionealberi.classList.remove('slided');
            mezzastagione = true;
        }
    }

    pulsantealberi.addEventListener('click', primavera);
});

I hope it helps you out , dude!

  • Related