so i am trying to make a game for a proyect that shows a 'next' button . My code seems to not work out as I add the event listener to a variable. The console tells me that even the variable is null and on the inspector the event tag doesnt appear. I dont seem to know what the problem is.
var section = document.querySelector('seccion');
var container = document.querySelector('container');
var text = document.querySelector('text');
var optionButtons = document.querySelector('option-buttons')
const button = document.getElementById('next');
var siguiente = button.addEventListener('click', next, true);
var next = function() {
var aparece = alert('funciona')
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>text Adventure</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DotGothic16&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<link href="style.css" rel="stylesheet">
</head>
<body>
<section id="seccion">
<div >
<div id="text">text</div>
<div id="option-buttons" >
<button id='next' >Siguiente</button>
</div>
</section>
</div>
<script type='text/javascript' src="app.js"></script>
</body>
</html>
CodePudding user response:
- Your HTML is invalid
The div with the class 'container' needs to be closed inside the section tag, your's is outside of it.
To prevent this kind of mistakes I recommend some kind of HTML formatter like this one. - In your JavaScript you use a function before it's defined.
In this case it is the next function. Define it before adding it to the EventListener like this:
function next() {
var aparece = alert('funciona')
}
var siguiente = button.addEventListener('click', next, true);
CodePudding user response:
You need to change variable to function to use power of javascript hoisting or change order of the code:
var section = document.querySelector('seccion');
var container = document.querySelector('container');
var text = document.querySelector('text');
var optionButtons = document.querySelector('option-buttons')
const button = document.getElementById('next');
var siguiente = button.addEventListener('click', next, true);
function next() {
var aparece = alert('funciona')
};
or
var section = document.querySelector('seccion');
var container = document.querySelector('container');
var text = document.querySelector('text');
var optionButtons = document.querySelector('option-buttons')
const button = document.getElementById('next');
var next = function() {
var aparece = alert('funciona')
};
var siguiente = button.addEventListener('click', next, true);