lpetrucci
lpetrucci

Reputation: 1699

How to set absolute position in jQuery

I'm trying to set the left position of an absolute element with jQuery.

This is what I've tried:

var leftPercentage = 10 + '%';
var singleGrate = grateOne.append('<div class="single-grate"><div>');
singleGrate.css(left, leftPercentage);

I have also tried removing the percentage and using px but it didn't work.

I've also tried using offset, but while that works, it sets the element depending on the page, not the element containing the div I want to position.

I'm just lost as to how to get this to work. I followed a bunch of questions from stackoverflow but I'm pretty sure they are all very outdated because none of them worked.

What am I supposed to do here?

EDIT: Here's the codepen I am currently working on https://codepen.io/creativiii/pen/gyKjrm

Upvotes: 0

Views: 52

Answers (2)

lpetrucci
lpetrucci

Reputation: 1699

So apparently the problem was with append(), as it doesn't actually point to the appended element.

I changed my code to append the element to:

var singleGrate = $('<div class="single-grate"><div>').appendTo(grateOne);

Now singleGrate actually returns an element that I can then change with css().

Upvotes: 0

Marco Sanchez
Marco Sanchez

Reputation: 788

In the last line. You need to put "" to left so the code will be:

singleGrate.css("left", leftPercentage);

Upvotes: 1

Related Questions