Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One common script.js file in two html page causing errors

I am basically a beginner in programming world. So currently facing a problem that I don’t understand in which way I should search this solution. So I am here for help. Hope someone can help me. I really need this solution.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Game1</title>
</head>

<body>
    <p id="p1">Lorem ipsum dolor sit amet.</p>

    <script src="script.js"></script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Game2</title>
</head>

<body>
    <p id="p2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, quis!</p>

    <script src="script.js"></script>
</body>

</html>
(function() {
    const p1 = document.getElementById('p1');
    const textChange1 = () => {
        p1.innerHTML = 'textChange 1';
    }
    p1.addEventListener('click', textChange1);
})();


(function() {
    const p2 = document.getElementById('p2');
    const textChange2 = () => {
        p2.innerHTML = 'textChange 2';
    }
    p2.addEventListener('click', textChange2);
})();

So I want to run this script.js file in both Game1.html and Game2.html.

But it causing one error
![Text]https://i.ibb.co/BPVBv4N/html.jpg
in Game1.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

script.js:15 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at script.js:15:8
at script.js:16:3

in Game2.html

script.js:6 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at script.js:6:8
at script.js:7:3

I want to use one script file. When game1.html access it I want game1.html to access only the code including id=’p1′; and when its game2.html ,I want it to access only the part of js that include id=’p2′;
how can I achieve this, that the html use only the part of js that is needed not the others.

just like we use one css in multiple html .

note- I want only to use one js file no other sub-js file.
Thanks.

>Solution :

Check the element prior to executing, wrap your functions in something like this:

if (document.getElementById('p1') !== null){
 //p1 exists, continue
}

if (document.getElementById('p2') !== null){
 //p2 exists, continue
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading