0

I wrote the following code in JavaScript to open a popup window when a button is pressed, and then use setInterval to move the window every 2 seconds.

<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset = "utf-8">
    <title>  Javascriptin' Some Codes </title>
    <script>
            function hi() {
            var printOut = window.open("http://www.google.com","_blank", 'height=200, width=200');
            setInterval(function() { printOut.moveBy(10,10);}, 2000)
            window.alert("hi");}
    </script>
 </head>
 <body>
    <button onclick="hi()"> Try me </button>
 </body>
</html>

The window opens, but the setInterval doesn't appear to work- the window does not move after being launched. I was wondering why my code doesn't work, and what I could do to make it function the way I'd like it to.

gariepy
  • 3,576
  • 6
  • 21
  • 34
MYV
  • 4,294
  • 6
  • 28
  • 24
  • See this http://stackoverflow.com/questions/7678976/what-is-self-moveby-and-why-doesnt-it-work-on-chrome + the `alert` dialog will block further JS execution. – marekful Jul 30 '13 at 09:12
  • @ Marcell - moveby works on the popup window when I don't have it in an interval. – MYV Jul 30 '13 at 09:16
  • 1
    Yes, that's because in that case `moveBy` is executed _before_ `alert` blocks further execution. In case it is in `setInterval`, the first time it would execute the code in the anonymous function passed to `setInterval` is delayed by 2 seconds, but by then, alert blocks. Remove `alert`, and if `moveBy` is not disabled by your browser, it should work. – marekful Jul 30 '13 at 09:18

1 Answers1

1

The opened url has to be on the same domain as stated in this answer (DEMO).

For example on jsfiddle, this works:

var printOut = window.open("http://fiddle.jshell.net","_blank", 'height=200, width=200');

And that one doesn't:

var printOut = window.open("http://www.google.com","_blank", 'height=200, width=200');

You should also remove the alert, although it works in chrome it seams to break it in for example opera.

Community
  • 1
  • 1
Marcel Gwerder
  • 8,353
  • 5
  • 35
  • 60