RyanIndustries8
RyanIndustries8

Reputation: 157

Moving the placement a div in JavaScript

I have a function that I built (it's kind of bare bones at the moment), but I can't find how to move the object when it expands onMouseOver so it doesn't move the others on the page, is this possible?

function expandbox(x) {
    x.style.height = "100px";
    x.style.width = "100px";
}

function returnbox(x) {
    x.style.height = "80px";
    x.style.width = "80px";
}

Upvotes: 0

Views: 96

Answers (2)

xec
xec

Reputation: 18024

If you want to keep the element in document flow, set it to position: relative and move it around using top and left, which will be relative to where the element started out.

I'll use the same type of function you made, to demonstrate:

function moveBox(x) {
    x.style.position = "relative";
    // move 20px down and 10px left from original position
    x.style.top = "20px";
    x.style.left = "-10px";
}

If you want to remove the box from document flow (following elements will not be affected by its presence) set its position to absolute instead. Top and left values will be relative to its closest positioned ancestor (or <body> if there is none, as i assume in the comment below)

function moveBox(x) {
    x.style.position = "absolute";
    // position box 20px from top of body
    x.style.top = "20px";
    // and 10px from the left
    x.style.left = "10px";
}

An element is considered to be "positioned" if it has a value other than static (default, read more here), so if you want to control what the absolutely positioned element is relative to, you can give a container element position: relative

Upvotes: 1

gdoron
gdoron

Reputation: 150253

Make the element position relative inside a relative container, then change it's dimensions.

Make sure to give it higher z-index.
Place it with left,right,top,bottom properties of style.

Upvotes: 1

Related Questions