0

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?

1
  • To hold data on page change you need to either pass it via a query string or use localStorage (I would recommend that). Commented Jun 13, 2020 at 12:31

3 Answers 3

1

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');
}
Sign up to request clarification or add additional context in comments.

Comments

0

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];;
}

Comments

0

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:

  • the URL
  • local storage
  • a cookie

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.