user2832871
user2832871

Reputation: 9

Why doesn't my intuitive declaration work?

var get = document.getElementById("t3");
get.style.visibility="visible";

var get = document.getElementById("answerbutton");
get.style="visibility:hidden";

var get = document.getElementById("spacer");
get.style="margin-top:160px";

var get = document.getElementById("spacer");
get.style.margin-top="160px";

I’m fairly new to JavaScript so excuse my naivety. The top three declarations work but if I use the forth one ( as I did originally ) it doesn’t. So, while I now know how to get the margin-top to change on the click of a button can someone please enlighten me as to what is wrong with the forth one.

Thanks

Upvotes: 0

Views: 47

Answers (2)

Quentin
Quentin

Reputation: 943579

You can't have a hyphen in an identifier (since it becomes a subtraction operator).

Property names when using dot-notation are identifiers.

The mapping of JavaScript properties and CSS properties is to use camelCase instead of hyphenation.

So: marginTop not margin-top.

Upvotes: 3

Mike Samuel
Mike Samuel

Reputation: 120516

get.style.margin-top is an arithmetic expression which cannot be the left-hand-side of an assignment. It's like saying (x - y) = z which might work in Prolog but not in JavaScript, and is not what you want to do in any event.

Try

get.style.marginTop = ...

instead per How do I set the margin of an object with javascript?

Upvotes: 4

Related Questions