0

I have a div that on click it expands or closes, I would also like to change the top position of a different fixed div depending on the click state of the original div.

For example If original div is expanded I would like div 2 to have top:10px

If closed div 2 to have top:0

This is the current toggle function to expand or close the div

<a href="#" class="toggle" onclick="dropDownMSG(); this.parentNode.classList.toggle('open');return false;">
                    <img src="/Static/images/header-logo-top.png" alt="Informa logo"/>
                </a>

then bellow I have

function dropDownMSG() {
         document.getElementById("mySidenav").style.top = "10";
    }

However this only adds top:10px on click, so on toggle again that closes the div the top dose not reset to 0.

I need a way to say:

that if toggle open then

document.getElementById("mySidenav").style.top = "10";

Else

document.getElementById("mySidenav").style.top = "0";
Beep
  • 2,737
  • 7
  • 36
  • 85

2 Answers2

1

You can check current top value in an if else block and update accordingly

function dropDownMSG() {
    const element = document.getElementById("mySidenav");
    if (element.style.top === '10') {
        element.style.top = '0';
    } else {
        element.style.top = '10';
    }
}

For better performance, I'd advise you to use a classes.

function dropDownMSG() {
    const element = document.getElementById("mySidenav");
    //        if (element.style.top === '10') {
    //            element.style.top = '0';
    //        } else {
    //            element.style.top = '10';
    //        }

    if (element.className.indexOf('expand') === -1) {
        element.className += 'expand';
    } else {
        element.className = element.className.replace('expand', '');
    }
}

and add a css class

.expand{top:10px;}
vijay krishna
  • 514
  • 4
  • 14
  • Hmm kinda fixes one but brakes the other. the second div now adds top and removes top. perfect but now the main div dose not expand on click. – Beep Oct 16 '18 at 11:10
  • Yes. But, I think you can move that code also to **dropDownMSG()** function. Also, I think you can replace return with `event.preventDefault()` like this [post] (https://stackoverflow.com/a/128966/6762052) – vijay krishna Oct 16 '18 at 11:16
  • will try and let you know. – Beep Oct 16 '18 at 11:19
  • 1
    Also, don't forget to bind this in anchor tag like this `` – vijay krishna Oct 16 '18 at 11:31
1

use html data-attribute to assign the state then change it on your script on click.

HTML

 <a href="#" class="toggle" onclick="dropDownMSG(this)">
   <img src="/Static/images/header-logo-top.png" alt="Informa logo"/>
 </a>

CSS

  function dropDownMSG(elem){
    if(elem.dataset.state === "open"){
      elem.dataset.state = "close";
      document.getElementById("mySidenav").style.top = "10px";
    }
    else{
      elem.dataset.state = "open";
      document.getElementById("mySidenav").style.top = "0";
    }
  }