0

I am trying to create a div using javascript document.write() in a specified position .

This gives correct answer

document.write("<div style='position: absolute; left:200px; top:100px;'<h1 style='font-size:10px; color:blue;'> HELLO WORLD<h1></div>");

but whenever I use a javascript variable in top and left, left gives correct position but top don't

document.write("<div style='position: absolute; left: " + left + "px; top: " + top + "px;'>" + "    <h1 style='font-size:10px; color:blue;'> HELLO WORLD<h1></div>"); 

How can I use a javascript variable in top?

  • 4
    because `top` equates to [window.top](https://developer.mozilla.org/en-US/docs/Web/API/Window/top) which is read only ... use a different variable name, e.g. `var Top`, or enclose the code in a function, or an IIFE ... or don't use `document.write` at all – Jaromanda X May 28 '18 at 04:32
  • It work's. Thanks a lot. – MD. Noor Uddin May 28 '18 at 04:36

2 Answers2

0

Because top equates to window.top which is read only ... use a different variable name, or enclose the code in a function, or an IIFE.

– answered by Jaromanda X

Kawsar Ahmed
  • 380
  • 1
  • 12
  • Now document.write() works fine. Why not to use it? I am new in javascript :) – MD. Noor Uddin May 28 '18 at 04:41
  • 1
    You can get away with document.write in a simple page - but anything more complex than a very very simple page, document.write is definitely something to avoid - note: I didn't post an answer as I'm sure it's been asked before – Jaromanda X May 28 '18 at 04:44
  • Answered here: https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Kawsar Ahmed May 28 '18 at 04:45
  • no, not at all - I could be wrong :p the document.write part is not relevant to the question though (remove that from the answer :p ) – Jaromanda X May 28 '18 at 04:53
0

Please change your variable name top to some other e.g. top2 etc.

top is Windoww object in JavaScript.

Here s the example that shows it.

var top = 100;  // not ok (it's Window Object)
var top2 = 100; // ok
var left = 200; // ok

/* top */
console.log(alert("<div style='position: absolute; left:" + top +"px; top:" + left + "px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div>"));
// <div style='position: absolute; left:[object Window]px; top:200px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div>


/* top2 */
<div style='position: absolute; left:[object Window]px; top:200px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div>
// <div style='position: absolute; left:100px; top:200px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div
hygull
  • 7,072
  • 2
  • 35
  • 42