I’m trying to dynamically insert HTML content(with buttons) into a static HTML file.
This is where I want to insert the HTML dynamically:
<div class="pantalla">
<div class="contenidoPantalla"></div>
</div>
This is the HTML I want to insert:
<div class="box center">
<div class="inner-box">
<button data-option="1" data-next-page="menu2.html">
Economía cerrada sin sector público/Closed economy no public sector
</button>
</div>
<div class="inner-box">
<button data-option="2" data-next-page="menu5.html">
Economía cerrada con sector público/Closed economy with public sector
</button>
</div>
<div class="inner-box">
<button data-option="3" data-next-page="menu12.html">
Economía abierta con sector público/Open economy with public sector
</button>
</div>
</div>
I’m trying to use various JavaScript methods, but I always have the same problem: I can’t click on the button. The console tells me “Button type attribute has not been set.”
I’ve tried with pure JavaScript:
document.addEventListener('DOMContentLoaded', function() {
var contenidoPantalla = document.querySelector('.contenidoPantalla');
var htmlFile = '/html/menu1.html';
//console.log(htmlFile)
fetch(htmlFile)
.then(response => response.text())
.then(data => {
contenidoPantalla.innerHTML = data;
});
});
Also with jQuery (this and more alternatives):
$(document).ready(function() {
$(".contenidoPantalla").load("/html/menu1.html", function() {
// Aquí puedes agregar los controladores de eventos para tus botones
$(document).on('click', 'button', function() {
console.log("HOLA");
var option = $(this).data('option');
var nextPage = $(this).data('next-page');
controlServos(option, nextPage);
});
});
});
And with Ajax:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/html/menu1.html", true);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector('.contenidoPantalla').innerHTML = this.responseText;
// Aquí puedes agregar los controladores de eventos para tus botones
var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
var option = this.getAttribute('data-option');
var nextPage = this.getAttribute('data-next-page');
controlServos(option, nextPage);
});
});
}
};
xhr.send();
I still don’t understand why the button properties aren’t being applied, because the HTML is being added correctly to ‘contenidoPantalla’, but I can’t click on it.