To achieve smooth, scroll-triggered animations for your course content, you can utilize the AOS (Animate On Scroll) library. AOS is easy to integrate and highly customizable, allowing you to create the desired animation effects where elements slide up, scale, and fade into view as they enter the viewport. Additionally, AOS supports re-triggering animations when scrolling back and forth, ensuring that the animations play every time the elements come into view.
Here's a step-by-step guide to integrating AOS into your project and configuring it to meet your requirements:
1. Include AOS Library in Your Project
First, you need to include the AOS CSS and JavaScript files in your index.html. You can use CDN links for easy integration.
Update templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DarkHub</title>
<!-- Google Fonts -->
<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=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Roboto+Slab:wght@100..900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<!-- Marked.js -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<!-- Prism.js for Syntax Highlighting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/plugins/autoloader/prism-autoloader.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css">
<!-- AOS CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.css" rel="stylesheet">
<!-- Your Custom CSS -->
<link rel="stylesheet" href="../static/css/base.css">
<link rel="stylesheet" href="../static/css/hotbar.css">
<link rel="stylesheet" href="../static/css/course-content.css">
</head>
<body>
<div class="screen">
{% include "components/hotbar.html" %}
<div class="screen-content">
<div class="courses-container">
<div class="course-tile">
<div class="course-title">Test course</div>
<img class="course-background" src="../static/images/javascript.png">
</div>
</div>
<div class="course-content-container">
<!-- Dynamic content will be rendered here -->
</div>
</div>
</div>
<!-- Your Custom JS -->
<script src="../static/js/main.js"></script>
<script src="../static/js/course_render_manager.js"></script>
<!-- AOS JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.js"></script>
<script>
// Initialize AOS
AOS.init({
duration: 800, // Animation duration in milliseconds
easing: 'ease-in-out', // Easing effect
once: false, // Whether animation should happen only once
mirror: false, // Whether elements should animate out while scrolling past them
});
</script>
</body>
</html>
2. Configure AOS in Your JavaScript
After rendering dynamic content, you'll need to refresh AOS so that it can recognize the newly added elements. Modify your course_render_manager.js to include AOS refresh after the content is rendered.
Update static/js/course_render_manager.js:
function renderCourse(courseData) {
const container = $('.course-content-container');
container.empty(); // Clear previous content
// Configure marked to use Prism for syntax highlighting
marked.setOptions({
highlight: function(code, lang) {
if (Prism.languages[lang]) {
return Prism.highlight(code, Prism.languages[lang], lang);
} else {
return code;
}
}
});
// Append course title and description with AOS attributes
container.append(`
<div class="courseTitle" data-aos="fade-up">${courseData.courseTitle}</div>
<div class="courseDescription" data-aos="fade-up">${marked.parse(courseData.courseDescription)}</div>
<div class="sections" data-aos="fade-up"></div>
`);
const sectionsContainer = container.find('.sections');
courseData.sections.forEach(section => {
// Append each section with AOS attributes
const sectionElement = $(`
<div class="section-container" data-aos="fade-up">
<div class="sectionTitle">${section.sectionTitle}</div>
<div class="topics"></div>
</div>
`);
const topicsContainer = sectionElement.find('.topics');
section.topics.forEach(topic => {
// Append each topic with AOS attributes
const topicElement = $(`
<div class="topic-container" data-aos="fade-up">
<div class="topicTitle">
<img class="course-list-icon" src="../static/images/topic-icon.webp">
${topic.topicTitle}
</div>
<div class="subtopics"></div>
</div>
`);
const subtopicsContainer = topicElement.find('.subtopics');
topic.subtopics.forEach(subtopic => {
// Append each subtopic with AOS attributes
const subtopicElement = $(`
<div class="subtopic-container" data-aos="fade-up">
<div class="title">
<img class="course-list-icon" src="../static/images/subtopic-icon.webp">
${subtopic.title}
</div>
<div class="content">${marked.parse(subtopic.content)}</div>
</div>
`);
// Check if definitions exist and are not empty
if (subtopic.definitions && Object.keys(subtopic.definitions).length > 0) {
const definitionsContainer = $('<div class="definitions" data-aos="fade-up"></div>');
for (const [term, definition] of Object.entries(subtopic.definitions)) {
definitionsContainer.append(`
<div class="definition-container" data-aos="fade-up">
<div class="definition-a">${term}</div>
<div class="definition-b">${marked.parse(definition)}</div>
</div>
`);
}
subtopicElement.append(definitionsContainer);
}
subtopicsContainer.append(subtopicElement);
});
topicsContainer.append(topicElement);
});
sectionsContainer.append(sectionElement);
});
// Apply syntax highlighting
Prism.highlightAll();
// Add copy buttons
addCopyButtons();
// Refresh AOS to recognize new elements
AOS.refresh();
}
function addCopyButtons() {
// Find all code blocks
const codeBlocks = document.querySelectorAll('pre > code');
codeBlocks.forEach((codeBlock) => {
// Create copy button
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.textContent = 'Копировать';
// Add button next to the code block
codeBlock.parentNode.insertBefore(copyButton, codeBlock);
// Add click event listener for copying
copyButton.addEventListener('click', () => {
const code = codeBlock.textContent;
navigator.clipboard.writeText(code).then(() => {
copyButton.textContent = 'Скопировано!';
setTimeout(() => {
copyButton.textContent = 'Копировать';
}, 2000);
}).catch(err => {
console.error('Ошибка при копировании: ', err);
});
});
});
}
function getCourseFromId(courseId) {
$.ajax({
url: `/get_course/${courseId}`,
method: 'GET',
success: function(response) {
renderCourse(response);
},
error: function(xhr, status, error) {
console.error("Ошибка при получении курса:", error);
}
});
}
$(document).ready(function() {
getCourseFromId("test");
});
3. Add data-aos Attributes to Dynamic Elements
In the renderCourse function above, notice that each dynamic element includes the data-aos="fade-up" attribute. This attribute tells AOS to apply the "fade-up" animation to the element when it enters the viewport. You can customize the animation type by changing the value of the data-aos attribute. Here are some popular AOS animations:
fade-up
fade-down
fade-left
fade-right
fade-zoom-in
flip-left
flip-right
zoom-in
zoom-out
Feel free to experiment with different animations to see which one best fits your design preferences.
4. Customize AOS Animations (Optional)
If you want to customize the animation further, such as adjusting the delay or offset, you can add additional data-aos attributes.
For example:
<div class="section-container" data-aos="fade-up" data-aos-delay="100" data-aos-offset="200">
<!-- Section Content -->
</div>
data-aos-delay: Specifies the delay before the animation starts (in milliseconds).
data-aos-offset: Defines the offset (in pixels) from the original trigger point.
5. Ensure Smooth Re-triggering of Animations
By setting once: false in the AOS initialization, the animations will trigger every time the elements come into the viewport, allowing for smooth re-triggering when scrolling back and forth.
AOS.init({
duration: 800,
easing: 'ease-in-out',
once: false, // Enable animations to trigger multiple times
mirror: false,
});
6. Finalize and Test Your Implementation
After implementing the above steps, ensure that your dynamic content correctly includes the data-aos attributes and that AOS refreshes after rendering the content. Test the scrolling behavior to confirm that the animations trigger smoothly as elements enter and exit the viewport.
7. Additional CSS Adjustments (Optional)
To enhance the visual appearance and ensure that the initial state of the elements aligns with your desired animation, you might want to adjust some CSS properties. However, AOS handles most of the animation transitions, so significant changes might not be necessary.
Example Adjustment in static/css/course-content.css:
/* Optional: Adjust initial opacity for smoother transitions */
.courseTitle,
.courseDescription,
.section-container,
.topic-container,
.subtopic-container,
.definition-container {
opacity: 0; /* Elements start as transparent */
transform: translateY(20px) scale(0.95); /* Slightly shifted down and scaled */
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
/* When AOS applies the 'aos-animate' class, elements become fully visible and normal size */
.aos-animate {
opacity: 1;
transform: translateY(0) scale(1);
}
Note: AOS already handles animations, so the above CSS is optional and can be customized based on your specific design needs.
8. Final Project Structure
Your updated project structure should look like this:
DarkHub/
├── courses/
│ └── test.json
├── static/
│ ├── css/
│ │ ├── base.css
│ │ ├── course-content.css
│ │ └── hotbar.css
│ ├── images/
│ │ ├── h_icon.webp
│ │ ├── javascript.png
│ │ ├── section-icon.webp
│ │ ├── subtopic-icon.webp
│ │ └── topic-icon.webp
│ ├── js/
│ │ ├── course_render_manager.js
│ │ └── main.js
├── templates/
│ ├── components/
│ │ └── hotbar.html
│ └── index.html
└── app.py
9. Example of courses/test.json
Ensure that your test.json is properly formatted to match the structure expected by the renderCourse function. Here's an example structure:
{
"courseTitle": "Тестовый курс",
"courseDescription": "Это тестовый курс для теста",
"sections": [
{
"sectionTitle": "Основы JavaScript",
"topics": [
{
"topicTitle": "Введение в JavaScript",
"subtopics": [
{
"title": "Что такое JavaScript?",
"content": "Это контент сабтопика",
"definitions": {
"JavaScript": "Язык программирования, добавляющий интерактивность веб-страницам.",
"HTML": "Язык разметки гипертекста, используемый для создания структуры веб-страниц.",
"CSS": "Каскадные таблицы стилей, используемые для стилизации веб-страниц."
}
},
{
"title": "Подключение JavaScript к HTML",
"content": "Это контент сабтопика",
"definitions": {}
}
]
}
]
}
]
}
10. Final Testing
-
Run Your Flask Application:
python app.py
-
Open in Browser:
Navigate to http://localhost:8081 in your web browser.
-
Scroll to Trigger Animations:
Scroll through your course content to see the elements animate smoothly as they enter the viewport. Try scrolling up and down to ensure that animations re-trigger correctly.
11. Troubleshooting Tips
By following these steps, you can enhance your project with smooth, scroll-triggered animations that improve user experience and engagement. AOS provides a robust and flexible way to handle animations, and its easy integration with your existing setup should make the implementation straightforward.
If you encounter any issues or need further customization, feel free to ask for more detailed assistance!