Изменение заголовка h2 при вводе текста в input
Столкнулся с проблемой. Хочу чтобы при вводе в инпут текста добавлялось в содержимое элемента h1 с задержкой 300мс.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<h1 id="title"></h2>
<input type="text" id="input">
</body>
</html>
let input = document.querySelector('#input');
let title = document.querySelector('#title');
function replaceTitle(e) {
e.preventDefault();
title.textContent = input.value;
}
setTimeout(replaceTitle(), 300);
Ответы (3 шт):
Автор решения: Aziz Umarov
→ Ссылка
Попробуйте повесить на событие ввода.
let input = document.querySelector('#input');
let title = document.querySelector('#title');
input.addEventListener("keyup", (e)=>{
e.preventDefault();
setTimeout(replaceTitle, 300);
});
function replaceTitle() {
title.textContent = input.value; // это замена title
document.title = input.value; // это замена title документа
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<h2 id="title"></h2>
<input type="text" id="input">
</body>
Автор решения: Сергей
→ Ссылка
document.addEventListener("DOMContentLoaded", function () {
let input = document.createElement("input");
document.body.append(input);
let h2 = document.createElement("h2");
document.body.append(h2);
let timeout;
function enteringText() {
let text = input.value;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
h2.innerHTML = text;
}, 300);
}
input.addEventListener("input", enteringText);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer src="example_2.js"></script>
<title>Document</title>
</head>
<body>
</body>
</html>
Автор решения: Нагибаю ТвоиМечты
→ Ссылка
// add element, style and class
let input = document.createElement('input');
input.classList.add('input')
input.type = 'text';
let h2 = document.createElement('h2');
h2.classList.add('head')
h2.style.padding = '10px 0';
h2.style.backgroundColor = '#eee';
document.body.append(input);
document.body.append(h2);
// function
// Ищем элементы по классу
let classInput = document.querySelector('.input');
let classHead = document.querySelector('.head');
// Пустая переменная для взаимодействия с ( clearTimeout() ) и ( setTimeout() )
let timeout;
// Функция которая выводит текст из ( input ) в ( h2 )
function inputText() {
// используем ( .textContent ) чтобы избежать неприятностей :)
classHead.textContent = classInput.value;
}
// Функция которая дает нам задержку
function outputText() {
// Здесь будет очищаться наш таймаут.
// Пока текст набирают со скоростью 300мс и меньше(оооочень быстро),
// то текст не покажется в заголовке
timeout = clearTimeout(timeout);
// Здесь выводиться текст в заголовке с задержкой в 300мс
// Используем нашу функцию что выше ( inputText )
timeout = setTimeout(inputText, 300);
}
// Запускаем нашу функцию ( outputText ) по событию ( input )
// input - ввод(взаимодействие) текста(с нашей строкой ввода)
classInput.addEventListener('input', outputText);
Как-то так. Только что все теги тоже через JS добавил. А так принцип поиска по классу. Буду думать что помогло :)