How do you manipulate html code which was created in JavaScript? - javascript

I'm having a problem with referencing newly created HTML which was created using JavaScript. Unfortunately, I cannot seem to access the newly created html for whatever reason. I've programmed the code to where I can display the numbers, but I cannot then manipulate them. Here is the code:
let activ = document.querySelector("#fizbuz--btn");
0
let rever = document.querySelector("#fizbuz--btn1");
let displ = document.querySelector("#fizbuz--btn2");
let numbers = document.querySelector(".numbers")
let numberss = document.querySelectorAll(".num")
displ.addEventListener("click", () => {
for (i = 0; i < 22; i++) {
numbers.innerHTML += `<div class="num">${i}</div>`
}
})
if (displ.clicked == true) {
activ.addEventListener("click", () => {
for (i = 0; i < numberss.length; i++) {
if (numberss[i].innerHTML % 3 == 0 && numberss[i].innerHTML % 5 == 0) {
numberss[i].style.backgroundColor = "blue"
} else if (numberss[i].innerHTML % 3 == 0) {
numberss[i].style.backgroundColor = "red";
} else if (numberss[i].innerHTML % 5 == 0) {
numberss[i].style.backgroundColor = "orange"
}
}
})
rever.addEventListener("click", () => {
for (i = 0; i < numbers.length; i++) {
numbers[i].style.backgroundColor = "rgb(61, 133, 117)"
}
})
}
<div class="bg-color">
<div class="navbar">
<div class="nav--head">Home</div>
<div class="nav--head">About</div>
<div class="nav--head">Contact</div>
</div>
</div>
<div class="subHeading">
This is just for practice. <br> This will be styled using CSS.
</div>
<div class="fbinfo">
<div class="subhead">Multiples of 3 shall be highlighed in red</div>
<div class="subhead">Multiples of 5 shall be highlighed in orange</div>
<div class="subhead">Multiples of 3 and 5 shall be highlighed in blue</div>
</div>
<div class="fizbuzz">
<div class="btns">
<button id="fizbuz--btn2">Click Me for NUMBERS</button>
<button id="fizbuz--btn">Click Me for FIZZBUZZ</button>
<button id="fizbuz--btn1">Click Me for REVERSE</button>
</div>
<div class="numbers">
<!-- <div class="num">1</div> <div class="num">2</div>
<div class="num">3</div> <div class="num">4</div>
<div class="num">5</div> <div class="num">6</div>
<div class="num">7</div> <div class="num">8</div>
<div class="num">9</div> <div class="num">10</div>
<div class="num">11</div> <div class="num">12</div>
<div class="num">13</div> <div class="num">14</div>
<div class="num">15</div> <div class="num">16</div>
<div class="num">17</div> <div class="num">18</div>
<div class="num">19</div> <div class="num">20</div> -->
</div>
</div>

You need to assign numberss after you add the elements to the DOM. So the assignment has to be in the click listener.
There's no clicked property on button elements, so if (displ.clicked == true) will never succeed and should be removed. You can add a check for whether the numbers have been created to the beginning of the other event listeners.
let activ = document.querySelector("#fizbuz--btn");
let rever = document.querySelector("#fizbuz--btn1");
let displ = document.querySelector("#fizbuz--btn2");
let numbers = document.querySelector(".numbers")
let numberss;
displ.addEventListener("click", () => {
for (i = 0; i < 22; i++) {
numbers.innerHTML += `<div class="num">${i}</div>`
}
numberss = document.querySelectorAll(".num")
})
activ.addEventListener("click", () => {
if (!numberss) {
alert("click on NUMBERS first");
return;
}
for (i = 0; i < numberss.length; i++) {
if (numberss[i].innerHTML % 3 == 0 && numberss[i].innerHTML % 5 == 0) {
numberss[i].style.backgroundColor = "blue"
} else if (numberss[i].innerHTML % 3 == 0) {
numberss[i].style.backgroundColor = "red";
} else if (numberss[i].innerHTML % 5 == 0) {
numberss[i].style.backgroundColor = "orange"
}
}
})
rever.addEventListener("click", () => {
if (!numberss) {
alert("click on NUMBERS first");
return;
}
for (i = 0; i < numberss.length; i++) {
numberss[i].style.backgroundColor = "rgb(61, 133, 117)"
}
})
<div class="bg-color">
<div class="navbar">
<div class="nav--head">Home</div>
<div class="nav--head">About</div>
<div class="nav--head">Contact</div>
</div>
</div>
<div class="subHeading">
This is just for practice. <br> This will be styled using CSS.
</div>
<div class="fbinfo">
<div class="subhead">Multiples of 3 shall be highlighed in red</div>
<div class="subhead">Multiples of 5 shall be highlighed in orange</div>
<div class="subhead">Multiples of 3 and 5 shall be highlighed in blue</div>
</div>
<div class="fizbuzz">
<div class="btns">
<button id="fizbuz--btn2">Click Me for NUMBERS</button>
<button id="fizbuz--btn">Click Me for FIZZBUZZ</button>
<button id="fizbuz--btn1">Click Me for REVERSE</button>
</div>
<div class="numbers">
<!-- <div class="num">1</div> <div class="num">2</div>
<div class="num">3</div> <div class="num">4</div>
<div class="num">5</div> <div class="num">6</div>
<div class="num">7</div> <div class="num">8</div>
<div class="num">9</div> <div class="num">10</div>
<div class="num">11</div> <div class="num">12</div>
<div class="num">13</div> <div class="num">14</div>
<div class="num">15</div> <div class="num">16</div>
<div class="num">17</div> <div class="num">18</div>
<div class="num">19</div> <div class="num">20</div> -->
</div>
</div>

Related

Adding youtube href to calender Each Dates

Currently we are working on a online class website in which our client want to add recorded class ( classes going on online will be recorded and uploaded to YouTube in unlisted format ) videos to the the calendar dates. I will add the code of the calendar here.
Here am attaching the codepen link : https://codepen.io/internette/pen/YqJEjY
<div class="yellow">
<div id="calendar">
<div id="toolbar"></div>
<div id="color-picker" class="show"></div>
<div id="dates" class="show">
<div id="lastMt">‹</div>
<div id="nextMt">›</div>
<div id="months-cont">
<div id="months">
<span class="active month">January</span><span class="month">February</span><span class="month">March</span><span class="month">April</span><span class="month">May</span><span class="month">June</span><span class="month">July</span><span class="month">August</span><span class="month">September</span><span class="month">October</span><span class="month">November</span><span class="month">December</span>
</div>
</div>
<div id="daysotweek">
<div class="day">S</div>
<div class="day">M</div>
<div class="day">T</div>
<div class="day">W</div>
<div class="day">T</div>
<div class="day">F</div>
<div class="day">S</div>
</div>
<div id="days">
</div>
</div>
<div id="info" class="hide">
<div id="actual-date"></div>
<div id="back"><</div>
<div id="month-name"></div>
<div id="weather">
<div id="sun"></div>
<div id="mountains"></div>
<div id="rain">
<div class="raindrop" id="drop-1"></div>
<div class="raindrop center" id="drop-2"></div>
<div class="raindrop center" id="drop-3"></div>
<div class="raindrop" id="drop-4"></div>
</div>
<div id="temp">57°<span>F</span></div>
</div>
<div id="bg-card">
<div class="content"></div>
</div>
<div id="card">
<div class="content">
<div id="event-name"></div>
<div id="event-details">
<div class="col-3">
<i class="fa fa-map-marker" aria-hidden="true"></i>
<h3>Location</h3>
<p>12345 Generic Ave., Some City, Some State, 12345
</div>
<div class="col-3">
<i class="fa fa-clock-o" aria-hidden="true"></i>
<h3>Time</h3>
<p> 12:00 AM </p>
</div>
<div class="col-3">
<i class="fa fa-user" aria-hidden="true"></i>
<h3>Attendee</h3>
<p>Me, You, and 2+</p>
</div>
<div style="clear: both"></div>
</div>
</div>
</div>
</div>
<div id="colors" class="hide">
<div id="close">×</div>
<p>Choose theme color</p>
<div class="color" id="salmon"></div>
<div class="color" id="dkpink"></div>
<div class="color" id="red"></div>
<div class="color" id="redorg"></div>
<div class="color" id="orange"></div>
<div class="color" id="orgylw"></div>
<div class="color active" id="yellow"></div>
<div class="color" id="green"></div>
<div class="color" id="aqua"></div>
<div class="color" id="teal"></div>
<div class="color" id="sltbl"></div>
<div class="color" id="pwdbl"></div>
<div class="color" id="blue"></div>
<div class="color" id="purple"></div>
<div class="color" id="dkprpl"></div>
</div>
</div>
</div>
What am looking for is when the Date in the calender is clicked, toggle space should display a href of the youtube video.
Just add the anchor tag the same way you've added the rest of the elements. I've modified your code to show a link to youtube. Please check the code snippet:
var allMonths, dayArray = [],
click = 0,
dotw = [/Sun/gi, /Mon/gi, /Tue/gi, /Wed/gi, /Thu/gi, /Fri/gi, /Sat/gi];
function getAllDays(month, year) {
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
var dayToPush = new Date(date);
days.push(dayToPush);
date.setDate(date.getDate() + 1);
}
return days;
}
function getYear() {
var d = new Date();
var curYear = d.getFullYear();
return curYear;
}
function addElements(query, id) {
//for onload, use activeIndex+1 as query value
document.getElementById(id).innerHTML = '';
var allDays = getAllDays((query), getYear());
for (var i = 0; i < allDays.length; i++) {
allDays[i] = allDays[i].toString();
}
var stopNow = false,
counter = 0;
for (var i = 0; i < dotw.length; i++) {
if (allDays[0].match(dotw[i])) {
stopNow = true;
} else {
if (!stopNow) {
counter += 1;
}
}
}
for (var i = 0; i < counter; i++) {
allDays.unshift(" ");
}
for (var i = 0; i < allDays.length; i++) {
var singleDay = document.createElement('div');
singleDay.className = 'day';
singleDay.dataset.title = '';
singleDay.dataset.location = '';
//Parse Day
if (allDays[i] !== " ") {
var dayOTW = allDays[i].split(' ')[2];
if (dayOTW.charAt(0) === "0") {
allDays[i] = dayOTW.replace(/0/gi, '');
} else {
allDays[i] = dayOTW;
}
}
singleDay.innerHTML = allDays[i];
document.getElementById(id).appendChild(singleDay);
}
var allOfDays = document.querySelectorAll('#days .day');
var dayArray = [];
for (var i = 0; i < allOfDays.length; i++) {
if (i === 6 || i === 13 || i === 20 || i === 27 || i === 34) {
// dayArray.push(i);
// console.log(allOfDays[i]);
allOfDays[i].outerHTML += '<div class="day-details"><div id="input-arrow"></div><div class="input">CLICK ME</div></div>'
}
}
document.getElementById(id).innerHTML += '<div class="day-details"><div id="input-arrow"></div><div class="input">CLICK ME</div><div style="clear:both"></div>';
}
//Thanks: http://stackoverflow.com/questions/4649699/is-it-possible-to-get-elements-numerical-index-in-its-parent-node-without-loopi
function whichChild(elem) {
var i = 0;
while ((elem = elem.previousSibling) != null) ++i;
return i;
}
window.onload = function() {
allMonths = document.querySelectorAll('.month');
var monthCont = document.getElementById('months');
for (var i = 0; i < allMonths.length; i++) {
allMonths[i].innerHTML += ' ' + getYear();
}
addElements(0, 'days');
}
document.body.addEventListener('click', function(e) {
var currentActive = document.querySelector('#months .month.active');
var calWidth = Number(getComputedStyle(currentActive).width.replace(/px/gi, ''));
var activeIndex = 0;
for (var i = 0; i < allMonths.length; i++) {
if (allMonths[i].innerHTML === currentActive.innerHTML) {
activeIndex = i;
}
}
if (e.target.id === 'nextMt') {
if (activeIndex < 11) {
document.querySelector('#months .month:first-child').style.marginLeft = -(calWidth * (activeIndex + 1)) + 'px';
currentActive.className = 'month';
allMonths[activeIndex + 1].className += ' active';
addElements((activeIndex + 1), 'days');
} else {
document.querySelector('#months .month:first-child').style.marginLeft = '0px';
currentActive.className = 'month';
allMonths[0].className += ' active';
addElements(0, 'days');
}
} else if (e.target.id === 'lastMt') {
if (activeIndex > 0) {
document.querySelector('#months .month:first-child').style.marginLeft = -(calWidth * (activeIndex - 1)) + 'px';
currentActive.className = 'month';
allMonths[activeIndex - 1].className += ' active';
addElements((activeIndex - 1), 'days');
} else {
document.querySelector('#months .month:first-child').style.marginLeft = -(calWidth * 11) + 'px';
currentActive.className = 'month';
allMonths[11].className += ' active';
addElements(11, 'days');
}
}
if (e.target.id === 'color-picker') {
document.querySelector('#dates.show').className = 'hide';
document.getElementById('colors').className = 'show';
e.target.className = 'hide';
}
if (e.target.id === 'back') {
document.getElementById('color-picker').className = document.getElementById('color-picker').className.replace(/hide/gi, 'show');
document.getElementById('info').className = document.getElementById('info').className.replace(/show/gi, 'hide');
document.getElementById('dates').className = document.getElementById('dates').className.replace(/hide/gi, 'show');
}
if (e.target.className === 'color') {
var allColors = document.querySelectorAll('.color');
for (var i = 0; i < allColors.length; i++) {
allColors[i].className = 'color';
if (allColors[i].id === e.target.id) {
allColors[i].className += ' active';
}
}
document.querySelector('body > div').className = 'prev-' + document.querySelector('body > div').className + ' ' + document.querySelector('.color.active').id;
document.querySelector('body > div').className = document.querySelector('.color.active').id;
}
if (e.target.id === 'close') {
if (e.target.parentNode.id === 'colors') {
e.preventDefault();
e.target.parentNode.className = 'hide';
document.getElementById('dates').className = 'show';
document.getElementById('color-picker').className = 'show';
}
}
if (e.target.className.match(/day/gi) && e.target.parentNode.id === 'days') {
for (var i = 0; i < document.querySelectorAll('.day-details.expanded').length; i++) {
document.querySelectorAll('.day-details.expanded')[i].className = document.querySelectorAll('.day-details.expanded')[i].className.replace(/ expanded/gi, '');
}
for (var i = 0; i < document.querySelectorAll('.day.expanded').length; i++) {
if (document.querySelectorAll('.day.expanded')[i].innerHTML !== e.target.innerHTML) {
document.querySelectorAll('.day.expanded')[i].className = document.querySelectorAll('.day.expanded')[i].className.replace(/ expanded/gi, '');
}
}
if (e.target.className.match(/expanded/gi)) {
e.target.className = e.target.className.replace(/ expanded/gi, '');
} else {
e.target.className += ' expanded';
}
var currElm = e.target;
while (!currElm.nextSibling.className.match(/day-details/gi)) {
currElm = currElm.nextSibling;
}
currElm.nextSibling.className += ' expanded';
currElm.nextSibling.childNodes[0].style.marginLeft = (e.target.offsetLeft + 8) + 'px';
}
if (e.target.className === 'input') {
e.target.outerHTML = '<input type="text"/>';
document.querySelector('.day-details.expanded input').focus();
}
if (e.target.tagName === 'A' && e.target.parentNode.className === 'input') {
click += 1;
setTimeout(function() {
if (click > 1) {
document.querySelector('.day-details.expanded .input').outerHTML = '<input type="text" value="' + document.querySelector('.day-details.expanded .input a').innerHTML + '"/>';
document.querySelector('.day-details.expanded input').focus();
document.querySelector('.day-details.expanded input').setSelectionRange(document.querySelector('.day-details.expanded input').value.length, document.querySelector('.day-details.expanded input').value.length);
} else if (click === 1) {
document.getElementById('color-picker').className = document.getElementById('color-picker').className.replace(/show/gi, 'hide');
document.getElementById('month-name').innerHTML = document.querySelector('.month.active').innerHTML.replace(' 2016', '');
document.getElementById('info').className = 'show';
document.getElementById('actual-date').style.left = document.querySelector('.day.expanded').offsetLeft + 'px';
document.getElementById('actual-date').style.top = document.querySelector('.day.expanded').offsetTop + 'px';
document.getElementById('dates').className = 'hide';
TweenMax.to("#actual-date", ((document.querySelector('.day.expanded').offsetTop * 2.5) / document.getElementById('calendar').clientHeight), {
bezier: {
values: [{
x: 0,
y: 0
}, {
x: (3 * (document.getElementById('calendar').clientWidth - document.querySelector('.day.expanded').offsetLeft - 28)) / 4,
y: -(1 * (document.querySelector('.day.expanded').offsetTop - 9)) / 4
}, {
x: document.getElementById('calendar').clientWidth - document.querySelector('.day.expanded').offsetLeft - 26,
y: -(document.querySelector('.day.expanded').offsetTop - 7)
}]
}
});
document.getElementById('actual-date').innerHTML = document.querySelector('.day.expanded').innerHTML;
document.getElementById('event-name').innerHTML = document.querySelector('.day-details.expanded .input a').innerHTML;
document.querySelector('.day-details.expanded').className = document.querySelector('.day-details.expanded').className.replace(/ expanded/, '');
document.querySelector('.day.expanded').className = document.querySelector('.day.expanded').className.replace(/ expanded/, '');
}
click = 0;
}, 500);
}
});
document.body.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
document.querySelector('.day.expanded').dataset.title = document.querySelector('.day-details.expanded input').value;
if (document.querySelector('.day-details.expanded input').value.length > 0) {
document.querySelector('.day.expanded').className += ' has-event';
document.querySelector('.day-details.expanded input').outerHTML = '<div class="input"><a>' + document.querySelector('.day-details.expanded input').value + '</a></div>';
} else {
if (document.querySelector('.day.expanded').className.match(/ has-event/gi)) {
document.querySelector('.day.expanded').className = document.querySelector('.day.expanded').className.replace(/ has-event/gi, '');
}
document.querySelector('.day-details.expanded input').outerHTML = '<div class="input"></div>';
}
click = 0;
}
});
<link href="https://codepen.io/internette/pen/YqJEjY.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.2/TweenMax.min.js"></script>
<div class="yellow">
<div id="calendar">
<div id="toolbar"></div>
<div id="color-picker" class="show"></div>
<div id="dates" class="show">
<div id="lastMt">‹</div>
<div id="nextMt">›</div>
<div id="months-cont">
<div id="months">
<span class="active month">January</span><span class="month">February</span><span class="month">March</span><span class="month">April</span><span class="month">May</span><span class="month">June</span><span class="month">July</span><span class="month">August</span>
<span
class="month">September</span><span class="month">October</span><span class="month">November</span><span class="month">December</span>
</div>
</div>
<div id="daysotweek">
<div class="day">S</div>
<div class="day">M</div>
<div class="day">T</div>
<div class="day">W</div>
<div class="day">T</div>
<div class="day">F</div>
<div class="day">S</div>
</div>
<div id="days">
</div>
</div>
<div id="info" class="hide">
<div id="actual-date"></div>
<div id="back">
<</div>
<div id="month-name"></div>
<div id="weather">
<div id="sun"></div>
<div id="mountains"></div>
<div id="rain">
<div class="raindrop" id="drop-1"></div>
<div class="raindrop center" id="drop-2"></div>
<div class="raindrop center" id="drop-3"></div>
<div class="raindrop" id="drop-4"></div>
</div>
<div id="temp">57°<span>F</span></div>
</div>
<div id="bg-card">
<div class="content"></div>
</div>
<div id="card">
<div class="content">
<div id="event-name"></div>
<div id="event-details">
<div class="col-3">
<i class="fa fa-map-marker" aria-hidden="true"></i>
<h3>Location</h3>
<p>12345 Generic Ave., Some City, Some State, 12345
</div>
<div class="col-3">
<i class="fa fa-clock-o" aria-hidden="true"></i>
<h3>Time</h3>
<p> 12:00 AM </p>
</div>
<div class="col-3">
<i class="fa fa-user" aria-hidden="true"></i>
<h3>Attendee</h3>
<p>Me, You, and 2+</p>
</div>
<div style="clear: both"></div>
</div>
</div>
</div>
</div>
<div id="colors" class="hide">
<div id="close">×</div>
<p>Choose theme color</p>
<div class="color" id="salmon"></div>
<div class="color" id="dkpink"></div>
<div class="color" id="red"></div>
<div class="color" id="redorg"></div>
<div class="color" id="orange"></div>
<div class="color" id="orgylw"></div>
<div class="color active" id="yellow"></div>
<div class="color" id="green"></div>
<div class="color" id="aqua"></div>
<div class="color" id="teal"></div>
<div class="color" id="sltbl"></div>
<div class="color" id="pwdbl"></div>
<div class="color" id="blue"></div>
<div class="color" id="purple"></div>
<div class="color" id="dkprpl"></div>
</div>
</div>
</div>

Show active class

I want to add class 'active' to next div 1 second before first is removed.
Practically, I want to have an 'active' class on 2 elements at the same time for that 1 second.
Can someone help me?
Thanks
<div class="map-inner">
<div class="map-location-outer">
<div class="map-location-inner location1 active">
<div class="map-location">
<div class="map-icon">
<img src="i/content/map-icon2.svg">
</div>
<span class="map-pin"><span></span></span>
</div><!-- map-location -->
</div>
</div>
<div class="map-location-outer">
<div class="map-location-inner location2">
<div class="map-location">
<div class="map-icon">
<img src="i/content/map-icon3.svg">
</div>
<span class="map-pin"><span></span></span>
</div><!-- map-location -->
</div>
</div>
<div class="map-location-outer">
<div class="map-location-inner location3">
<div class="map-location">
<div class="map-icon">
<img src="i/content/map-icon1.png">
</div>
<span class="map-pin"><span></span></span>
</div><!-- map-location -->
</div>
</div>
</div>
var x = 1;
function updateClass() {
let a = $(".map-location-inner.active");
a.removeClass("active");
a = a.parent().next(".map-location-outer");
if (a.length == 0)
a = $(".map-location-outer").first();
a.find(".map-location-inner").addClass("active");
}
setInterval(function () {
updateClass();
}, x * 5500);
You can use setTimeout to wait before removing 1st .active class and add 2nd .active class before removing 1st one.
var x = 1;
function updateClass() {
let a = $(".map-location-inner.active");
let b = a.parent().next(".map-location-outer");
if (b.length == 0)
b = $(".map-location-outer").first();
b.find(".map-location-inner").addClass("active");
setTimeout(function() {
a.removeClass("active");
}, 1000);
}
setInterval(function () {
updateClass();
}, x * 5500);

1 button to toggle 3 sort variations

I have 3 buttons in my view. Each of them have single work to do.
Now I want them to be a one key that is doing 3 things:
With each click toggling through each sort
const buttonAsc = document.getElementById("Sort-item-asc")
const buttonDesc = document.getElementById("Sort-item-desc")
const buttonNo = document.getElementById("Sort-item-no")
const times = document.getElementsByClassName("time")
const originalHours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
originalHours.push(hour)
}
buttonAsc.onclick = function() {
let hours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
hours.push(hour)
}
hours.sort()
for (let i = 0; i < hours.length; i++) {
times[i].firstElementChild.innerText = hours[i];
}
}
buttonDesc.onclick = function() {
let hours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
hours.push(hour)
}
hours.sort()
hours.reverse()
for (let i = 0; i < hours.length; i++) {
times[i].firstElementChild.innerText = hours[i];
}
}
buttonNo.onclick = function() {
for (let i = 0; i < originalHours.length; i++) {
times[i].firstElementChild.innerText = originalHours[i];
}
}
<div class="full-item">
<div class="buttons">
<div class="button-item">
<button id="Sort-item-asc">Sort Asc</button>
</div>
<div class="button-item">
<button id="Sort-item-desc">Sort Desc</button>
</div>
<div class="button-item">
<button id="Sort-item-no">No Sort</button>
</div>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
You could create a super-array that has the three versions of the list (ascending, descending, unsorted). Then at every click extract the first list from that super-array, and at the same time add it again at the back of the list. Use this list for the display:
const button = document.getElementById("Sort-item");
const times = [...document.getElementsByClassName("time")];
const originalHours = times.map(time => time.textContent);
// Pre-build the three versions of the list
const allHours = [[...originalHours].sort(), [...originalHours].sort().reverse(), originalHours];
button.addEventListener("click", function() {
// Cycle the three lists:
const hours = allHours.shift();
allHours.push(hours);
for (let i = 0; i < hours.length; i++) {
times[i].firstElementChild.textContent = hours[i];
}
});
<div class="full-item">
<div class="buttons">
<div class="button-item">
<button id="Sort-item">Sort Toggle</button>
</div>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
If you need the div elements to be relocated (because you had specific attributes on them or references to them), then you could store them similarly in the arrays:
const button = document.getElementById("Sort-item");
const container = document.querySelector(".item-sort");
const times = [...document.querySelectorAll(".time")];
const originalItems = times.map(time => [time.parentNode, time.textContent]);
const sortedItems = [...originalItems].sort((a,b) => a[1].localeCompare(b[1]))
.map(a => a[0]); // Only keep node reference
// Pre-build the three versions of the list
const allItems = [sortedItems, [...sortedItems].reverse(),
originalItems.map(a => a[0])];
button.addEventListener("click", function() {
// Cycle the three lists:
const items = allItems.shift();
allItems.push(items);
for (const item of items) {
container.appendChild(item);
}
});
<div class="full-item">
<div class="buttons">
<div class="button-item">
<button id="Sort-item">Sort Toggle</button>
</div>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
Have you considered keeping only one button?
You could a global variable "count" that you increment each time the button is clicked. Then, with an "if" statement, you could fire each of the three functions, depending on the value of the counter?
A more user friendly approach would be to use a dropdown instead of multiple clicks.
Allowing you to choose which sort method you want instead of having to determine what happened from the result.
const sortOptions = document.getElementById('Sort-options');
const times = document.getElementsByClassName("time");
const originalHours = [];
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
originalHours.push(hour)
}
sortOptions.addEventListener('change', function(event){
let selection = event.target.value;
let hours = originalHours.slice();
if (selection === 'Sort Asc') {
hours.sort();
}
if (selection === 'Sort Desc') {
hours.sort().reverse()
}
for (let i = 0; i < hours.length; i++) {
times[i].firstElementChild.innerText = hours[i];
}
});
<div class="full-item">
<select id="Sort-options">
<option value="" selected>No Sort</option>
<option value="Sort Asc">Sort Asc</option>
<option value="Sort Desc">Sort Desc</option>
</select>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
I understand you want to move the item div around
const button = document.getElementById("sort");
const items = document.querySelectorAll(".item");
const times = document.querySelectorAll(".time");
const container = document.querySelector(".item-sort");
const originalHours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
originalHours.push(hour);
items[i].setAttribute("data-time",hour); // add the time to the item div
}
const sortClasses = ["nosort","asc","desc"];
let cnt = 0;
button.addEventListener("click",function() {
let hours = originalHours.slice();
this.className="";
cnt++;
if (cnt>=sortClasses.length) cnt=0;
this.classList.toggle(sortClasses[cnt]);
if (this.classList.contains("asc")) {
hours.sort();
this.innerText = "Descending";
}
else if (this.classList.contains("desc")) {
hours.sort().reverse();
this.innerText = "Unsorted";
}
else this.innerText = "Ascending";
for (let i = 0; i < hours.length; i++) {
let sel = "[data-time='"+hours[i]+"']"; // selector based on time
let itemDiv = document.querySelector(sel);
if (itemDiv) container.appendChild(itemDiv);
}
});
<div class="full-item">
<div class="buttons">
<div class="button-item">
<button id="sort" class="nosort" title="Click to sort">Ascending</button>
</div>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"><img src="https://via.placeholder.com/300.png/9ff?text=15:20" /></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"><img src="https://via.placeholder.com/300.png/99f?text=13:10" /></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"><img src="https://via.placeholder.com/300.png/ff9?text=18:40" /></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
There are many ways to do this and one of them is as follow
const buttonAsc = document.getElementById("Sort-item-asc")
const buttonDesc = document.getElementById("Sort-item-desc")
const buttonNo = document.getElementById("Sort-item-no")
const times = document.getElementsByClassName("time")
const originalHours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
originalHours.push(hour)
}
buttonAsc.onclick = function() {
let hours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
hours.push(hour)
}
hours.sort()
for (let i = 0; i < hours.length; i++) {
times[i].firstElementChild.innerText = hours[i];
}
buttonAsc.parentElement.classList.remove("active");
buttonDesc.parentElement.classList.add("active");
}
buttonDesc.onclick = function() {
let hours = []
for (let i = 0; i < times.length; i++) {
const hour = times[i].innerText;
hours.push(hour)
}
hours.sort()
hours.reverse()
for (let i = 0; i < hours.length; i++) {
times[i].firstElementChild.innerText = hours[i];
}
buttonDesc.parentElement.classList.remove("active");
buttonNo.parentElement.classList.add("active");
}
buttonNo.onclick = function() {
for (let i = 0; i < originalHours.length; i++) {
times[i].firstElementChild.innerText = originalHours[i];
}
buttonNo.parentElement.classList.remove("active");
buttonAsc.parentElement.classList.add("active");
}
.button-item {
display: none;
}
.button-item.active{
display: block;
}
<div class="full-item">
<div class="buttons">
<div class="button-item active">
<button id="Sort-item-asc">Sort Asc</button>
</div>
<div class="button-item">
<button id="Sort-item-desc">Sort Desc</button>
</div>
<div class="button-item">
<button id="Sort-item-no">No Sort</button>
</div>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>

Why div inside div is color is not changing through JavaScript array

var ar = ['.two_in','.three_in','.four_in'], pb = "> *";
ar.forEach(function(x){
var sel = document.querySelectorAll( x + pb);
var colors = {};
colors[ar[0]] = 'blue';
colors[ar[1]] = 'green';
colors[ar[2]] = 'red';
for(var i = 0;i<sel.length;i++){
sel[i].style.backgroundColor = colors[sel[i].className];
}
})
<div class="two_in">
<div class="demo">blue</div>
<div class="demo">blue</div>
<div class="demo">blue</div>
</div>
<br>
<div class="three_in">
<div class="demo">green</div>
<div class="demo">green</div>
<div class="demo">green</div>
</div>
<br>
<div class="four_in">
<div class="demo">red</div>
<div class="demo">red</div>
<div class="demo">red</div>
</div>
I want to change all div color inside two_in to blue, three_in to green, and four_in to red respectively, what's the missing code? Can anyone explain it?
Example:
The all div inside two_in (three div whose div class is demo) should be blue color and as for the three_in and four_in.
Here is the mistake:
colors[ar[0]] = 'blue';
colors[ar[1]] = 'green';
colors[ar[2]] = 'red';
It is assigning a non primitive index there. What you need to is:
var ar = ['.two_in', '.three_in', '.four_in'],
pb = " > *";
ar.forEach(function(x) {
var sel = document.querySelectorAll(x + pb);
var colors = {};
colors[0] = 'blue';
colors[1] = 'green';
colors[2] = 'red';
for (var i = 0; i < sel.length; i++) {
sel[i].style.backgroundColor = colors[i];
}
})
<div class="two_in">
<div class="demo">blue</div>
<div class="demo">blue</div>
<div class="demo">blue</div>
</div>
<br>
<div class="three_in">
<div class="demo">green</div>
<div class="demo">green</div>
<div class="demo">green</div>
</div>
<br>
<div class="four_in">
<div class="demo">red</div>
<div class="demo">red</div>
<div class="demo">red</div>
</div>
Is the above what you want? Or, if you need the colour based on the text, then...
var ar = ['.two_in', '.three_in', '.four_in'],
pb = " > *";
ar.forEach(function(x) {
var sel = document.querySelectorAll(x + pb);
var colors = {};
colors['blue'] = 'blue';
colors['green'] = 'green';
colors['red'] = 'red';
for (var i = 0; i < sel.length; i++) {
sel[i].style.backgroundColor = colors[sel[i].innerHTML.trim()];
}
})
<div class="two_in">
<div class="demo">blue</div>
<div class="demo">blue</div>
<div class="demo">blue</div>
</div>
<br>
<div class="three_in">
<div class="demo">green</div>
<div class="demo">green</div>
<div class="demo">green</div>
</div>
<br>
<div class="four_in">
<div class="demo">red</div>
<div class="demo">red</div>
<div class="demo">red</div>
</div>

Showing and hiding div tags by their ID order using a button

I made a small questionnaire and I placed each question in a div tag. I'm trying to display the div tags in order, so when the user click the "Next" button it will move on to the next div and hide the previous one. Kind of like a paging system? I thought about creating some sort of a for loop but I feel like my code is super messy. Any suggestions? Thanks in advance.
<form>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div>
<button type="button">Next</button>
<button type="button">Back</button>
</form>
<script>
visible(){
document.getElementById('1').style.display = "block";
document.getElementById('2').style.display = "none";
document.getElementById('3').style.display = "none";
document.getElementById('4').style.display = "none";
document.getElementById('5').style.display = "none";
document.getElementById('6').style.display = "none";
document.getElementById('7').style.display = "none";
document.getElementById('8').style.display = "none";
document.getElementById('9').style.display = "none";
document.getElementById('10').style.display = "none";
}
You can use javascript functions to setup your divs. This uses jQuery for smooth transition as well.
<div id="1">Question 1</div>
<div id="2" class="hidden">Question 2</div>
<div id="3" class="hidden">Question 3</div>
<div id="4" class="hidden">Question 4</div>
<div id="5" class="hidden">Question 5</div>
<div id="6" class="hidden">Question 6</div>
<div id="7" class="hidden">Question 7</div>
<div id="8" class="hidden">Question 8</div>
<div id="9" class="hidden">Question 9</div>
<div id="10" class="hidden">Question 10</div>
<button type="button" onclick="reverseDiv();">Back</button>
<button type="button" onclick="advanceDiv();">Next</button>
<script>
var divNum=1;
advanceDiv = function() {
if(divNum < 10) {
divNum++;
$('#' + (divNum-1)).slideToggle();
$('#' + divNum).slideToggle();
}
else {
/* last slide reached */
alert('last question');
}
}
reverseDiv = function() {
if(divNum > 1) {
divNum--;
$('#' + (divNum+1)).slideToggle();
$('#' + divNum).slideToggle();
}
else {
alert('first question');
}
}
</script>
Here's a jsfiddle to show functionality (and also includes arrow keys to move between functions): https://jsfiddle.net/79xupebb/1/
To think about the start and the end in this is case is important.
What happens if you are at the end and then click the next button? Then you have to go to the start. And if you are at the start point and click the previous button, you have to go to the end:
if(current === start && direction === "prev") current = end;
if(current === end && direction === "next") current = start;
To make all the divs display: none and only the first one display: block use CSS, like:
#container div {
display: none;
}
#container div:first-child {
display: block;
}
with HTML
<div id="container">
<div id="1">div1</div>
<div id="2">div2</div>
<div id="3">div3</div>
...
</div>
All togehter with plain JavaScript:
var prev = document.getElementById("prev");
var next = document.getElementById("next");
var start = 1;
var end = 10;
var current = 1;
function slide(direction, start, end) {
document.getElementById(current).style.display = "none";
if(current === start && direction === "prev") {
current = end;
} else if(current === end && direction === "next") {
current = start;
} else if(direction === "next") {
current += 1;
} else if(direction === "prev") {
current -= 1;
}
document.getElementById(current).style.display = "block";
}
prev.addEventListener("click", function() {
slide("prev", start, end);
});
next.addEventListener("click", function() {
slide("next", start, end);
});
#container div {
display: none;
}
#container div:first-child {
display: block;
}
<div id="container">
<div id="1">div1</div>
<div id="2">div2</div>
<div id="3">div3</div>
<div id="4">div4</div>
<div id="5">div5</div>
<div id="6">div6</div>
<div id="7">div7</div>
<div id="8">div8</div>
<div id="9">div9</div>
<div id="10">div10</div>
<button id="prev" type="button">Previous</button>
<button id="next" type="button">Next</button>
</div>
There is a simple way to do what you want. Use a counter (current), start it at 1 and increase it/ decrease it whenever the user clicks one of the buttons, then loop through your div list and make them all display:none except the one that corresponds to your current value.
var current = 1;
function next(){
current+=1;
for(var i = 1; i<10; i++){
document.getElementById(i).style.display = ((current==i)?"block":"none");
}
}
function back(){
current-=1;
for(var i = 1; i<=10; i++){
document.getElementById(i).style.display = ((current==i)?"block":"none");
}
}
<form>
<div id="1" style="display:block">one</div>
<div id="2" style="display:none">two</div>
<div id="3" style="display:none">three</div>
<div id="4" style="display:none">four</div>
<div id="5" style="display:none">five</div>
<div id="6" style="display:none">six</div>
<div id="7" style="display:none">aaaa</div>
<div id="8" style="display:none">bbb</div>
<div id="9" style="display:none">nnn</div>
<div id="10" style="display:none">ggg</div>
<button type="button" onclick="next()">Next</button>
<button type="button" onclick="back()">Back</button>
</form>
Note: My code has no safeguards so it will go below 1 and above 10, you can always check with an if statement in each of the buttons' functions.
var i;
for(i=2;i<=10;i++)
document.getElementById(''+i).style.display = "none";
i=1;
document.getElementById('btnNext').onclick = function(){
document.getElementById(''+i).style.display = "none";
i++;
document.getElementById(''+i).style.display = "block";
}
document.getElementById('btnPrev').onclick = function(){
document.getElementById(''+i).style.display = "none";
i--;
document.getElementById(''+i).style.display = "block";
}
<form>
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
<div id="5">5</div>
<div id="6">6</div>
<div id="7">7</div>
<div id="8">8</div>
<div id="9">9</div>
<div id="10">10</div>
<button type="button" id="btnNext">Next</button>
<button type="button" id="btnPrev">Back</button>
</form>
Add the onclick property to your buttons first:
<button type="button" onclick="showNext()">Next</button>
<button type="button" onclick="showPrev()">Back</button>
Then retrieve the divs by adding the class="quest" to every div
var el = document.getElementsByClassName("quest");
function showNext(){
for(var i=0;i<el.length; i++){
if (el[i].style.display == "block"){
el[i].style.display = "none";
if ((i+1)==el.length) i=-1;
el[i+1].style.display = "block";
break;
}
}
}
function showPrev(){
for(var i=0;i<el.length; i++){
if (el[i].style.display == "block"){
el[i].style.display = "none";
if (i==0) i=el.length;
el[i-1].style.display = "block";
break;
}
}
}

Categories