Skip to content

Commit

Permalink
feat: Add animal quick add functionality with geolocation and toast n…
Browse files Browse the repository at this point in the history
…otifications
  • Loading branch information
drikusroor committed Oct 12, 2024
1 parent 34646ea commit 245be2c
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
95 changes: 95 additions & 0 deletions src/animals/static/js/add_animal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
document.addEventListener('DOMContentLoaded', function() {
const buttons = document.querySelectorAll('.animal-add-btn');
buttons.forEach(button => {

const initialInnerHTML = button.innerHTML;

button.addEventListener('click', async function() {
const animalTypeId = this.dataset.animalType;

button.disabled = true;
button.classList.add('opacity-50', 'cursor-not-allowed');

let location = '';

try {
const position = await getCurrentLocation();
location = `${position.coords.latitude},${position.coords.longitude}`;
} catch (error) {
console.error('Error getting location:', error);
}

fetch('/animals/api/animals/quick_add_animal/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
body: JSON.stringify({
animal_type: animalTypeId,
location,
})
})
.then(response => response.json())
.then(data => {
console.log('Animal added:', data);
// You can add some feedback here, like a toast notification
showToast('Animal added successfully!');
})
.catch(error => {
console.error('Error:', error);
showToast('Failed to add animal.', 'error');
})
.finally(() => {
// Wait for 1 second before enabling the button again
// This is to prevent multiple clicks
setTimeout(() => {
button.disabled = false;
button.classList.remove('opacity-50', 'cursor-not-allowed');
}, 1000);
});
});
});
});

// Get location through the browser's geolocation API as a promise
async function getCurrentLocation() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject('Geolocation is not supported by your browser');
} else {
navigator.geolocation.getCurrentPosition(
position => resolve(position),
error => reject(error)
);
}
});
}

// Function to get CSRF token
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

// Simple toast notification function
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `fixed z-[10000] bottom-4 right-4 px-4 py-2 rounded-md text-white ${type === 'success' ? 'bg-green-700' : 'bg-red-700'} transition-opacity duration-300 drop-shadow-lg`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
1 change: 1 addition & 0 deletions src/brazil_blog/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
{# Global javascript #}
<script type="text/javascript" src="{% static 'js/brazil_blog.js' %}"></script>
<script type="text/javascript" src="{% static 'js/add_drink.js' %}"></script>
<script type="text/javascript" src="{% static 'js/add_animal.js' %}"></script>

{% block extra_js %}
{# Override this in templates to add extra javascript #}
Expand Down
5 changes: 5 additions & 0 deletions src/brazil_blog/templates/includes/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ <h3 class="pl-4 mt-3 font-bold">{% trans "Hello" %} {{ user.username|default:""
{% quick_drink_add_buttons %}
</div>
</li>
<li class="px-4 mt-4">
<div id="quick-drink-add-container" class="p-4 bg-slate-100 rounded-b-3xl border-slate-500">
{% quick_animal_add_buttons %}
</div>
</li>
{% endif %}
</ul>
</div>
Expand Down

0 comments on commit 245be2c

Please sign in to comment.