0

I've got some code where when a button is clicked it toggles an active class. At the same time I need to set a top-margin on the toggled element, which also needs to be removed once the button is clicked again and the toggled class is removed. I can't set the top-margin as part of the active class as I need to get the value of the margin dynamically by checking the height of another element.

This is the code I've got to toggle the class and add the margin

var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;

sizeBtn.addEventListener("click", function(e) {
    sizeItems.classList.toggle('size-toggle--active')
    sizeItems.style.marginTop = "-" + elementHeight + "px";
});

However, obviously this doesn't remove the style when the button is clicked again so basically I need to toggle the style just like the active class. Is there anyway to do this?

1 Answer 1

1

You need to check if className is there or not so the code could be:

var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;

sizeBtn.addEventListener("click", function(e) {
  if(sizeItems.classList.contains('size-toggle--active')) {
    sizeItems.classList.remove('size-toggle--active')
    sizeItems.style.marginTop = null;
  }
  else{
    sizeItems.classList.add('size-toggle--active')
    sizeItems.style.marginTop = "-" + elementHeight + "px";
  }
});
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.