sgkdnay sgkdnay - 2 months ago 7
CSS Question

jquery div width Height re-position (dynamic)

I am accustomed to FIXED Height/Width aspect ratio, but now I'm attempting dynamic Height/Width ratio. I for the life outta me cannot think how to implement this with the dynamic.

For instance, at H:800,W:800 (Fixed Map), the dots (emulates as coord) @ 0,0 - 0,800 - 400,400 - 800,0 - 800,800, I know exactly where the dot goes with CSS(TOP LEFT)

With this map is 800x1000: I need to think HOW i can MAKE the dot go at: 0,0 - 0,1000 - 400,500 - 1000,0 - 1000,1000

or say map is 900x900: dot goes at: 0,0 - 0,900 - 450,450 - 900,0 - 900,900, so on, I think we get the idea.

This is what i used to calculate the size of the DIV to prepare myself for Dynamic:

var AH = $('#MapBox').outerHeight(true);
var AW = $('#MapBox').outerWidth(true);


for fixed dot, I used but cannot figure out dynamic:

tX = parseFloat(item.FieldID % 800);
tY = parseInt(item.FieldID / 800);


Thanks in advance!

Answer

There are many ways to achieve your goal. Depending on the source of your coordinates, you can fix this in javascript or css. (And I see your using MapBox, perhaps the thing you want to do is also available within that library, but that is out of scope for this question).

Javascript

Lets say your source is a list of coordinates:

var coords = [
  [0, 0],
  [0, 800],
  [400, 400],
  [800, 0]
  [800, 800]
]

These coordinates are based on a field of size 800x800. Lets call this the baseSize.

baseSizeX = 800;
baseSizeY = 800;

Also define a target size:

targetSizeX = 800; // or $('#MapBox').outerWidth(true);
targetSizeY = 1000; // or $('#MapBox').outerHeight(true);

Now you need to calculate a scale factor that you can apply to your coordinates. This is simply the ratio: base / target.

scaleX = targetSizeX / baseSizeY; // 800 / 800 = 1
scaleY = targetSizeY / baseSizeY; // 1000 / 800 = 1.25

To finish up, just scale each coordinate:

const X = 0;
const Y = 1;

for( coord of coords ){
  coord[X] = coord[X] * scaleX;
  coord[Y] = coord[Y] * scaleY;
}

CSS

In case your coordinates are static (eg. you want a dot in the left top, center bottom, right bottom etc) you can also just use CSS, no scripts needed. You can think of the coordinates as percentages; given a container of 800x800

  • (0, 0) equals top: 0%; left: 0%
  • (800, 0) equals top: 100%; left: 0%
  • (400, 400) equals top: 50%; left 50%

You could define the following CSS:

.container {
  position: absolute;
  width: 800px;
  height: 800px;
}

.container .first-dot {
  position: absolute;
  top: 0%;
  left: 0%;
}

.container .second-dot {
  position: absolute;
  top: 50%;
  left: 50%;
}

/* Etc. */
Comments