John
John

Reputation: 911

window.open() doesn't work correctly inside a JS function

I tried to create an updates list for my web, so that when I click on the relevant update- a new additional small html window will open and I will see the full update content.
This is the code I wrote:

index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>

<body ng-app="myApp">

<p ng-controller="updatesCtrl">
    <span ng-repeat="x in updates">
        <a href="updateWindow.html" onclick="showUpdate(x.title,x.update)">&#9679; {{x.title}}</a>
        <br><br>
    </span>                 
</p>

<script>updates();</script>

</body>
</html> 

script.js:

function updates(){
    angular.module('myApp', []).controller('updatesCtrl', function($scope) {
    $scope.updates = [
        {title:"update1",update:"update1 content"},
        {title:"update2",update:"update2 content"}
        ];
    });
}

function showUpdate(title, update){ 
    var win=window.open('updateWindow.html','newwindow','width=600, height=350'); 
    win.document.getElementById("title").innerHTML=title;
    win.document.getElementById("update").innerHTML=update;
    return false;
}

updateWindow.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>

<h1 id="title"></h1>
<p id="update"></p>

</body>
</html>  

I have few problems here:
1.When I clicked on the update link, the update window replaced the main page (index.html) window, and also was a full size page.
2. No change was made in the <h1> and the <p> of the updateWindow- although I wrote a script that was suppose to enter an html content to those places.

I don't understand why I didn't get what I expected with this code. Especially, I don't understand the first problem: if I only try to replace the onclick content inside index.html with this: "window.open('updateWindow.html','newwindow','width=600, height=350'); return false;" - I get a new additional window with a smaller size as expected (I won't get the update content inside this window, but at least that solves my first problem).

What is the problem with my code?

Upvotes: 0

Views: 1057

Answers (2)

Mathew Jennings
Mathew Jennings

Reputation: 53

it looks to me that the window is not loading before you try to update html: Screenshot of my recreation you can see that the html page has not even loaded yet and the dev tools says there is a Uncaught TypeError: Cannot set property 'innerHTML' of null try getting the new page to update it onloadin the update page.

Upvotes: 0

Mathew Jennings
Mathew Jennings

Reputation: 33

Try to use window.open('updateWindow.html','_blank','width=600, height=350'); instead

Upvotes: 1

Related Questions