To achieve smooth scroll animations where course content containers gradually appear as the user scrolls, you'll need to implement the following steps:
- Define the Animation States in CSS
- Apply Animation Classes to Course Content Elements
- Use Intersection Observer API to Trigger Animations on Scroll
Below is a comprehensive guide to implementing these steps in your project.
1. Define the Animation States in CSS
First, you'll need to define the initial hidden state and the visible state with smooth transitions. Add these styles to your static/css/base.css or create a new CSS file if you prefer to keep things organized.
/* Add these to static/css/base.css */
/* Initial hidden state */
.animate {
opacity: 0;
transform: translateY(20px) scale(0.95);
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
/* Visible state */
.animate.show {
opacity: 1;
transform: translateY(0) scale(1);
}
Explanation:
-
.animate: This class sets the initial state of the element to be slightly translated down (translateY(20px)), scaled down (scale(0.95)), and fully transparent (opacity: 0). It also defines the transition properties for smooth animation.
-
.animate.show: When the show class is added, the element transitions to its original position (translateY(0)), full size (scale(1)), and full opacity (opacity: 1).
2. Apply Animation Classes to Course Content Elements
Since your course content is dynamically generated using course_render_manager.js, you'll need to ensure that each content container has the animate class applied when it is created. Modify your course_render_manager.js as follows:
/* Update static/js/course_render_manager.js */
/* Add the 'animate' class to the elements you want to animate.
For example, add it to section-container, topic-container, and subtopic-container */
function renderCourse(courseData) {
const container = $('.course-content-container');
container.empty(); // Clear previous content
// Configure marked for syntax highlighting
marked.setOptions({
highlight: function(code, lang) {
if (Prism.languages[lang]) {
return Prism.highlight(code, Prism.languages[lang], lang);
} else {
return code;
}
}
});
container.append(`
<div class="courseTitle animate">${courseData.courseTitle}</div>
<div class="courseDescription animate">${marked.parse(courseData.courseDescription)}</div>
<div class="sections"></div>
`);
const sectionsContainer = container.find('.sections');
courseData.sections.forEach(section => {
const sectionElement = $(`
<div class="section-container animate">
<div class="sectionTitle animate">${section.sectionTitle}</div>
<div class="topics"></div>
</div>
`);
const topicsContainer = sectionElement.find('.topics');
section.topics.forEach(topic => {
const topicElement = $(`
<div class="topic-container animate">
<div class="topicTitle animate">
<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 => {
const subtopicElement = $(`
<div class="subtopic-container animate">
<div class="title animate">
<img class="course-list-icon" src="../static/images/subtopic-icon.webp">
${subtopic.title}
</div>
<div class="content animate">${marked.parse(subtopic.content)}</div>
</div>
`);
// Check for definitions
if (subtopic.definitions && Object.keys(subtopic.definitions).length > 0) {
const definitionsContainer = $('<div class="definitions animate"></div>');
for (const [term, definition] of Object.entries(subtopic.definitions)) {
definitionsContainer.append(`
<div class="definition-container animate">
<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 Prism syntax highlighting
Prism.highlightAll();
// Add copy buttons to code blocks
addCopyButtons();
// Initialize scroll animations after rendering
initScrollAnimations();
}
function initScrollAnimations() {
const animatedElements = document.querySelectorAll('.animate');
const observerOptions = {
threshold: 0.1
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('show');
observer.unobserve(entry.target); // Optional: Stop observing after animation
}
});
}, observerOptions);
animatedElements.forEach(el => {
observer.observe(el);
});
}
Explanation:
-
Adding the animate Class: Each element that you want to animate as it comes into view is assigned the animate class when it's created. This includes sections, topics, subtopics, titles, content, and definitions.
-
initScrollAnimations Function: After rendering all course content, this function initializes the scroll animations by selecting all elements with the animate class and observing them using the IntersectionObserver API. When an element enters the viewport (isIntersecting becomes true), the show class is added, triggering the CSS transitions defined earlier. The observer then unobserves the element to prevent repeated animations.
-
Calling initScrollAnimations: This function is called at the end of renderCourse to ensure that all newly added elements are observed for scroll-triggered animations.
3. Ensure JavaScript Runs After Content is Loaded
Ensure that renderCourse is called when the document is ready and that the initial content is also set up for animations. Your existing getCourseFromId("test") inside $(document).ready already handles this.
However, make sure you remove or adjust any static content in index.html that might conflict with dynamic rendering. If you're using dynamic rendering exclusively, you might not need the static course content in index.html. Here's how you can adjust it:
<!-- Update templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DarkHub</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=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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<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">
<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 injected here -->
</div>
</div>
</div>
<script src="../static/js/main.js"></script>
<script src="../static/js/course_render_manager.js"></script>
</body>
</html>
Optional: If you prefer to keep some static content for fallback or initial display before dynamic content loads, ensure that these elements also have the animate class if you want them to animate on load.
4. Final Touches and Testing
After implementing the above steps, follow these recommendations:
-
Test Responsiveness: Ensure that the animations work smoothly across different screen sizes and devices.
-
Performance Considerations: Using IntersectionObserver is efficient, but observing a large number of elements might have performance implications. If you notice any lag, consider optimizing the number of observed elements or debouncing the animation triggers.
-
Fallbacks: For browsers that do not support the IntersectionObserver API, consider adding a polyfill or providing fallback styles.
Complete Code Snippets
1. Updated static/css/base.css:
:root {
--base-color: rgb(241, 240, 231);
--second-color: #cecece;
--font-color: #252525;
--base-gap: 15px;
}
html {
font-family: "Roboto", sans-serif;
font-weight: 500;
font-size: 20px;
color: var(--font-color);
}
body {
margin: 0;
}
.screen {
display: flex;
width: 100%;
/* height: 100vh; */
background-color: var(--base-color);
flex-direction: column;
align-items: center;
}
.screen-content {
display: flex;
width: calc(100% - var(--base-gap) * 2);
height: 100%;
padding: var(--base-gap);
max-width: 1200px;
}
.courses-container {
display: grid;
grid-template-columns: repeat(auto-fit, 300px);
grid-template-rows: repeat(auto-fit, 200px);
grid-gap: var(--base-gap);
width: 100%;
height: 100%;
display: none;
}
.course-tile {
width: 300px;
height: 200px;
/* aspect-ratio: 2 / 3; */
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
border-radius: 10px;
position: relative;
cursor: pointer;
}
.course-background {
height: 100%;
position: absolute;
transition: transform 0.3s;
}
.course-title {
z-index: 2;
position: absolute;
left: var(--base-gap);
bottom: -10px;
opacity: 0;
color: white;
transition: bottom 0.2s, opacity 0.2s;
}
.course-tile:hover {
.course-background {
transform: scale(1.1);
}
.course-title {
bottom: var(--base-gap);
opacity: 1;
}
}
.course-tile:active {
.course-background {
transform: scale(1.05);
transition: transform 0.05s;
}
}
button:hover {
filter: brightness(90%);
}
button:active {
transform: scale(0.95);
}
pre {
background-color: #2d2d2d;
border-radius: 5px;
padding: 15px;
position: relative;
display: inline-block;
min-width: 50px;
max-width: 100%;
overflow-x: auto;
}
pre > code {
color: #ccc;
white-space: pre-wrap;
word-break: break-word;
}
.copy-button {
position: absolute;
top: 5px;
right: 5px;
background-color: #4CAF50;
border: none;
color: white;
padding: 5px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 12px;
margin: 4px 2px;
cursor: pointer;
border-radius: 3px;
}
/* Добавляем стили для контейнера кода */
.code-container {
display: flex;
justify-content: center;
width: 100%;
}
.code-container pre {
max-width: 80%; /* или другое значение, которое вам подходит */
}
.topics > .topic-container:first-of-type {
.topicTitle {
margin: 10px 0 10px 0;
border-top: none;
}
}
/* Ползунок */
::-webkit-scrollbar {
width: 5px; /* Ширина ползунка с учетом margin */
background: transparent; /* Прозрачный фон */
}
::-webkit-scrollbar-thumb {
background: rgb(103 104 114); /* Белый цвет с прозрачностью 70% */
border-radius: 10px; /* Скругление ползунка */
margin: 5px; /* Отступ от стенок */
}
/* Animation Classes */
.animate {
opacity: 0;
transform: translateY(20px) scale(0.95);
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
.animate.show {
opacity: 1;
transform: translateY(0) scale(1);
}
2. Updated static/js/course_render_manager.js:
function renderCourse(courseData) {
const container = $('.course-content-container');
container.empty(); // Clear previous content
// Configure marked for syntax highlighting
marked.setOptions({
highlight: function(code, lang) {
if (Prism.languages[lang]) {
return Prism.highlight(code, Prism.languages[lang], lang);
} else {
return code;
}
}
});
container.append(`
<div class="courseTitle animate">${courseData.courseTitle}</div>
<div class="courseDescription animate">${marked.parse(courseData.courseDescription)}</div>
<div class="sections"></div>
`);
const sectionsContainer = container.find('.sections');
courseData.sections.forEach(section => {
const sectionElement = $(`
<div class="section-container animate">
<div class="sectionTitle animate">${section.sectionTitle}</div>
<div class="topics"></div>
</div>
`);
const topicsContainer = sectionElement.find('.topics');
section.topics.forEach(topic => {
const topicElement = $(`
<div class="topic-container animate">
<div class="topicTitle animate">
<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 => {
const subtopicElement = $(`
<div class="subtopic-container animate">
<div class="title animate">
<img class="course-list-icon" src="../static/images/subtopic-icon.webp">
${subtopic.title}
</div>
<div class="content animate">${marked.parse(subtopic.content)}</div>
</div>
`);
// Check for definitions
if (subtopic.definitions && Object.keys(subtopic.definitions).length > 0) {
const definitionsContainer = $('<div class="definitions animate"></div>');
for (const [term, definition] of Object.entries(subtopic.definitions)) {
definitionsContainer.append(`
<div class="definition-container animate">
<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 Prism syntax highlighting
Prism.highlightAll();
// Add copy buttons to code blocks
addCopyButtons();
// Initialize scroll animations after rendering
initScrollAnimations();
}
function addCopyButtons() {
// Find all code blocks
const codeBlocks = document.querySelectorAll('pre > code');
codeBlocks.forEach((codeBlock) => {
// Create a button
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.textContent = 'Копировать';
// Append the button to the code block's parent (pre)
codeBlock.parentNode.appendChild(copyButton);
// Add click event to copy code
copyButton.addEventListener('click', () => {
const code = codeBlock.textContent;
navigator.clipboard.writeText(code).then(() => {
copyButton.textContent = 'Скопировано!';
setTimeout(() => {
copyButton.textContent = 'Копировать';
}, 2000);
}).catch(err => {
console.error('Ошибка при копировании: ', err);
});
});
});
}
function initScrollAnimations() {
const animatedElements = document.querySelectorAll('.animate');
const observerOptions = {
threshold: 0.1
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('show');
observer.unobserve(entry.target); // Optional: stop observing after animation
}
});
}, observerOptions);
animatedElements.forEach(el => {
observer.observe(el);
});
}
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. Updated templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DarkHub</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=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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<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">
<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 injected here -->
</div>
</div>
</div>
<script src="../static/js/main.js"></script>
<script src="../static/js/course_render_manager.js"></script>
</body>
</html>
5. Optional: Using a CSS Library for Animations
If you prefer to use a pre-built solution, consider integrating a CSS library like AOS (Animate On Scroll). However, the manual approach outlined above provides more control and reduces dependencies.
Conclusion
By following the steps above, your course content will now animate smoothly into view as users scroll through the page. This enhances the user experience by making the interface more dynamic and engaging.
If you encounter any issues or need further customization, feel free to ask!