Search code examples
javascripthtmlwindowhostingalert

Open popup in a new window by clicking a button in Javascript Alert


I'm using this code:

  <script type="text/javascript">
window.alert("Click Ok If Over 18");
window.open(
  '.html', 
  '_blank' // <- This is what makes it open in a new window.
);
</script>

I need to add this code for open a popup in new window:

<script type='text/javascript' src='address popup'></script>

If I add it in this way:

<script type="text/javascript">
window.alert("Click Ok If Over 18");
window.open(
  'address popup', 
  '_blank' // <- This is what makes it open in a new window.
);
</script>

It doesn't open as expected. I see only text. Maybe it's because I did not use src:. What I can do?


Solution

  • The first parameter of window.open() needs to be the URL of the page you want to open in the popup.

    Rather than using an alert, sounds like you should use a confirm. Alert doesn't actually allow the user to say they aren't 18; even if they close the alert instead of hitting "ok", it'll still continue to open your pop-up. But confirm() gives them an "ok" button and a "cancel" button, so they can choose.

    So altogether, here's what your code might look like:

    <script type="text/javascript">
    var isEighteen = window.confirm("Click Ok If Over 18");
    if (isEighteen) { // if they clicked "ok"
        window.open(
          'http://example.com/popup-is18.html', 
          '_blank'
        );
    } else { // if they clicked "cancel"
        window.open(
          'http://example.com/popup-not18.html', 
          '_blank'
        );
    }
    </script>
    

    It looks like you were trying to include the JavaScript from another file. If you did that, you'd want to put everything inside of the script tag above into a file, some_name_you_can_make_up.js, and then do this:

    <script type="text/javascript" src="http://example.com/some_name_you_can_make_up.js"></script>