data-country
почему-то на русском - какого чёрта? Надо, чтобы были такими же, как и id
у элементов .tabcontent
.const tabLinks = document.querySelectorAll('.tablinks');
const tabContent = document.querySelectorAll('.tabcontent');
tabLinks.forEach(n => n.addEventListener('click', openTab));
function openTab({ currentTarget: t }) {
const { country } = t.dataset;
tabLinks.forEach(n => n.classList.toggle('active', n === t));
tabContent.forEach(n => n.classList.toggle('active', n.id === country));
// или, к чёрту data-атрибуты и id, можно индексами воспользоваться;
// конечно, в этом случае необходимо, чтобы .tablinks и соответствующие им
// .tabcontent были расположены в одинаковом порядке
const index = Array.prototype.indexOf.call(tabLinks, t);
tabLinks.forEach(n => n.classList.toggle('active', n === t));
tabContent.forEach((n, i) => n.classList.toggle('active', i === index));
}
const info = new google.maps.InfoWindow();
marker.addListener('click', function() {
info.setContent('сюда засовываете свою информацию');
info.open(map, marker);
});
$('p i').text((i, text) => i % 3 ? text : 'hello, world!!');
document.querySelectorAll('p i').forEach((n, i) => {
n.textContent = i % 3 ? n.textContent : 'fuck the world';
});
p
общий родитель, то можно и не смотреть на индекс, сразу нужные элементы получить:for (const n of document.querySelectorAll('p:nth-of-type(3n + 1) i')) {
n.innerText = 'fuck everything';
}
if (inputs[el].value == "") el++; if (inputs[el].value.match(/[А-я]/)) {
moment.locale('ru');
document.querySelector('#load').addEventListener('click', function load() {
fetch('https://api.github.com/users/fristyr/repos')
.then(r => r.json())
.then(data => {
const formatIn = 'YYYY-MM-DDTHH:mm:ss';
const formatOut = 'DD MMMM YYYY';
document.querySelector('.repo-wrapp').insertAdjacentHTML('afterbegin', data.map(item => `
<article class="repo">
<a href="${item.html_url}" class="repo__name">${item.name}</a>
<br>
<span class="repo__technology">${item.language}</span>
<span class="repo__update">${moment(item.updated_at, formatIn).format(formatOut)}</span>
</article>`
).join(' '));
});
});
<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);
}
});