Reputation: 2823
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";
Upvotes: 0
Views: 1667
Reputation: 207
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";
}
}
Upvotes: 1
Reputation: 524
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;}
Upvotes: 1