I found a strange behavior in JS. How to stop this behavior

40 Views Asked by At

let's start with two files index.html and script.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>click me</button>
    <div></div>
    <script src="script.js"></script>
</body>
</html>
const buttonUser = document.querySelector("button");
const divUser = document.querySelector("div");

buttonUser.addEventListener("click", () => {
    divUser.innerHTML = `
        <h1> welcome to the page </h1> 
        <button onclick="welcomeMassage()"> click me 2 <button>
    `
})

function welcomeMassage() {
    console.log("Hello World!");
}

if i clicked in the first button the addEventListener work and adding h1 and second button two divUser adn if i click on the second one it's also work and console.log("Hello world") but :::::::

if change the javascript file two script.mjs and index.js

    <script type="module" src="script.mjs"></script>

When I click on the first button, the addEventListener works, but when I click on the second button, it does not work and shows up in the console. The welcomeMassage function is not defined, and I can't access it from the console. So why has this happened, and how can I prevent this behavior?

i want when use scritp.mjs file and i click in the button not show in console functionNamve not defined and perform the function

1

There are 1 best solutions below

2
Tanvir Rahman On

The issue you're facing is because of scoping. You need to ensure that welcomeMessage is accessible from the global scope so that your inline onclick handler can invoke it. One way to do this is by explicitly assigning the function to a property of the global window object. This makes the function accessible as a global variable, which allows it to be called from inline event handlers.

To fix this, here's the updated code:

In index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>click me</button>
    <div></div>
    <script type="module" src="script.mjs"></script>
</body>
</html>

In script.mjs

window.welcomeMessage = function() {
    console.log("Hello World!");
}

const buttonUser = document.querySelector("button");
const divUser = document.querySelector("div");

buttonUser.addEventListener("click", () => {
    divUser.innerHTML = `
        <h1> welcome to the page </h1> 
        <button onclick="welcomeMessage()"> click me 2 </button>
    `;
});

const buttonUser = document.querySelector("button");
const divUser = document.querySelector("div");

buttonUser.addEventListener("click", () => {
    divUser.innerHTML = `
        <h1> welcome to the page </h1> 
        <button onclick="welcomeMessage()"> click me 2 </button>
    `;
});