I’m trying to replicate the code below to open up a different page, each time. Please see:
Code:
<section class="container g-py-15">
<div class="g-brd-around g-brd-5 g-brd-gray-light-v4 g-pa-30">
<div class="row">
<div class="col-md-9 align-self-center">
<h3 class="h4">Task 1 & Extension</h3>
<p class="lead g-mb-20 g-mb-0--md">Set up the inital track markers</p>
</div>
<div class="col-md-3 align-self-center text-md-right">
<button onclick="openWin()">Open code</button>
<button onclick="closeWin()">Close code</button>
<script>
let myWindow;
function openWin() {
myWindow = window.open("8_1python/task1.html", "_blank", "width=800, height=800");
}
function closeWin() {
myWindow.close();
}
</script>
</div>
</div>
</div>
</section>
<section class="container g-py-15">
<div class="g-brd-around g-brd-5 g-brd-gray-light-v4 g-pa-30">
<div class="row">
<div class="col-md-9 align-self-center">
<h3 class="h4">Task 2 & Extension</h3>
<p class="lead g-mb-20 g-mb-0--md">Complete the track set up </p>
</div>
<div class="col-md-3 align-self-center text-md-right">
<button onclick="openWin()">Open code</button>
<button onclick="closeWin()">Close code</button>
<script>
let myWindow;
function openWin() {
myWindow = window.open("8_1python/task2.html", "_blank", "width=800, height=800");
}
function closeWin() {
myWindow.close();
}
</script>
This works fine to open up task 1, but when I want to replicate the code for task 2, it still opens up task 1.
It opens up task 1 each time. Above I have posted the repeated code for task 1, which works fine, and task 2 which does not.
3
Answers
All your buttons will open the same URL unless you give a different URL.
Here’s a simple example of a fixed window opener:
There are further improvements to make still. Most glaring issues first.
Here’s how I solved those issues:
Use a single pair of functions with parameters and return values.
You are overwriting you previous definitions of
myWindow
,openWindow
andcloseWin
if you just copy paste the snippet modifying the URL to open.I’ll show you a way to do it without inline handlers since they are considered dangerous, outdated and disallowed by strict CSP headers.
You can store the
url
to open and ataskId
as data attributes. Then you can use your event handler to open that URL and to store the reference in a global variable that tracks the open windows.