To properly fix the modal using Bootstrap in your template, follow these steps to ensure the modal structure is correct, all necessary classes and IDs are in place, and the JavaScript interacts seamlessly with the modal. Below is a comprehensive guide to updating your code:
1. Ensure Bootstrap CSS and JS are Included
First, make sure that Bootstrap's CSS and JavaScript are correctly included in your base.html. Typically, you should include them in the <head> and just before the closing </body> tag, respectively.
In the <head> section:
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
Before the closing </body> tag:
<!-- Bootstrap Bundle JS (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
Note: Ensure these links point to the correct Bootstrap version you're using. The above example uses Bootstrap 5.3.0.
2. Correct the Modal HTML Structure
Bootstrap requires a specific structure for modals to function correctly. Here's how you can modify your modal:
{% if authenticated and current_user.id == author.id %}
<!-- Share Button -->
<button type="button" class="btn btn-success" id="shareButton" data-bs-toggle="modal" data-bs-target="#shareModal">
Поделиться
</button>
<!-- Share Modal -->
<div class="modal fade" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="shareModalLabel">Ссылка для общего доступа</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
</div>
<div class="modal-body">
<input type="text" class="form-control" id="sharedLinkInput" readonly>
<button class="btn btn-secondary mt-2" id="copyLinkButton">Скопировать ссылку</button>
</div>
</div>
</div>
</div>
{% endif %}
Key Points:
-
Button Attributes:
The shareButton now includes data-bs-toggle="modal" and data-bs-target="#shareModal" which automatically handles the opening of the modal without needing explicit JavaScript for toggling.
-
Modal Structure:
The modal has the classes modal fade for the fading effect and proper accessibility attributes (tabindex, aria-labelledby, aria-hidden). Ensure the id of the modal matches the data-bs-target in the button.
3. Remove Redundant or Conflicting Elements
In your original code, there's another button with id="shareBtn" outside of the authenticated check. This can cause conflicts as IDs should be unique within a page. Remove or rename this button if it's not necessary.
<!-- Remove or ensure uniqueness if this button is needed elsewhere -->
<!--
<button id="shareBtn" class="btn btn-primary me-2">Поделиться</button>
-->
4. Update JavaScript for Modal Interaction
With the modal HTML structure correctly set, update your JavaScript to handle fetching the share link and copying it to the clipboard. Here's the revised script:
<script>
document.addEventListener('DOMContentLoaded', function () {
const shareButton = document.getElementById('shareButton');
const shareModalElement = document.getElementById('shareModal');
const shareModal = new bootstrap.Modal(shareModalElement);
const sharedLinkInput = document.getElementById('sharedLinkInput');
const copyLinkButton = document.getElementById('copyLinkButton');
if (shareButton) {
shareButton.addEventListener('click', function () {
fetch("{{ url_for('share_video', video_id=current_video.id) }}", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Add CSRF token here if your backend requires it
},
body: JSON.stringify({})
})
.then(response => response.json())
.then(data => {
if (data.shared_url) {
sharedLinkInput.value = data.shared_url;
shareModal.show();
} else {
alert('Не удалось получить ссылку для общего доступа.');
}
})
.catch(error => {
console.error('Error:', error);
alert('Произошла ошибка при генерации ссылки.');
});
});
}
if (copyLinkButton) {
copyLinkButton.addEventListener('click', function () {
sharedLinkInput.select();
sharedLinkInput.setSelectionRange(0, 99999); // For mobile devices
// Use the Clipboard API for better compatibility and security
navigator.clipboard.writeText(sharedLinkInput.value)
.then(() => {
copyLinkButton.textContent = 'Скопировано!';
setTimeout(() => {
copyLinkButton.textContent = 'Скопировать ссылку';
}, 2000);
})
.catch(err => {
console.error('Failed to copy: ', err);
alert('Не удалось скопировать ссылку.');
});
});
}
// Optional: Handle revoke share functionality if applicable
const revokeShareButton = document.getElementById('revokeShareButton');
const revokeModalElement = document.getElementById('revokeModal');
if (revokeShareButton && revokeModalElement) {
const revokeModal = new bootstrap.Modal(revokeModalElement);
revokeShareButton.addEventListener('click', function () {
revokeModal.show();
});
}
});
</script>
Enhancements:
-
Clipboard API:
Instead of using the deprecated document.execCommand('copy'), the script now uses the modern Clipboard API (navigator.clipboard.writeText) for better security and compatibility.
-
Error Handling:
Improved error handling with .catch blocks and user feedback via alerts.
-
CSRF Protection:
If your backend framework requires CSRF tokens for POST requests, ensure to include them in the headers.
5. Consolidate and Organize Scripts
Ensure that all your JavaScript related to the modal and other functionalities are organized and do not conflict with each other. Here's a consolidated view of your script sections:
<!-- Share Modal Script -->
<script>
document.addEventListener('DOMContentLoaded', function () {
// Share Modal Elements
const shareButton = document.getElementById('shareButton');
const shareModalElement = document.getElementById('shareModal');
const shareModal = new bootstrap.Modal(shareModalElement);
const sharedLinkInput = document.getElementById('sharedLinkInput');
const copyLinkButton = document.getElementById('copyLinkButton');
// Event Listener for Share Button
if (shareButton) {
shareButton.addEventListener('click', function () {
fetch("{{ url_for('share_video', video_id=current_video.id) }}", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Add CSRF token here if required
},
body: JSON.stringify({})
})
.then(response => response.json())
.then(data => {
if (data.shared_url) {
sharedLinkInput.value = data.shared_url;
shareModal.show();
} else {
alert('Не удалось получить ссылку для общего доступа.');
}
})
.catch(error => {
console.error('Error:', error);
alert('Произошла ошибка при генерации ссылки.');
});
});
}
// Event Listener for Copy Link Button
if (copyLinkButton) {
copyLinkButton.addEventListener('click', function () {
sharedLinkInput.select();
sharedLinkInput.setSelectionRange(0, 99999); // For mobile devices
navigator.clipboard.writeText(sharedLinkInput.value)
.then(() => {
copyLinkButton.textContent = 'Скопировано!';
setTimeout(() => {
copyLinkButton.textContent = 'Скопировать ссылку';
}, 2000);
})
.catch(err => {
console.error('Failed to copy: ', err);
alert('Не удалось скопировать ссылку.');
});
});
}
// Revoke Share Modal (Optional)
const revokeShareButton = document.getElementById('revokeShareButton');
const revokeModalElement = document.getElementById('revokeModal');
if (revokeShareButton && revokeModalElement) {
const revokeModal = new bootstrap.Modal(revokeModalElement);
revokeShareButton.addEventListener('click', function () {
revokeModal.show();
});
}
});
</script>
6. Finalize and Test
After implementing the above changes:
-
Test the Modal:
- Click the "Поделиться" (
shareButton) to open the modal.
- Ensure that the fetch request is made and the link populates the input field.
- Click "Скопировать ссылку" (
copyLinkButton) and verify that the link is copied to your clipboard.
-
Check Responsiveness:
Ensure the modal looks good on various screen sizes.
-
Verify Accessibility:
Ensure that the modal is accessible, with proper focus management and ARIA attributes.
-
Handle Edge Cases:
- What happens if the fetch request fails?
- Ensure the user is informed appropriately.
7. Complete Revised Template
Here's the complete revised section of your template with the fixed modal:
{% extends "base.html" %}
{% block content %}
<div class="container mt-4">
<div class="row">
<!-- Related Videos Section -->
<div class="col-md-3 order-md-2"> <!-- Left Side for Related Videos -->
<h5>Related Videos</h5>
{% for vid in last_videos %}
<div class="related-video mb-3">
<a href="/video/{{ vid.id }}" class="text-decoration-none text-dark" width="408" height="230">
<img src="/static/pre/{{ vid.id }}.jpg" class="img-fluid mb-1" >
<p class="mt-3">{{ vid.title }}</p>
</a>
</div>
{% endfor %}
</div>
<!-- Main Video Section -->
<div class="col-md-9 order-md-1"> <!-- Right Side for Main Video -->
<div class="video-container paused" data-volume-level="high">
<img class="thumbnail-img">
<div class="video-controls-container">
<!-- Control elements -->
</div>
<video width="100%" autoplay src="{{ video_src }}" controls>
<track kind="captions" srclang="en" src="assets/subtitles.vtt">
</video>
</div>
<!-- Video Title and Details -->
<h3 class="mt-3">{{ current_video.title }}</h3>
<p>Загружено {{ current_video.datetime | timesince }} назад</p>
<div class="d-flex align-items-center mb-3">
<a href="/user/{{ author.id }}" class="text-decoration-none text-dark">
<img src="{{ avatar_url }}" alt="Avatar" class="img-fluid rounded-circle me-2" style="width:90px; height:90px;">
</a>
<div>
<a href="/user/{{ author.id }}" class="text-decoration-none text-dark">{{ author.name }} {{ author.surname }}</a>
<div>
<button onclick="follow()" class="btn btn-outline-danger btn-sm {% if subscription %} active {% endif %}" type="button" name="follow" id="follow" {% if not authenticated or current_user.id == current_video.author %} disabled {% endif %}>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-person-plus-fill" viewBox="0 0 16 16">
<path d="M1 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
<path fill-rule="evenodd" d="M13.5 5a.5.5 0 0 1 .5.5V7h1.5a.5.5 0 0 1 0 1H14v1.5a.5.5 0 0 1-1 0V8h-1.5a.5.5 0 0 1 0-1H13V5.5a.5.5 0 0 1 .5-.5z"/>
</svg>
<span id="followers">{{ author.followers }}</span>
</button>
<button onclick="like()" class="btn btn-outline-danger btn-sm {% if like %} active {% endif %}" type="button" name="like" id="like" {% if not authenticated or current_user.id == current_video.author %} disabled {% endif %}>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart-fill" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
</svg>
<span id="likes">{{ current_video.likes }}</span>
</button>
<!-- Include jQuery and other scripts if necessary -->
<script src="/js/jquery-1.2.6.min.js"></script>
<script src="/js/jquery-ui-personalized-1.5.2.packed.js"></script>
<script src="/js/sprinkle.js"></script>
<!-- Follow and Like Script -->
<script type="text/javascript">
function follow() {
var follow = document.getElementById("follow");
var followers = document.getElementById("followers");
if (follow.classList.contains('active')) {
follow.classList.remove("active");
followers.innerHTML = parseInt(followers.innerText) - 1;
$.post('/api/not_follow/{{ current_video.author }}');
} else {
follow.classList.add("active");
followers.innerHTML = parseInt(followers.innerText) + 1;
$.post('/api/follow/{{ current_video.author }}');
}
}
function like() {
var likeBtn = document.getElementById("like");
var likes = document.getElementById("likes");
if (likeBtn.classList.contains('active')) {
likeBtn.classList.remove("active");
likes.innerHTML = parseInt(likes.innerText) - 1;
$.post('/api/not_like/{{ current_video.id }}');
} else {
likeBtn.classList.add("active");
likes.innerHTML = parseInt(likes.innerText) + 1;
$.post('/api/like/{{ current_video.id }}');
}
}
</script>
</div>
</div>
</div>
<p style="color: #808080">{{ current_video.description }}</p>
{% if authenticated and (current_user.id |int == current_video.author |int or current_user.id == 1) %}
<a href="{{ url_for('edit_video', video_id=current_video.id) }}" class="btn btn-warning">Edit Video</a>
<form action="{{ url_for('delete_video', video_id=current_video.id) }}" style="display: inline;">
<button type="submit" class="btn btn-danger">Delete Video</button>
</form>
{% endif %}
{% if authenticated and current_user.id == author.id %}
<!-- Share Button and Modal -->
<button type="button" class="btn btn-success" id="shareButton" data-bs-toggle="modal" data-bs-target="#shareModal">
Поделиться
</button>
<!-- Share Modal -->
<div class="modal fade" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="shareModalLabel">Ссылка для общего доступа</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
</div>
<div class="modal-body">
<input type="text" class="form-control" id="sharedLinkInput" readonly>
<button class="btn btn-secondary mt-2" id="copyLinkButton">Скопировать ссылку</button>
</div>
</div>
</div>
</div>
{% endif %}
<!-- Share Button Script -->
<script>
document.addEventListener('DOMContentLoaded', function () {
const shareButton = document.getElementById('shareButton');
const shareModalElement = document.getElementById('shareModal');
const shareModal = new bootstrap.Modal(shareModalElement);
const sharedLinkInput = document.getElementById('sharedLinkInput');
const copyLinkButton = document.getElementById('copyLinkButton');
if (shareButton) {
shareButton.addEventListener('click', function () {
fetch("{{ url_for('share_video', video_id=current_video.id) }}", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Add CSRF token here if required
},
body: JSON.stringify({})
})
.then(response => response.json())
.then(data => {
if (data.shared_url) {
sharedLinkInput.value = data.shared_url;
shareModal.show();
} else {
alert('Не удалось получить ссылку для общего доступа.');
}
})
.catch(error => {
console.error('Error:', error);
alert('Произошла ошибка при генерации ссылки.');
});
});
}
if (copyLinkButton) {
copyLinkButton.addEventListener('click', function () {
sharedLinkInput.select();
sharedLinkInput.setSelectionRange(0, 99999); // For mobile devices
navigator.clipboard.writeText(sharedLinkInput.value)
.then(() => {
copyLinkButton.textContent = 'Скопировано!';
setTimeout(() => {
copyLinkButton.textContent = 'Скопировать ссылку';
}, 2000);
})
.catch(err => {
console.error('Failed to copy: ', err);
alert('Не удалось скопировать ссылку.');
});
});
}
// If you have revoke functionality, ensure it's handled here
const revokeShareButton = document.getElementById('revokeShareButton');
const revokeModalElement = document.getElementById('revokeModal');
if (revokeShareButton && revokeModalElement) {
const revokeModal = new bootstrap.Modal(revokeModalElement);
revokeShareButton.addEventListener('click', function () {
revokeModal.show();
});
}
});
</script>
<!-- Share Functionality for General Users (Optional) -->
<button id="shareBtn" class="btn btn-primary me-2">Поделиться</button>
<script>
// Share Functionality
document.getElementById('shareBtn').addEventListener('click', () => {
const currentURL = window.location.href;
// Create a temporary input element to hold the URL
const tempInput = document.createElement('input');
tempInput.value = currentURL;
document.body.appendChild(tempInput);
// Select and copy the URL from the temporary input element
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy'); // Legacy method for compatibility
// Remove the temporary input element from the DOM
document.body.removeChild(tempInput);
// Show a confirmation alert
alert('Ссылка скопирована!');
});
// You can add other JavaScript functions here, like liking comments or editing them.
</script>
<!-- Video Controls Styling -->
<style>
.video-container {
width: 100%; /* Ensure full width within column */
}
.related-video img {
width: 100%;
border-radius: 4px;
}
</style>
<!-- Rest of your content like comments goes here -->
</div>
</div>
</div>
{% endblock %}
8. Additional Recommendations
-
CSRF Protection:
If your backend framework (like Flask with WTForms or Django) requires CSRF tokens for POST requests, ensure they are included in your fetch requests. You can pass them in the headers or include them in the request body.
-
Accessibility:
Ensure that the modal is accessible. Bootstrap modals are generally accessible, but always test with screen readers and keyboard navigation.
-
Error Feedback:
Instead of using alert, consider using Bootstrap's alert components for better UI/UX.
-
Code Organization:
For maintainability, consider moving your JavaScript to separate .js files instead of embedding them directly in the HTML.
-
Avoid Multiple Autoplay Attributes:
In your <video> tag, you have autoplay listed twice. Remove the duplicate to prevent potential conflicts.
<video width="100%" autoplay src="{{ video_src }}" controls>
<track kind="captions" srclang="en" src="assets/subtitles.vtt">
</video>
9. Test Thoroughly
After making these changes:
-
Functionality:
Ensure that clicking the "Поделиться" button opens the modal, fetches the share link, and allows copying the link.
-
Responsiveness:
Check the modal on different screen sizes to ensure it displays correctly.
-
Error Handling:
Simulate errors (like a failed fetch request) to see if error messages display as expected.
-
Browser Compatibility:
Test on different browsers to ensure consistent behavior.
By following the above steps, your Bootstrap modal should function correctly within your template, providing a seamless user experience for sharing video links.