1

На своем сайте я хочу сделать уведомление, если пользователь не зарегистрирован, то ему писало "Пожалуйста, войдите в аккаунт или зарегистрируйтесь" Но я очень плох в написании кода на js, так как я его совсем не учил и у меня просто нет времени на более плотное его изучение. В недрах моего разума родилось вот это

function showhidepopup() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
setTimeout(function () {
    popup.classList.toggle("hidepopup");
}, 5000);
setTimeout(function () {
    popup.classList.toggle("show");
    popup.classList.toggle("hidepopup")
}, 6500);}

Данная функция вызывается из другой функции через ajax

$.ajax({
    url: "/api/" + type + "/" + pk + "/" + action + "/",
    type: 'POST',
    data: {'obj': pk},

    success: function (json) {
        if (json.user_login === 0) {
            showhidepopup()
        } else {
            current.find("[data-count='" + action + "']").text(json.count);
            $('#bookmarks-user').text(json.user_mark)
            if ($(bookmarkheart).css('fill') == "rgb(255, 255, 255)") {
                $(bookmarkheart).css({fill: "#ffc96c"});
            } else {
                $(bookmarkheart).css({fill: "#ffffff"});
            }
        }

    }
});

Подскажите пожалуйста правильную реализацию автоскрывающегося popup уведомления, потому что это ужаснейший костыль

html

<span class="popuptext" id="myPopup">Пожалуйста, войдите в аккаунт или зарегистрируйтесь
    </span>

css

.popuptext::after {
    content: "";

}

.show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s
}

.hidepopup {
    visibility: hidden;
    animation: fadeOut 1s
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}

.fadeIn {
    animation-name: fadeIn;
    opacity: 1;
    visibility: visible;
}

вот гифка как примерно это выглядитgif

1 ответ 1

0

Не буду претендовать на полноценное решение, но вот как я обычно реализую подобное:

class Notification {
  constructor(content) {
    this.content = content;
  }

  write(time = 10000) {
    const notification = document.createElement('div');
    notification.classList.add('notification');
    notification.textContent = this.content;
    notification.dataset.id = Math.random();
    document.querySelector('.notification-bar').appendChild(notification);
    setTimeout(() => {
      this._remove(notification.dataset.id);
    }, time);
  }

  _remove(id) {
    document.querySelector(`[data-id="${id}"]`).remove();
  }
}

const notification = new Notification('Войдите или зарегестрируйтесь..');
notification.write(2000);
<div class="notification-bar"></div>

То-есть во время создания самого уведомления я присваиваю ему id и планирую через определенное время найти его по id и вызвать .remove(), т.е. удалить.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.