<div id="slider"></div>
<div id="value"></div>
const min = 100;
const max = 500;
$('#slider').slider({
min,
max,
value: min + Math.random() * (max - min) | 0,
range: 'min',
animate: 'fast',
slide: (e, ui) => $('#value').html(max - ui.value + min),
});
const options = [
[ 'hello, world!!', 'fuck the world', 'fuck everything' ],
500,
(elem => item => elem.textContent = item)
(document.querySelector('.slide-words')),
];
function interval(arr, delay, callback) {
let i = -1;
return arr.length
? setInterval(() => callback(arr[i = -~i % arr.length]), delay)
: null;
}
const intervalId = interval(...options);
// надо остановить, делаем так: clearInterval(intervalId);
function interval(arr, delay, callback) {
let timeoutId = null;
arr.length && (function next(i) {
timeoutId = setTimeout(() => {
callback(arr[i]);
next((i + 1) % arr.length);
}, delay);
})(0);
return () => clearTimeout(timeoutId);
}
const stop = interval.apply(null, options);
// надо остановить, делаем так: stop();
parseInt('')
будет NaN
.parseInt($(this).val())
на parseInt($(this).val()) || 0
. <span>hello, world!!... fuck the world... fuck everything</span>
body {
margin: 0;
background: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
span {
color: red;
font-size: 24px;
font-family: monospace;
}
.xxx {
display: inline-block;
min-width: 10px;
transition: all 0.2s;
transform: scale(1);
}
.hidden {
opacity: 0;
transform: scale(30);
}
function show(el) {
el.innerHTML = Array
.from(el.innerText, n => `<span class="xxx hidden">${n}</span>`)
.join('');
el.querySelectorAll('span').forEach((n, i) => {
setTimeout(() => n.classList.remove('hidden'), 100 * i);
});
}
show(document.querySelector('span'));
const getValue = el => el.textContent.match(/"(.*?)"/)[1];
// или
const getValue = ({ innerText: t }) =>
JSON.parse(t.slice(t.indexOf('['), -~t.indexOf(']'))).shift();
document.querySelectorAll('li button').forEach(function(n) {
n.addEventListener('click', this);
}, e => console.log(getValue(e.target)));
document.querySelector('ul').addEventListener('click', e => {
if (e.target.tagName === 'BUTTON') {
console.log(getValue(e.target));
}
});
const sums = arr.reduce((acc, n, i) => (
(i & 1) || acc.push(0),
acc[acc.length - 1] += n,
acc
), []);
// или
const sums = arr.reduce(
(acc, n, i) => (acc[i / 2 | 0] += n, acc),
Array(Math.ceil(arr.length / 2)).fill(0)
);
// или
const sums = Array.from(
{ length: arr.length / 2 + arr.length % 2 },
(n, i) => arr[i * 2] + (arr[i * 2 + 1] || 0)
);
// или
const sums = eval(`[${arr}]`.replace(/(\d+),(\d+)/g, '$1+$2'));
const result = sums.join(' ');
// или
const result = sums.reduce((acc, n) => acc + (acc && ' ') + n, '');
// или
const result = ''.concat(...sums.flatMap((n, i) => i ? [ ' ', n ] : n));
// или
const result = String(sums).replace(/,/g, ' ');
const isPositiveInteger = RegExp.prototype.test.bind(/^\d+$/);
// или
const isPositiveInteger = str =>
!(!str || str.replace(/\d/g, ''));
// или
const isPositiveInteger = str =>
Boolean(str) && !str.match(/\D/);
Нужна именно регулярка, т.к. числа большой длины.
const isPositiveInteger = str =>
str !== '' && [...str].every(n => Number.isInteger(+n));
// или
function isPositiveInteger(str) {
for (const n of str) {
if (!'0123456789'.includes(n)) {
return false;
}
}
return str.length > 0;
}
// или
function isPositiveInteger(str) {
let result = !!str;
for (let i = 0; i < str.length && result; i++) {
const n = str.charCodeAt(i);
result = 47 < n && n < 58;
}
return result;
}
const containerSelector = '.form-fields';
const itemSelector = `${containerSelector} .wrapper-from-field`;
const activeClass = 'active';
const toggle = item => item
.closest(containerSelector)
.querySelectorAll(itemSelector)
.forEach(n => n.classList.toggle(activeClass, n === item));
document.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('change', this);
}, e => toggle(e.currentTarget));
// или
document.addEventListener('change', e => {
const item = e.target.closest(itemSelector);
if (item) {
toggle(item);
}
});
const getCard = button => $(`#card${button.id.match(/\d+/).pop()}`);
$('[id^="button"]').hover(
e => getCard(e.target).fadeIn(),
e => getCard(e.target).fadeOut(),
);
const $buttons = $('[id^=button]').hover(function(e) {
this.eq($buttons.index(e.target))[e.type === 'mouseenter' ? 'fadeIn' : 'fadeOut']();
}.bind($('[id^=card]')));
top += 2
, вы вовсе не с числом работаете. Меняйте имя переменной или выполняйте свой код в области видимости, отличной от глобальной или сделайте свой top свойством какого-нибудь объекта или... select.innerHTML = [
{ val: 69, optionText: 'hello, world!!', selectText: 'HELLO, WORLD!!' },
{ val: 187, optionText: 'fuck the world', selectText: 'FUCK THE WORLD' },
{ val: 666, optionText: 'fuck everything', selectText: 'FUCK EVERYTHING' },
].map(n => `
<option value="${n.val}" hidden>${n.selectText}</option>
<option value="${n.val}">${n.optionText}</option>
`).join('');
select.addEventListener('change', e => e.target.value = e.target.value);
const source = document.querySelector('.menu');
const target = document.querySelector('#parent');
for (const n of source.children) {
target.appendChild(n.cloneNode(true));
}
// или
source.querySelectorAll(':scope > *').forEach(n => {
target.insertAdjacentElement('beforeend', n.cloneNode(true));
});
// вложенные узлы копии добавляем в целевой элемент
target.append(...source.cloneNode(true).children);
// или, заменяем целевой элемент копией исходного
target.replaceWith(source.cloneNode(true));
target.innerHTML = source.innerHTML;
// или
target.outerHTML = source.outerHTML;