copypaste
copypaste

Reputation: 175

Window.load doesn't working

Can some one please tell me why the next code isn't working?

var nump = 0;
 function point() {
  nump++;
  document.getElementById('point').style.margin = nump + 'px 0px 0px';
 }
window.onload = point();

I trying make div move when window is loaded, thank you all.

Upvotes: 0

Views: 106

Answers (4)

Shikiryu
Shikiryu

Reputation: 10219

By moving, do you want to say, like this : http://jsfiddle.net/myC7J/1/

Which would be adding a setInterval like this :

var interval;
window.onload = function(){ interval = setInterval(point, 100);}

EDIT :

Since it seems you want to make a game : If you want to play with position in DOM, why don't you use position: absolute , top and left Else, you should consider using Canvas.

Upvotes: 0

Christoph
Christoph

Reputation: 51191

1) You need to hand over a function reference:

window.onload = point;

2) Your comment

I trying make div move when window is loaded

makes me assume, you want to call the function recursively which should be done in the following way:

function point() {
    nump+=4;
    document.getElementById('point').style.margin = nump + 'px 0px 0px';
    // exemplary constraint to exit the loop, change to your liking
    if (nump < 300){setTimeout(point,20);}
}

your modified Example

Upvotes: 0

mplungjan
mplungjan

Reputation: 177746

Assigning an event handler that is a named function is done without the ()

DEMO based on your fiddle

var nump = 100; // setting a value that actually is visible
function point() {
  nump++;
  document.getElementById('point').style.margin = nump + 'px 0px 0px';
}
window.onload = point;

unless the named function returns a function.

Since you are using jQuery:

var nump = 0;
function point() {
  nump++;
  document.getElementById('point').style.margin = nump + 'px 0px 0px';
}
$(function() {
  point(); // will move 1 pixel
});

Perhaps you mean

$(function() {
  setInterval(function() {
    point(); // will move 1 pixel
  },100); // move one pixel every 100ms
});

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

To extend @mplungjan's answer: You should only assign the necessary style with JavaScript no need to change anything else then the margin-top property:

var nump = 0;
window.onload=function() {
  nump++;
  document.getElementById('point').style.marginTop = nump;
}

Upvotes: 0

Related Questions