Добро пожаловать на сайт SEDBY

Скрипт кастомизации формы поиска в стиле Github

Скрипт кастомизации формы поиска в стиле Github

Используем клавиатурные нажатия для переброса курсора, отправки формы или ее очистки

const topSearch = document.forms.topsearch;

if (topSearch) {

  const topSearchInput = topSearch.sq;
  const topSearchInputPlaceholder = topSearchInput.getAttribute('data-placeholder');
  const topSearchButton = topSearch.querySelector('button');

  function hastext() {
    if (topSearchInput.value === '') {
      topSearchButton.disabled = true;
    } else {
      topSearchButton.disabled = false;
    }
  }

  function noActive() {
    return document.activeElement === document.body;
  }

  topSearchInput.addEventListener("keyup", function() {
    hastext();
  });

  window.addEventListener('keydown', (event) => {
    if (event.code === "Slash" && noActive()) {
      event.preventDefault();
      topSearchInput.value = topSearchInput.placeholder = '';
      topSearchInput.focus();
    } else if (event.key === "Escape" && document.activeElement === topSearchInput) {
      event.preventDefault();
      topSearchInput.value = '';
      topSearchInput.blur();
      topSearchInput.placeholder = topSearchInputPlaceholder;
      topSearchButton.disabled = true;
    } else if (event.key === "Enter" && document.activeElement === topSearchInput) {
      return;
    }
    // console.log(event.key);
  });

  window.addEventListener('click', function(event) {
    if (topSearchInput.contains(event.target)) {
      // console.log("Clicked on form input!");
      topSearchInput.value = topSearchInput.placeholder = '';
    } else if (topSearchButton.contains(event.target)) {
      // console.log("Clicked on form button!");
      return;
    } else {
      // console.log("Clicked on empty space!");
      topSearchInput.value = '';
      topSearchInput.placeholder = topSearchInputPlaceholder;
      topSearchButton.disabled = true;
    }
  });

}
  • Создан: 18.01.26 @ 20:01
  • Будет удален: никогда
  • Просмотры сниппета: 25
  • Тип кода: JavaScript
  • Владелец: admin
Блок пользователя
Регистрация на нашем сайте позволит вам общаться на форумах и получить доступ к другому полезному функционалу
Вы вошли как Гость