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 class="container"> <div id="text">text</div> <div id="option-buttons" class="btn-grid"> <button id='next' class="btn">Siguiente</button> </div> </section> </div> <script type='text/javascript' src="app.js"></script> </body> </html>
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);
function next() {
var aparece = alert('funciona')
}
var siguiente = button.addEventListener('click', next, true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.