Reputation: 523
So here is my content.js
file.
var title
function content(e) {
title = e.getAttribute('title');
// alert(title); //it alerts the title
window.document.location="movie";
}
function setcontent(){
document.getElementById("name").innerHTML = title; //undefined
}
The content(e)
function is called by recommend.html
and after it redirects to the page movie.html
, setcontent()
function will be called by the movie.html
.
Here is my movie.html
<html>
<head>
<title>Movie Page</title>
<script type="text/javascript" src="{{url_for('static', filename='content.js')}}"></script>
</head>
<body onload="setcontent()">
<center>
<div id="name"></div>
</center>
</body>
But once the browser redirects to movie.html
, it shows undefined
in the place of id name
instead of the title value. I'm not sure what went wrong. Can somebody help me with this?
Upvotes: 0
Views: 223
Reputation: 6882
If you want to store data between page loads, then you need to store it in the browsers "localStorage" (or "sessionStorage"). Like this:
function content(e) {
localStorage.setItem('title', e.getAttribute('title'));
window.document.location="movie";
}
function setcontent(){
document.getElementById("name").innerHTML = localStorage.getItem('title');
}
Upvotes: 1
Reputation: 944441
A JavaScript program (in the context of a <script>
element) runs inside a web page.
If you navigate to a new webpage then you are effectively quitting that program and running a new one.
Variables don't have a life-span longer than the program they are part of.
If you want data from one page to be available in another then the first page needs to put it somewhere that the second page can access.
Such places include:
Upvotes: 0
Reputation: 2587
When you redirect, window object will belong to new window. Your previous window's variables won't be available in new window.
You can achieve your use case by:
var title
function content(e) {
title = e.getAttribute('title');
// alert(title); //it alerts the title
window.document.location=`movie?name=${title}`;
}
function setcontent(){
document.getElementById("name").innerHTML = window.location.search.split("=")[1];;
}
Upvotes: 0