I've included a stripped down version of my code. I have a function which generates list elements, and the elements have children which should have a 3D effect from a library I've included. As is, the library is not affecting the elements generated, I assume because it is set by innerHtml or finishes generating after the script at the end is read. Is there a way to make this work?
<html>
<script type="text/javascript">
function createList() {
const list = ["https://placekitten.com/300/300", "https://placekitten.com/300/300"];
var output = '<ul>';
list.forEach((example) => {
output +=
`
<li>
<div class="img-container" data-tilt>
<img src="${example}" />
</div>
</li>
`;
});
output += '</ul>';
document.getElementById("catalog-container").innerHTML = output;
}
</script>
<body onload="createList()">
<div id="catalog-container">
</div>
<script type="text/javascript" src="vanilla-tilt.js"></script>
</body>
</html>
Create the elements before the library script runs. There are several options. One is to put your script tag before the library's, and avoid the body onload
handler:
<body>
<div id="catalog-container">
</div>
<script>
function createList() {
// ...
}
createList(); // or remove the function entirely
</script>
<script src="vanilla-tilt.js"></script>
Another is to, instead, dynamically inject the library after your script runs. At the end of your function:
document.body.appendChild(document.createElement('script')).src = 'vanilla-tilt.js';
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.