Evan
Evan

Reputation: 95

How to change div position with Javascript?

So, here's what I've got so far: https://jsfiddle.net/625qofbe/1/

What I want is for the position of the "about" div, containing the Lorem Ipsum text and what should be an "X" symbol (I dunno how to link images into JSfiddle, sorry) to move, say, 30 pixels to the left when the user clicks on the "About" button in the top-left. Here's the Javascript I've been trying to do that with:

document.getElementById("button").addEventListener("click", AboutOnScreen);

function AboutOnScreen() {
    document.getElementById("about").style.left = 30px;
}

I've been Googling and checking the Javascript against successful little experiments like this for ages, but nothing's worked and I can't see what I'm doing wrong here.

The end goal is to have the Lorem text hidden offscreen, slide in when the user clicks on About, then slide offscreen once they click the X icon. I was sure I knew in theory how do that, but I've hit a snag on step one.

EDIT: Thanks for the help guys, but weirdly the two solutions that both worked fine in JSfiddle didn't work even when I copy/pasted the code back into Sublime Text. I did, however, get the thing working by removing the "addEventListener" line and adding "onclick='AboutOnScreen()'" into the div tag for the About button. The "addEventListener" line sent up an error notification when I checked the page source (as suggested by Arindam) so I got rid of it entirely. The weird thing is I'm sure I tried that before with no success, so the solution to this head-scratcher turned out to be a confluence of all the answers below.

Upvotes: 2

Views: 1872

Answers (2)

zer00ne
zer00ne

Reputation: 43880

When setting the inline style of an element's distance value in plain JS, it's a combo of Number and String or String. So the value can be: '430px' or 430+'px'.

document.getElementById("button").addEventListener("click", AboutOnScreen);

function AboutOnScreen() {
  document.getElementById("about").style.left = 430 + 'px';
}

You said move to the left by 30px, which is interpreted (at least to me), as 30px from the element is positioned currently. So it was left: 400px so the value should be 430px if moving 30px to the left.

FIDDLE

Upvotes: 1

Arindam
Arindam

Reputation: 342

As @Rikard mentioned, do the following:

document.getElementById("button").addEventListener("click", AboutOnScreen);

function AboutOnScreen() {
    document.getElementById("about").style.left = '30px';
}

Which should get the snippet working. As for the sliding animation, you can use CSS3 (assuming browser support) to quickly add animation for your page.

A good resource for CSS3 animations would be http://www.w3schools.com/css/css3_animations.asp

Good luck and have fun!

Upvotes: 2

Related Questions