16

How can set the offset using JavaScript ?

1
  • 20
    var offset = 24; Commented Dec 23, 2009 at 7:47

3 Answers 3

25

You set the left and top CSS values.

With jQuery

$("#myEl").css({"position":"absolute","left":"100px","top":"100px"});

Vanilla JavaScript

var myEl = document.getElementById("myEl);
myEl.style.position = "absolute";
myEl.style.left = "100px";
myEl.style.top = "100px";
Sign up to request clarification or add additional context in comments.

Comments

2

If the container is scrollable, the scroll method may be more in line with the specification. If not, it has to be solved by setting the absolute positioning

Element.scroll() - Web APIs | MDN

// Put the 1000th vertical pixel at the top of the element
element.scroll(0, 1000);

// use optionas
element.scroll({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

Comments

0

You could also add a class, e.g.

Jquery: $("p:last").addClass("selected");

Javascript: Someone has posted a JS function here - http://bytes.com/topic/javascript/answers/542128-can-javascript-add-new-style-class

You would then need to make sure that 'selected' was defined in your style sheet. The relevant CSS properties are:

top left margin padding

You probably want a combination of margin (offset outside element) and padding (offset inside element).

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.