profile.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. document.addEventListener('DOMContentLoaded', function() {
  2. const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  3. if (!currentUser) {
  4. window.location.href = 'login.html';
  5. }
  6. document.getElementById('profile-username').value = currentUser.username;
  7. document.getElementById('profile-email').value = currentUser.email;
  8. if (currentUser.picture) {
  9. const profilePicturePreview = document.getElementById('profile-picture-preview');
  10. profilePicturePreview.src = currentUser.picture;
  11. profilePicturePreview.style.display = 'block';
  12. }
  13. document.getElementById('profile-form').addEventListener('submit', function(event) {
  14. event.preventDefault();
  15. const newUsername = document.getElementById('profile-username').value;
  16. const newEmail = document.getElementById('profile-email').value;
  17. const profilePicture = document.getElementById('profile-picture').files[0];
  18. if (profilePicture) {
  19. const reader = new FileReader();
  20. reader.onload = function(e) {
  21. currentUser.picture = e.target.result;
  22. saveUserData(newUsername, newEmail, currentUser.picture);
  23. };
  24. reader.readAsDataURL(profilePicture);
  25. } else {
  26. saveUserData(newUsername, newEmail, currentUser.picture);
  27. }
  28. });
  29. document.getElementById('logout').addEventListener('click', function() {
  30. localStorage.removeItem('currentUser');
  31. window.location.href = 'index.html';
  32. });
  33. function saveUserData(username, email, picture) {
  34. let users = JSON.parse(localStorage.getItem('users'));
  35. const currentUser = JSON.parse(localStorage.getItem('currentUser')); // Получаем текущего пользователя
  36. const userIndex = users.findIndex(u => u.username === currentUser.username);
  37. if (userIndex !== -1) {
  38. users[userIndex].username = username;
  39. users[userIndex].email = email;
  40. localStorage.setItem('users', JSON.stringify(users));
  41. currentUser.username = username;
  42. currentUser.email = email;
  43. localStorage.setItem('currentUser', JSON.stringify(currentUser));
  44. alert('Данные сохранены успешно!');
  45. }
  46. }
  47. });