0

I'm trying to set top using java script. I logged the top of the menu after adding top style, but it does not work.

How to style top using js??

Here is my codes

const top = (document.getElementById(element).offsetTop);

top is a number not String

document.getElementById('contentMenu').style.top = top.toString();
    
console.log("menu" +document.getElementById('contentMenu').style.top);   //output: menu

2
  • 3
    You need to add a unit to the the value you're assigning. For example px, em or %. Commented Sep 26, 2021 at 16:57
  • If top variable in your script is global, then it refers to the topmost browser window. window.top is a non-configurable DOM property, you should see an error on the line const top = .... Commented Sep 26, 2021 at 17:12

1 Answer 1

1
const top = document.getElementById(element).getBoundingClientRect().top;
document.getElementById('contentMenu').style.top = `${top}px`;
console.log(document.getElementById('contentMenu').style.top)
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.