I've just learned about creating reusable components and I'm trying to implement it to clean up my code. Before using the web components, I had jQuery and the AOS library working to get some basic animations on my webpage. However, once I create my custom web component, I'm not sure how to pass these scripts/libraries into my custom component.
I've created an example to show the problem. In this example, every animation that I've attempted in index.html is working perfectly.
index.html (below)
<!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">
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<style>
.jQuery{
position: relative;
}
</style>
</head>
<body>
<div data-aos="fade-left">
This AOS animation works. This text is inputted in index.html and successfully executes the AOS "fade-left" animation. (The AOS library scripts are included in index.html)
</div>
<br/>
<aos-component></aos-component>
<br/>
<div class="jQuery">
This jQuery animation works. This text is created in index.html and is animated using jQuery from test_jQuery.js.
</div>
</body>
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>AOS.init();</script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="test_jQuery.js"></script>
<script src="test_AOS.js" type="text/javascript" defer></script>
</html>
I created a "AOS-component" in 'test_AOS.js', with the idea of reusing this component. Every time I use this component, I want the same animation to load. However, I'm not sure how to pass the AOS library or jQuery scripts into this element.
test_AOS.js (below)
const template = document.createElement('template');
template.innerHTML = `
<style>
.testingAOS {
background-color: #dfdfdf;
}
</style>
<div class="testingAOS" data-aos="fade-left">
This AOS animation does NOT work. This text is inputted inside the custom HTML Element/Web Component (test_AOS.js) and does not execute the "fade-left" animation. test_AOS.js does NOT reference the AOS library.
<br/>
</div>
`;
class CustomElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
//Do I have to insert a reference to the aos.js script here and initialize AOS? How can I do that?
}
}
customElements.define('aos-component', CustomElement);
The jQuery script (test_jQuery.js) is working fine when called from index.html.
test_jQuery.js (below)
$(document).ready(function(){
$(".jQuery").animate({
left:'150px'
});
});
If I create a custom element (such as test_AOS.js), how would I implement jQuery commands?
Thank you so much in advance!