I build this multiple choice questions but not in quiz format. I have in the page an sequence of divs with questions and each question have their own choices and check button, so they are independent and free for the users to respond one, all or none. I made the content (questions and answers) wrote directly on HTML file because I have others working with me and they have only contact with the HTML files to implement some classes.
My problem is that I made one question and it's working, but when a duplicated the div with another question the interaction affects all the divs. For exemple:
when you select an option, the check button turns from disable to enable, but if you select an option from the second question, the check button from the first question change.
if you want to interact with two question in the same time, when you select an option in the first question, when you select an option in the second question on the first that you selected turns unselected.
So I want to make each div with question be independent, in a way that we can create as many questions as we want.
I created this https://jsfiddle.net/1yLwrcek/2/
let mcqCard = document.querySelectorAll('.mcq-card');
let answerOption = document.querySelectorAll('.mcq__answers li');
let submitButton = document.querySelector('.mcq__submit button');
let submitFeedback = document.querySelector('.mcq__submit--feedback');
let score = 0;
(function () {
// Select option, clear the others and enable submit
answerOption.forEach(option => {
option.addEventListener('click', function () {
console.log(submitButton.getAttribute('type'));
answerSelect(option);
});
});
//Submit button to check only selected class option.
submitButton.addEventListener('click', function () {
if (submitButton.getAttribute('type') === 'submit' && submitButton.getAttribute('aria-disabled') === 'false') {
butttonCheck();
} else {
buttonReset();
}
});
})();
function answerSelect(e) {
if (submitButton.getAttribute('type') === 'submit') {
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
element.classList.remove('mcq__answers--selected');
}
e.classList.add('mcq__answers--selected');
submitButton.setAttribute('aria-disabled', 'false');
}
}
function incorrectAnswer(event) {
event.classList.remove('mcq__answers--selected');
event.classList.add('mcq__answers--incorrect');
submitFeedback.innerHTML = `<span class="material-symbols-rounded">cancel</span>Resposta errada! <br class="d-lg-none" />Tente novamente.`;
submitFeedback.classList.remove('d-none', 'mcq__submit__feedback--correct');
submitFeedback.classList.add('mcq__submit__feedback--incorrect');
}
function correctAnswer(event) {
event.classList.remove('mcq__answers--selected');
event.classList.add('mcq__answers--correct');
submitFeedback.innerHTML = `<span class="material-symbols-rounded">check_circle</span>Resposta correta! <br class="d-lg-none" />VocĂȘ acertou em ${score} tentativa(s).`;
submitFeedback.classList.remove('d-none', 'mcq__submit__feedback--incorrect');
submitFeedback.classList.add('mcq__submit__feedback--correct');
}
function blockAnswerOption() {
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
element.classList.add('mcq__answers--blocked');
}
}
function butttonCheck() {
if (submitButton.getAttribute('type') === 'submit') {
score++;
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
if (element.classList.contains('mcq__answers--selected')) {
if (!element.hasAttribute('correct')) {
incorrectAnswer(element);
blockAnswerOption();
} else {
correctAnswer(element);
blockAnswerOption();
}
}
}
submitButton.setAttribute('type', 'reset');
submitButton.innerHTML = 'Reset';
}
}
function buttonReset() {
if (submitButton.getAttribute('type') === 'reset') {
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
element.classList.remove('mcq__answers--correct', 'mcq__answers--incorrect', 'mcq__answers--blocked', 'mcq__answers--selected');
submitButton.setAttribute('type', 'submit');
submitButton.innerHTML = 'Check';
submitButton.setAttribute('aria-disabled', 'true');
}
if (submitFeedback.classList.contains('mcq__submit__feedback--correct')) {
score = 0;
}
submitFeedback.classList.remove('mcq__submit__feedback--correct', 'mcq__submit__feedback--incorrect');
submitFeedback.classList.add('d-none');
}
}
:root {
/* Colors */
--primary-color: #d27f7d;
--primary-color-light: #ee9b9a;
--primary-color-dark: #bb6564;
--secondary-color: #8a6580;
--secondary-color-extra-light: #fae9f5;
--secondary-color-light: #c28cb4;
--secondary-color-dark: #5a3751;
--text-color: #1e1e1e;
--text-color-light: #535658;
--color-dark: #1e1e1e;
--color-light: #eef2f6;
--color-light-hover: #e6e6e625;
}
.mcq-card {
padding: 0px 30px;
}
.mcq-card .mcq__question {
padding: 30px 0;
border-bottom: 1px solid var(--secondary-color-light);
font-family: 'DM Sans Bold', sans-serif;
font-size: 1.25rem;
}
/* Answers List */
.mcq-card .mcq__answers {
padding: 30px 0;
}
.mcq-card .mcq__answers ul {
list-style-type: none;
margin: 0;
}
.mcq-card .mcq__answers ul li {
padding: 10px 20px;
margin-bottom: 20px;
border: 2px solid var(--primary-color-light);
border-radius: 8px;
cursor: pointer;
font-size: 1rem;
transition: 0.1s;
}
.mcq-card .mcq__answers ul li:last-child {
margin-bottom: 0;
}
.mcq-card .mcq__answers ul li:not(.mcq__answers--blocked, .mcq__answers--selected, .mcq__answers--correct, .mcq__answers--incorrect):hover {
border-color: var(--primary-color-dark);
/* background-color: var(--color-light-hover); */
}
.mcq-card .mcq__answers ul li.mcq__answers--selected {
background-color: var(--secondary-color-extra-light);
border-color: var(--secondary-color-light);
color: var(--secondary-color-dark);
}
.mcq-card .mcq__answers ul li.mcq__answers--correct {
background-color: #c0ffce;
border-color: #28a745;
color: #014811;
cursor: not-allowed;
}
.mcq-card .mcq__answers ul li.mcq__answers--incorrect {
background-color: #ffc5cb;
border-color: #dc3545;
color: #81000c;
cursor: not-allowed;
}
.mcq-card .mcq__answers ul li.mcq__answers--blocked:not(.mcq__answers--correct, .mcq__answers--incorrect) {
cursor: not-allowed;
border-color: var(--color-light);
color: var(--text-color-light);
}
/* Submit Button */
.mcq-card .mcq__submit {
display: flex;
flex-direction: row;
justify-content: start;
align-items: center;
padding: 30px 0;
border-top: 1px solid var(--secondary-color-light);
}
.mcq-card .mcq__submit button[aria-disabled='true'] {
background-color: #909599;
border-color: #909599;
cursor: not-allowed;
}
/* Feedback mensage */
.mcq-card .mcq__submit .mcq__submit--feedback {
font-family: 'DM Sans Bold', sans-serif;
margin-left: 20px;
line-height: 1.2;
}
.mcq-card .mcq__submit .mcq__submit--feedback .material-symbols-rounded {
font-weight: 700;
margin-right: 10px;
}
.mcq-card .mcq__submit .mcq__submit--feedback.mcq__submit__feedback--correct {
display: block !important;
color: #28a745;
}
.mcq-card .mcq__submit .mcq__submit--feedback.mcq__submit__feedback--incorrect {
display: block !important;
color: #dc3545;
}
<div class="mcq-card card shadow round border-0">
<div class="mcq__question">1. Question</div>
<div class="mcq__answers">
<ul>
<li tabindex="0">Option 1</li>
<li tabindex="0">Option 2</li>
<li tabindex="0" correct>Option 3</li>
</ul>
</div>
<div class="mcq__submit">
<button class="button-primary" aria-disabled="true" type="submit">Check</button>
<span class="d-none mcq__submit--feedback"></span>
</div>
</div>
<div class="mcq-card card shadow round border-0">
<div class="mcq__question">2. Question</div>
<div class="mcq__answers">
<ul>
<li tabindex="0">Option 1</li>
<li tabindex="0">Option 2</li>
<li tabindex="0" correct>Option 3</li>
</ul>
</div>
<div class="mcq__submit">
<button class="button-primary" aria-disabled="true" type="submit">Check</button>
<span class="d-none mcq__submit--feedback"></span>
</div>
</div>
Thanks
Because each question has exact same structure, you'll need either assign an unique ID for each or go by its index.
But most simple solution is to query each element of each question separately:
let mcqCard = document.querySelectorAll('.mcq-card');
let score = 0;
(function () {
mcqCard.forEach(mcq =>
{
let answerOption = mcq.querySelectorAll('.mcq__answers li');
let submitButton = mcq.querySelector('.mcq__submit button');
let submitFeedback = mcq.querySelector('.mcq__submit--feedback');
// Select option, clear the others and enable submit
answerOption.forEach(option => {
option.addEventListener('click', function () {
console.log(submitButton.getAttribute('type'));
answerSelect(option, submitButton, answerOption);
});
});
//Submit button to check only selected class option.
submitButton.addEventListener('click', function () {
if (submitButton.getAttribute('type') === 'submit' && submitButton.getAttribute('aria-disabled') === 'false') {
butttonCheck();
} else {
buttonReset();
}
});
function answerSelect(e, submitButton) {
if (submitButton.getAttribute('type') === 'submit') {
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
element.classList.remove('mcq__answers--selected');
}
e.classList.add('mcq__answers--selected');
submitButton.setAttribute('aria-disabled', 'false');
}
}
function incorrectAnswer(event) {
event.classList.remove('mcq__answers--selected');
event.classList.add('mcq__answers--incorrect');
submitFeedback.innerHTML = `<span class="material-symbols-rounded">cancel</span>Resposta errada! <br class="d-lg-none" />Tente novamente.`;
submitFeedback.classList.remove('d-none', 'mcq__submit__feedback--correct');
submitFeedback.classList.add('mcq__submit__feedback--incorrect');
}
function correctAnswer(event) {
event.classList.remove('mcq__answers--selected');
event.classList.add('mcq__answers--correct');
submitFeedback.innerHTML = `<span class="material-symbols-rounded">check_circle</span>Resposta correta! <br class="d-lg-none" />VocĂȘ acertou em ${score} tentativa(s).`;
submitFeedback.classList.remove('d-none', 'mcq__submit__feedback--incorrect');
submitFeedback.classList.add('mcq__submit__feedback--correct');
}
function blockAnswerOption() {
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
element.classList.add('mcq__answers--blocked');
}
}
function butttonCheck() {
if (submitButton.getAttribute('type') === 'submit') {
score++;
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
if (element.classList.contains('mcq__answers--selected')) {
if (!element.hasAttribute('correct')) {
incorrectAnswer(element);
blockAnswerOption();
} else {
correctAnswer(element);
blockAnswerOption();
}
}
}
submitButton.setAttribute('type', 'reset');
submitButton.innerHTML = 'Reset';
}
}
function buttonReset() {
if (submitButton.getAttribute('type') === 'reset') {
for (let i = 0; i < answerOption.length; i++) {
const element = answerOption[i];
element.classList.remove('mcq__answers--correct', 'mcq__answers--incorrect', 'mcq__answers--blocked', 'mcq__answers--selected');
submitButton.setAttribute('type', 'submit');
submitButton.innerHTML = 'Check';
submitButton.setAttribute('aria-disabled', 'true');
}
if (submitFeedback.classList.contains('mcq__submit__feedback--correct')) {
score = 0;
}
submitFeedback.classList.remove('mcq__submit__feedback--correct', 'mcq__submit__feedback--incorrect');
submitFeedback.classList.add('d-none');
}
}
});
})();
:root {
/* Colors */
--primary-color: #d27f7d;
--primary-color-light: #ee9b9a;
--primary-color-dark: #bb6564;
--secondary-color: #8a6580;
--secondary-color-extra-light: #fae9f5;
--secondary-color-light: #c28cb4;
--secondary-color-dark: #5a3751;
--text-color: #1e1e1e;
--text-color-light: #535658;
--color-dark: #1e1e1e;
--color-light: #eef2f6;
--color-light-hover: #e6e6e625;
}
.mcq-card {
padding: 0px 30px;
}
.mcq-card .mcq__question {
padding: 30px 0;
border-bottom: 1px solid var(--secondary-color-light);
font-family: 'DM Sans Bold', sans-serif;
font-size: 1.25rem;
}
/* Answers List */
.mcq-card .mcq__answers {
padding: 30px 0;
}
.mcq-card .mcq__answers ul {
list-style-type: none;
margin: 0;
}
.mcq-card .mcq__answers ul li {
padding: 10px 20px;
margin-bottom: 20px;
border: 2px solid var(--primary-color-light);
border-radius: 8px;
cursor: pointer;
font-size: 1rem;
transition: 0.1s;
}
.mcq-card .mcq__answers ul li:last-child {
margin-bottom: 0;
}
.mcq-card .mcq__answers ul li:not(.mcq__answers--blocked, .mcq__answers--selected, .mcq__answers--correct, .mcq__answers--incorrect):hover {
border-color: var(--primary-color-dark);
/* background-color: var(--color-light-hover); */
}
.mcq-card .mcq__answers ul li.mcq__answers--selected {
background-color: var(--secondary-color-extra-light);
border-color: var(--secondary-color-light);
color: var(--secondary-color-dark);
}
.mcq-card .mcq__answers ul li.mcq__answers--correct {
background-color: #c0ffce;
border-color: #28a745;
color: #014811;
cursor: not-allowed;
}
.mcq-card .mcq__answers ul li.mcq__answers--incorrect {
background-color: #ffc5cb;
border-color: #dc3545;
color: #81000c;
cursor: not-allowed;
}
.mcq-card .mcq__answers ul li.mcq__answers--blocked:not(.mcq__answers--correct, .mcq__answers--incorrect) {
cursor: not-allowed;
border-color: var(--color-light);
color: var(--text-color-light);
}
/* Submit Button */
.mcq-card .mcq__submit {
display: flex;
flex-direction: row;
justify-content: start;
align-items: center;
padding: 30px 0;
border-top: 1px solid var(--secondary-color-light);
}
.mcq-card .mcq__submit button[aria-disabled='true'] {
background-color: #909599;
border-color: #909599;
cursor: not-allowed;
}
/* Feedback mensage */
.mcq-card .mcq__submit .mcq__submit--feedback {
font-family: 'DM Sans Bold', sans-serif;
margin-left: 20px;
line-height: 1.2;
}
.mcq-card .mcq__submit .mcq__submit--feedback .material-symbols-rounded {
font-weight: 700;
margin-right: 10px;
}
.mcq-card .mcq__submit .mcq__submit--feedback.mcq__submit__feedback--correct {
display: block !important;
color: #28a745;
}
.mcq-card .mcq__submit .mcq__submit--feedback.mcq__submit__feedback--incorrect {
display: block !important;
color: #dc3545;
}
<div class="mcq-card card shadow round border-0">
<div class="mcq__question">1. Question</div>
<div class="mcq__answers">
<ul>
<li tabindex="0">Option 1</li>
<li tabindex="0">Option 2</li>
<li tabindex="0" correct>Option 3</li>
</ul>
</div>
<div class="mcq__submit">
<button class="button-primary" aria-disabled="true" type="submit">Check</button>
<span class="d-none mcq__submit--feedback"></span>
</div>
</div>
<div class="mcq-card card shadow round border-0">
<div class="mcq__question">2. Question</div>
<div class="mcq__answers">
<ul>
<li tabindex="0">Option 1</li>
<li tabindex="0">Option 2</li>
<li tabindex="0" correct>Option 3</li>
</ul>
</div>
<div class="mcq__submit">
<button class="button-primary" aria-disabled="true" type="submit">Check</button>
<span class="d-none mcq__submit--feedback"></span>
</div>
</div>
Related
I have a Details tab with a dropdown that swaps forms in and out and a Result tab that displays the result in a graph. When the user selects "Result" I want to validate the data entry before going to the result tab.
What happens is that when the Result tab is clicked it becomes active and changes color. I then goes into script.js displayResultContent() which validates the data entry. If the data is not valid I don't want to proceed to the result tab so I only show the result if the data is okay.
The issue I have is that if the data is invalid, error messages are displayed on the form, but the Result tab remains displayed with the active color instead of changing to the non active color. Once the user clicks the mouse on the screen the tab changes color.
Is there any way to make this tab change to the non active color without having to click on the screen? I haven't yet put the media queries in so this looks best on a wide screen, otherwise the tabs are displayed below each other instead of beside. It still works though.
const DATE_TYPE_PAST = 0;
const DATE_TYPE_FUTURE = 1;
const SUCCESS = 0;
const ERROR = 1;
$(function() {
$('#details-tab').click(displayDetails);
$('#result-tab').click(displayResultContent);
$("#your-details-tab").click(displayYourDetailsTab);
$("#your-superannuation-tab").click(displayYourSuperannuationTab);
});
function displayYourDetailsTab() {
removeAllForms();
var form = $("#your-details-form");
form.show();
$('#details-tab').html("Your Details");
}
function displayYourSuperannuationTab() {
removeAllForms();
var form = document.getElementById("your-superannuation-form");
form.style.display = 'block';
$('#details-tab').html("Your Superannuation");
}
function removeAllForms() {
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
forms[i].style.display = "none";
}
}
function displayDetails() {
$('#details').show();
$('#result').hide();
$('#result-tab').removeClass('active');
$('#details-tab').addClass('active');
}
function displayResultContent() {
// FIRST CHECK DATA ENTRY
const dateResult = checkDate(document.getElementById("date-of-birth"), DATE_TYPE_PAST);
const rentResult = checkMandatoryWholeNumber(document.getElementById("fortnightly-rent"), "Fortnightly rent ", 0, 999);
if (dateResult === SUCCESS && rentResult === SUCCESS) {
$('#result').show();
$('#details').hide();
$('#result-tab').addClass('active');
$('#details-tab').removeClass('active');
}else {
$('#result-tab').removeClass('active');
}
}
const showError = (input, message) => {
// get the form-field element
let formField = input.closest(".form-field");
// add the error class
formField.classList.remove('success');
formField.classList.add('error');
// show the error message
const error = formField.querySelector('small');
error.textContent = message;
};
const showSuccess = (input) => {
// get the form-field element
let formField = input.closest(".form-field");
// remove the error class
formField.classList.remove('error');
formField.classList.add('success');
// hide the error message
const error = formField.querySelector('small');
error.textContent = '';
};
const yourDetailsForm = document.getElementById("your-details-form");
if (yourDetailsForm != null) {
yourDetailsForm.addEventListener('input', function(e) {
switch (e.target.id) {
case 'date-of-birth':
checkDate(document.getElementById(e.target.id), DATE_TYPE_PAST);
break;
case 'fortnightly-rent':
checkMandatoryWholeNumber(document.getElementById(e.target.id), "Fortnightly rent ", 0, 999);
break;
}
});
}
const isRequired = value => value !== '';
const isValidDate = function(date) {
return (date !== "Invalid Date") && date !== ("Nan");
}
function checkDate(dateElement, dateType) {
const val = dateElement.value;
const newDate = new Date(val);
if (isValidDate(newDate)) {
const today = new Date();
today.setHours(0,0,0,0);
if (dateType === DATE_TYPE_PAST) {
if (newDate < today) {
// okay
showSuccess(dateElement);
return SUCCESS;
}else {
// error
showError(dateElement, "date must be in the past");
return ERROR;
}
} if (dateType === DATE_TYPE_FUTURE) {
if (newDate >= today) {
// okay
showSuccess(dateElement);
return SUCCESS;
}else {
// error
showError(dateElement, "date must be in the future");
return ERROR;
}
}
}else {
showError(dateElement, "date is mandatory");
return ERROR;
}
}
$(document).on("keydown", ".whole-number", function (e) {
const invalidChars = [
"-",
"+",
"e",
".",
];
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
function checkMandatoryWholeNumber(element, prefix, min, max) {
if (!isRequired(element.value)) {
showError(element, prefix + " is mandatory");
return ERROR;
}
const val = parseInt(element.value);
if (val < min || val > max) {
showError(element, prefix + " must be between " + min + " and " + max);
return ERROR;
}
showSuccess(element);
return SUCCESS;
}
html, body {
height: 100%;
margin: 0;
overflow:hidden;
}
.content {
height:100%;
margin-left: 15%;
margin-right: 15%;
display:flex;
flex-flow: column;
}
.content .result-content {
background-color: #FFF;
flex: 1 1 auto;
margin-left:1%;
margin-right:1%;
display: none;
}
#tabs {
width: 70%;
margin: 0 auto;
padding: 0;
border-bottom: 7px solid #FE6D73;
margin-top: 50px;
}
.form-container {
width: 70%;
height: 98%;
background-color: #FFF;
margin: 0 auto;
overflow-y: auto;
overflow-x: hidden;
padding-bottom: 7px;
box-sizing: border-box;
padding-top: 0px;
}
li {
list-style: none;
}
/*******************************************************************/
/* NAV TABS */
/******************************************************************/
.nav-link {
border-radius: 15px 15px 0px 0px !important;
text-decoration: none;
height: 40px;
font-size: 80%;
background-color: #eeeeee !important;
color: #aaaaaa;
}
.nav-link.active,
.nav-link:active,
.nav-link:hover,
.nav-link:focus {
border-radius: 15px 15px 0px 0px !important;
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
.nav-link-left {
width: 255px;
}
.nav-link-right {
width: 100px;
}
.nav-tabs>li>ul>li>a {
width: 200px;
}
.dropdown-menu {
z-index: 999999;
}
.nav-tabs>li>ul {
background-color: #FE6D73 !important;
}
/* Remove border from tabs */
.nav-tabs .nav-link {
border: 0px solid transparent;
}
/* This is the dropdown link */
.dropdown-item {
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
/* Border at bottom of each item in the drop down list */
.dropdown-menu>li {
border-bottom: 1px solid #FEF9EF !important;
}
.nav-tabs>li>ul>li.active>a, .nav-tabs>li>ul>li.active>a:focus, .nav-tabs>li>ul>li>a:hover {
background-color: #FEF9EF !important;
color: #FE6D73 !important;
}
.dropdown-menu {
border-top: 1px solid #FEF9EF;
}
/*******************************************************************/
/* FORMS */
/******************************************************************/
input[type="number"] {
/*80px*/
width: 5em;
font-size: 80%;
}
input[type="date"] {
border: 1px solid #cccccc;
}
input {
border: 1px solid #cccccc;
}
#your-superannuation-form {
display: none;
}
form {
margin-top: 20px;
background-color: beige;
}
.form-group {
margin-top: 20px;
}
.disabled-link {
cursor: not-allowed;
opacity: 0.5;
}
.disabled-text {
opacity: 0.5;
}
.enabled-text {
opacity: 1.0;
}
.enabled-link {
cursor: pointer;
opacity: 1.0;
}
.pointer-not-allowed{
cursor: not-allowed;
}
.pointer-allowed {
cursor: pointer;
}
form label {
font-family: 'opensansreg', 'Verdana', 'Arial';
}
.form-text {
font-family: Georgia;
align-self: start;
}
.button-text {
font-family: Georgia;
font-size:80%;
}
.input-text {
font-family: Consolas, Lucida Console, monospace;
}
:root {
--error-color: #dc3545;
--success-color: #cccccc;
--warning-color: #ffc107;
}
.form-field input:focus {
outline: none;
}
.form-field.error input {
/* border-color: var(--error-color); */
border: 1px solid #dc3545;
}
.form-field.success input {
/* border-color: var(--success-color); */
border: 1px solid #cccccc;
}
.form-field small {
color: var(--error-color);
font-size: 70%;
display: block;
}
<!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">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="tabs">
<ul class="nav nav-tabs">
<li class="dropdown nav-item">
<a class="nav-link nav-link-left dropdown-toggle active" id="details-tab" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Details</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" id="your-details-tab" href="#">Your Details</a></li>
<li><a class="dropdown-item" id="your-superannuation-tab" href="#">Your Superannuation</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link nav-link-right" id="result-tab" href="#" tabindex="-1">Result</a>
</li>
</ul>
</div>
<div class="content">
<div class="form-container" id="details">
<form id="your-details-form">
<div class="form-group">
<label for="date-of-birth" class="form-text">Date of Birth</label>
<div class="form-field">
<input type="date" class="form-text" id="date-of-birth" name="date-of-birth">
<small></small>
</div>
</div>
<div class="form-group">
<label for="fortnightly-rent" class="form-text">Fortnightly Rent</label>
<div class="form-field">
<input type="text" class="input-text" size="4" id="fortnightly-rent" name="fortnightly-rent"
onKeyDown="if (this.value.length == 4) this.value = this.value.slice(0, -1);"/>
<small></small>
</div>
</div>
</form>
<form id="your-superannuation-form">
THIS IS YOUR SUPERANNUATION FORM
</form>
</div> <!-- end form-container-->
<div class="result-content" id="result">
THIS IS THE RESULT
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.8.0/dist/chart.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Please remove the .nav-link:focus selector from this declaration
.nav-link.active,
.nav-link:active,
.nav-link:hover{
border-radius: 15px 15px 0px 0px !important;
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
Currently when you click on a tab the focus remains and it goes only after clicking away
.nav-link.active,
.nav-link:active,
.nav-link:hover,
.nav-link:focus <---- It works properly after removing this
{
border-radius: 15px 15px 0px 0px !important;
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
I'm having a problem with bluring the background when my menu is open. I tried writing something on my own but it's not working.
function backgroundBlur() {
var menuBox = document.getElementById("mobile-menu");
var blur = document.getElementById("body");
if (menuBox.style.dsiplay = "block") {
blur.style.filter = "blur(3px)";
}
}
I think the problem can be caused by three reasons:
Typo noted by #RyanWalls
The backgroundBlur() method is not called
The display property of the menuBox is not block
I made a run to simulate this event:
let button = document.getElementById('setBlur');
let control = false;
function backgroundBlur(control) {
var menuBox = document.getElementById("mobile-menu");
var blur = document.getElementById("body");
if (menuBox.style.display === "block")
{
if(!control)
{
blur.style.filter = "blur(3px)";
button.innerHTML = 'Remove Blur';
}
else
{
blur.style.filter = "blur(0px)";
button.innerHTML = 'Add Blur';
}
}
}
button.addEventListener('click', function() {
backgroundBlur(control);
control = !control;
});
*{
margin: 0;
}
#body{
background-color: black;
}
button{
margin-top: 25px;
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
width: 100%;
}
.vertical-menu {
width: 200px;
}
.vertical-menu a {
background-color: #eee;
color: black;
display: block;
padding: 12px;
text-decoration: none;
}
.vertical-menu a:hover {
background-color: #ccc;
}
.vertical-menu a.active {
background-color: #04AA6D;
color: white;
}
<div id="body">
<div id="mobile-menu" style="display: block;">
<div class="vertical-menu">
Home
Link 1
</div>
</div>
</div>
<button id="setBlur">Add Blur</button>
I have a row of buttons that I can select. I only want to be able to select one button at a time.
If I deselect the last selected button, it causes the page to reload when I actually just want all buttons deselected. Is there a way to accomplish this?
https://jsfiddle.net/donfontaine12/um05k6cw/33/#&togetherjs=Hm5JqaEvUi
let rankedNo1 = document.querySelector("#ranked_no1");
let rankedNo2 = document.querySelector("#ranked_no2");
let rankedNo3 = document.querySelector("#ranked_no3");
let rankedNo4 = document.querySelector("#ranked_no4");
let rankedNo5 = document.querySelector("#ranked_no5");
let rankedNo6 = document.querySelector("#ranked_no6");
let rankedNo7 = document.querySelector("#ranked_no7");
let rankedNo8 = document.querySelector("#ranked_no8");
let rankedNo9 = document.querySelector("#ranked_no9");
let rankedNo10 = document.querySelector("#ranked_no10");
let rankedNoArray = [rankedNo1, rankedNo2, rankedNo3, rankedNo4, rankedNo5, rankedNo6, rankedNo7, rankedNo8, rankedNo9, rankedNo10];
rankedNo1.addEventListener("click", function() {
toggleHighlight(rankedNo1);
event.preventDefault();
});
rankedNo2.addEventListener("click", function() {
toggleHighlight(rankedNo2);
event.preventDefault();
});
rankedNo3.addEventListener("click", function() {
toggleHighlight(rankedNo3);
event.preventDefault();
});
rankedNo4.addEventListener("click", function() {
toggleHighlight(rankedNo4);
event.preventDefault();
});
rankedNo5.addEventListener("click", function() {
toggleHighlight(rankedNo5);
event.preventDefault();
});
rankedNo6.addEventListener("click", function() {
toggleHighlight(rankedNo6);
event.preventDefault();
});
rankedNo7.addEventListener("click", function() {
toggleHighlight(rankedNo7);
event.preventDefault();
});
rankedNo8.addEventListener("click", function() {
toggleHighlight(rankedNo8);
event.preventDefault();
});
rankedNo9.addEventListener("click", function() {
toggleHighlight(rankedNo9);
event.preventDefault();
});
rankedNo10.addEventListener("click", function() {
toggleHighlight(rankedNo10);
event.preventDefault();
});
function toggleHighlight(r) {
let highlighted = lastHighlighted();
if (highlighted) {
for (let h of highlighted) {
if (h == r) {
r.firstElementChild.classList.remove("selected");
highlighted[h.index].remove();
} else {
h.firstElementChild.classList.remove("selected");
if (r.firstElementChild.classList.contains("selected")) {
r.firstElementChild.classList.remove("selected");
} else {
r.firstElementChild.classList.add("selected");
}
}
}
} else {
if (r.firstElementChild.classList.contains("selected")) {
r.firstElementChild.classList.remove("selected");
} else {
r.firstElementChild.classList.add("selected");
}
}
}
function lastHighlighted() {
let highlightedNos = rankedNoArray.filter(x => x.firstElementChild.classList.contains("selected"));
return highlightedNos;
}
#rank_flex_combo #ranked_nos,
#rank_flex_combo,
#ranked_no,
#ranked_no1,
#ranked_no2,
#ranked_no3,
#ranked_no4,
#ranked_no5,
#ranked_no6,
#ranked_no7,
#ranked_no8,
#ranked_no9,
#ranked_no10 {
display: flex;
flex-direction: row;
margin: 0em 0.5em;
}
#ranked_nos a,
#ranked_no1 a,
#ranked_no2 a,
#ranked_no3 a,
#ranked_no4 a,
#ranked_no5 a,
#ranked_no6 a,
#ranked_no7 a,
#ranked_no8 a,
#ranked_no9 a,
#ranked_no10 a {
font-weight: bold;
text-decoration: none;
padding: 0.25em 0.5em;
color: dodgerblue;
background-color: lightcyan;
border: 2px solid cyan;
border-radius: 5px;
}
#ranked_nos .selected,
#ranked_no1 .selected,
#ranked_no2 .selected,
#ranked_no3 .selected,
#ranked_no4 .selected,
#ranked_no5 .selected,
#ranked_no6 .selected,
#ranked_no7 .selected,
#ranked_no8 .selected,
#ranked_no9 .selected,
#ranked_no10 .selected {
color: mediumpurple;
background-color: lavender;
border: 2px solid mediumpurple;
}
#ranked_no a {
font-weight: bold;
text-decoration: none;
padding: 0.25em 2em;
color: dodgerblue;
background-color: white;
border: 2px solid cyan;
border-radius: 5px;
}
#ranked_no1 a:hover,
#ranked_no2 a:hover,
#ranked_no3 a:hover,
#ranked_no4 a:hover,
#ranked_no5 a:hover,
#ranked_no6 a:hover,
#ranked_no7 a:hover,
#ranked_no8 a:hover,
#ranked_no9 a:hover,
#ranked_no10 a:hover {
color: mediumpurple;
background-color: lavender;
border: 2px solid mediumpurple;
}
<div id="rank_flex_combo">
<div id="ranked_no">
Rank No.
</div>
<div id="ranked_no1">
1
</div>
<div id="ranked_no2">
2
</div>
<div id="ranked_no3">
3
</div>
<div id="ranked_no4">
4
</div>
<div id="ranked_no5">
5
</div>
<div id="ranked_no6">
6
</div>
<div id="ranked_no7">
7
</div>
<div id="ranked_no8">
8
</div>
<div id="ranked_no9">
9
</div>
<div id="ranked_no10">
10
</div>
</div>
You only need that:
const rankFlexCombo = document.getElementById('rank_flex_combo')
, rankedNo1 = document.querySelector('#rank_flex_combo > div#ranked_no1')
, rankedNoAll = document.querySelectorAll('#rank_flex_combo > div')
;
rankedNo1.classList.add('selected')
var OnSelect = rankedNo1
;
rankFlexCombo.onclick= e =>
{
if (!e.target.matches('#rank_flex_combo > div')) return
let rDiv = (e.target.id==='ranked_no') ? rankedNo1 : e.target;
rankedNoAll.forEach(d=>d.classList.remove('selected'))
if (rDiv===OnSelect)
{
// rankedNo1.classList.add('selected')
// OnSelect = rankedNo1 // for default selected
OnSelect = null
}
else
{
rDiv.classList.add('selected')
OnSelect = rDiv
}
}
#rank_flex_combo {
display: flex;
flex-direction: row;
}
#rank_flex_combo > div {
font-weight: bold;
padding: 0.25em 0.5em;
color: dodgerblue;
background-color: lightcyan;
border: 2px solid cyan;
border-radius: 5px;
margin: 0em 0.5em;
cursor: pointer;
}
#rank_flex_combo > div:hover,
#rank_flex_combo > div.selected {
color: mediumpurple;
background-color: lavender;
border: 2px solid mediumpurple;
}
<div id="rank_flex_combo">
<div id="ranked_no"> Rank No. </div>
<div id="ranked_no1"> 1 </div>
<div id="ranked_no2"> 2 </div>
<div id="ranked_no3"> 3 </div>
<div id="ranked_no4"> 4 </div>
<div id="ranked_no5"> 5 </div>
<div id="ranked_no6"> 6 </div>
<div id="ranked_no7"> 7 </div>
<div id="ranked_no8"> 8 </div>
<div id="ranked_no9"> 9 </div>
<div id="ranked_no10"> 10 </div>
</div>
Try this: [Works]
let rankedNo1 = document.querySelector("#ranked_no1");
let rankedNo2 = document.querySelector("#ranked_no2");
let rankedNo3 = document.querySelector("#ranked_no3");
let rankedNo4 = document.querySelector("#ranked_no4");
let rankedNo5 = document.querySelector("#ranked_no5");
let rankedNo6 = document.querySelector("#ranked_no6");
let rankedNo7 = document.querySelector("#ranked_no7");
let rankedNo8 = document.querySelector("#ranked_no8");
let rankedNo9 = document.querySelector("#ranked_no9");
let rankedNo10 = document.querySelector("#ranked_no10");
let rankedNoArray = [rankedNo1, rankedNo2, rankedNo3, rankedNo4, rankedNo5, rankedNo6, rankedNo7, rankedNo8, rankedNo9, rankedNo10];
rankedNo1.addEventListener("click", function() {
toggleHighlight(rankedNo1);
event.preventDefault();
});
rankedNo2.addEventListener("click", function() {
toggleHighlight(rankedNo2);
event.preventDefault();
});
rankedNo3.addEventListener("click", function() {
toggleHighlight(rankedNo3);
event.preventDefault();
});
rankedNo4.addEventListener("click", function() {
toggleHighlight(rankedNo4);
event.preventDefault();
});
rankedNo5.addEventListener("click", function() {
toggleHighlight(rankedNo5);
event.preventDefault();
});
rankedNo6.addEventListener("click", function() {
toggleHighlight(rankedNo6);
event.preventDefault();
});
rankedNo7.addEventListener("click", function() {
toggleHighlight(rankedNo7);
event.preventDefault();
});
rankedNo8.addEventListener("click", function() {
toggleHighlight(rankedNo8);
event.preventDefault();
});
rankedNo9.addEventListener("click", function() {
toggleHighlight(rankedNo9);
event.preventDefault();
});
rankedNo10.addEventListener("click", function() {
toggleHighlight(rankedNo10);
event.preventDefault();
});
function toggleHighlight(r) {
let highlighted = lastHighlighted();
if (highlighted && highlighted.length) {
for (let h of highlighted) {
if (h == r) {
r.firstElementChild.classList.remove("selected");
} else {
h.firstElementChild.classList.remove("selected");
if (r.firstElementChild.classList.contains("selected")) {
r.firstElementChild.classList.remove("selected");
} else {
r.firstElementChild.classList.add("selected");
}
}
i+=1;
}
} else {
r.firstElementChild.classList.add("selected");
}
}
function lastHighlighted() {
let highlightedNos = rankedNoArray.filter(x => x.firstElementChild.classList.contains("selected"));
return highlightedNos;
}
#rank_flex_combo #ranked_nos, #rank_flex_combo, #ranked_no,
#ranked_no1, #ranked_no2, #ranked_no3, #ranked_no4, #ranked_no5,
#ranked_no6, #ranked_no7, #ranked_no8, #ranked_no9, #ranked_no10 {
display: flex;
flex-direction: row;
margin: 0em 0.5em;
}
#ranked_nos a,
#ranked_no1 a, #ranked_no2 a, #ranked_no3 a, #ranked_no4 a, #ranked_no5 a,
#ranked_no6 a, #ranked_no7 a, #ranked_no8 a, #ranked_no9 a, #ranked_no10 a {
font-weight: bold;
text-decoration: none;
padding: 0.25em 0.5em;
color: dodgerblue;
background-color: lightcyan;
border: 2px solid cyan;
border-radius: 5px;
}
#ranked_nos .selected,
#ranked_no1 .selected, #ranked_no2 .selected, #ranked_no3 .selected, #ranked_no4 .selected,
#ranked_no5 .selected, #ranked_no6 .selected, #ranked_no7 .selected, #ranked_no8 .selected,
#ranked_no9 .selected, #ranked_no10 .selected {
color: mediumpurple;
background-color: lavender;
border: 2px solid mediumpurple;
}
#ranked_no a {
font-weight: bold;
text-decoration: none;
padding: 0.25em 2em;
color: dodgerblue;
background-color: white;
border: 2px solid cyan;
border-radius: 5px;
}
#ranked_no1 a:hover, #ranked_no2 a:hover, #ranked_no3 a:hover, #ranked_no4 a:hover, #ranked_no5 a:hover, #ranked_no6 a:hover, #ranked_no7 a:hover, #ranked_no8 a:hover, #ranked_no9 a:hover, #ranked_no10 a:hover {
color: mediumpurple;
background-color: lavender;
border: 2px solid mediumpurple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="rank_flex_combo">
<div id="ranked_no">
<a href="" >Rank No.</a>
</div>
<div id="ranked_no1">
1
</div>
<div id="ranked_no2">
2
</div>
<div id="ranked_no3">
3
</div>
<div id="ranked_no4">
4
</div>
<div id="ranked_no5">
5
</div>
<div id="ranked_no6">
6
</div>
<div id="ranked_no7">
7
</div>
<div id="ranked_no8">
8
</div>
<div id="ranked_no9">
9
</div>
<div id="ranked_no10">
10
</div>
</div>
I'm following this guide to create Search/Filter Dropdown.
But I have this method 'allNameMuseums()', that returns an array of names (for example :
array = ["Jack", "Paul", "George"]
My JS code :
async function allNameMuseums() {
let nomeFile = "dati_musei_infovis.csv";
let data3 = await d3.dsv(";", nomeFile, function (d) {
return {
Museo: d.Museo,
Ingresso: d.Ingresso,
Anno: d.Anno,
Mese: d.Mese,
Visitatori: d.Visitatori
};
});
return filtraggioNomeMuseo(data3);
};
function filtraggioNomeMuseo(data) {
array_filtrato = [];
var map = {};
//var visitatori = 0;
for (i=0; i<data.length; i++) {
if (!(array_filtrato.includes(data[i].Museo))) {
array_filtrato.push(data[i].Museo)
}
}
return array_filtrato;
}
I want to put these names instead of About, Base, Blog etc...
You could loop through the returned array and append the names as anchors to the dropdown like :
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item){
document.getElementById("myDropdown").innerHTML += ''+item+'';
})
});
NOTE: Put your code inside DOMContentLoaded event listener to make sure all the DOM elements are loaded before executing your code/
Working sample:
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) {
document.getElementById("myDropdown").innerHTML += '' + item + '';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function allNameMuseums() {
return ["Jack", "Paul", "George"];
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
border-box: box-sizing;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
#myInput:focus {
outline: 3px solid #ddd;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>
My JavaScript assignment is a ''to-do list', the user needs to be able to press the enter key, I tried this code but it's not working. If anyone has suggestions please let me know! Thanks
EDIT: Here is my JavaScript, HTML and CSS file
EDIT II: Here are the directions in full
1. After inserting a new item, clear the input field
2. If the user presses the enter key, perform the same action as clicking the plus button.
3. Check to make sure that the user entered something into the input field adding it to the list
4. When the user clicks on the heading, so a prompt to allow them to change the title. Make sure they entered something before changing it.
window.addEventListener('load', function(){
var todos = document.getElementsByClassName('todo-item');
var removes = document.getElementsByClassName('remove');
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(e) {
console.log('=' + e.target.className);
if(e.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(e.target.className.indexOf('completed'));
if(e.target.className.indexOf('completed') > -1) {
console.log(' ' + e.target.className);
e.target.className = e.target.className.replace(' completed', '');
} else {
console.log('-' + e.target.className);
e.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function valueField(input,val){
if(input.value == "")
input.value=val;
}
function clearField(input,val){
if(input.value == val)
input.value="";
}
function removeItem(e) {
if(e.target.className.indexOf('remove') < 0) {
return;
}
function handle(e){
var keycode
if(e.keyCode === ""){
}
return false;
}
var el = e.target.parentNode;
el.parentNode.removeChild(el);
}
});
body {
background-color: #BCDBF2;
font-family: Helvetica, Arial, sans-serif;
}
body > div {
width: 300px;
margin:50px auto;
}
h1 {
text-align: center;
}
.todo-list {
list-style: none;
padding: 0px;
}
.todo-item {
border: 2px solid #444;
margin-top: -2px;
padding: 10px;
cursor: pointer;
display: block;
background-color: #ffffff;
}
.todo-new {
display: block;
margin-top: 10px;
}
.todo-new input[type='text'] {
width: 260px;
height: 22px;
border: 2px solid #444;
}
.todo-new a {
font-size: 1.5em;
color: black;
text-decoration: none;
background-color: #ffffff;
border: 2px solid #444;
display: block;
width: 24px;
float: right;
text-align: center;
}
.todo-new a:hover {
background-color: #0EB0dd;
}
.remove {
float: right;
font-family: Helvetica, Arial, sans-serif;
font-size: 0.8em;
color: #dd0000;
}
.remove:before {
content: 'X';
}
.remove:hover {
color: #ffffff;
}
.todo-item::after:hover{
background-color: #dd0000;
color: white;
}
.todo-item:hover {
background-color: #0EB0FF;
color: white;
}
.completed {
text-decoration: line-through;
opacity: 0.5;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 18 - Event Delegation</title>
<link rel='stylesheet' href='main.css'/>
</head>
<body>
<div>
<h1>To-Do List</h1>
<ul class='todo-list'>
<li class='todo-item'>4L 2% Milk
<span class='remove'></span></li>
<li class='todo-item'>Butter, Unsalted
<span class='remove'></span></li>
<li class='todo-item'>Dozen Eggs
<span class='remove'></span></li>
<li class='todo-item'>Walk the dog
<span class='remove'></span></li>
<li class='todo-item'>Cut the lawn
<span class='remove'></span></li>
<li class='todo-item'>Laundry
<span class='remove'></span></li>
<li class='todo-new'>
<input id='new-item-text' type='text'/>
<a id='add-item' href='#'>+</a>
</li>
</ul>
</div>
<script src='main.js'></script>
</body>
</html>
Look up the key code that will correspond to enter. One place to find this is on MDN KeyboardEvent:keyCode. Using that, you can write:
var ENTER = 13;
function handle(e){
if(e.keyCode === ENTER){
// insert a new line or whatever you want
}
return false;
}
You need to register the onkeypress event on a HTML element, for example on the input text, like this:
<input id='new-item-text' type='text' onkeypress="return handle(event)" />
Also, you can register the event on <body>or other HTML elements. And you can register the event using HTML or using Javascript.
In HTML:
<element onkeypress="myScript">
In JavaScript:
object.onkeypress=function(){myScript};
If you want to learn more about this event you can read this docs.
To know where is the handle function needs to be global (declared outside the load event).
The last thing to do, is to filter the enter button with e.keyCode === 13. Important: is a Number, not a String.
I put below all the code testable that you can see and run (I applied the example when press enter on the input text).
I hope to help you.
All the code
window.addEventListener('load', function() {
var todos = document.getElementsByClassName('todo-item');
var removes = document.getElementsByClassName('remove');
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(e) {
console.log('=' + e.target.className);
if (e.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(e.target.className.indexOf('completed'));
if (e.target.className.indexOf('completed') > -1) {
console.log(' ' + e.target.className);
e.target.className = e.target.className.replace(' completed', '');
} else {
console.log('-' + e.target.className);
e.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function valueField(input, val) {
if (input.value == "")
input.value = val;
}
function clearField(input, val) {
if (input.value == val)
input.value = "";
}
function removeItem(e) {
if (e.target.className.indexOf('remove') < 0) {
return;
}
var el = e.target.parentNode;
el.parentNode.removeChild(el);
}
});
function handle(e) {
if (e.keyCode === 13) {
console.log("Doing something");
}
return true;
}
body {
background-color: #BCDBF2;
font-family: Helvetica, Arial, sans-serif;
}
body > div {
width: 300px;
margin: 50px auto;
}
h1 {
text-align: center;
}
.todo-list {
list-style: none;
padding: 0px;
}
.todo-item {
border: 2px solid #444;
margin-top: -2px;
padding: 10px;
cursor: pointer;
display: block;
background-color: #ffffff;
}
.todo-new {
display: block;
margin-top: 10px;
}
.todo-new input[type='text'] {
width: 260px;
height: 22px;
border: 2px solid #444;
}
.todo-new a {
font-size: 1.5em;
color: black;
text-decoration: none;
background-color: #ffffff;
border: 2px solid #444;
display: block;
width: 24px;
float: right;
text-align: center;
}
.todo-new a:hover {
background-color: #0EB0dd;
}
.remove {
float: right;
font-family: Helvetica, Arial, sans-serif;
font-size: 0.8em;
color: #dd0000;
}
.remove:before {
content: 'X';
}
.remove:hover {
color: #ffffff;
}
.todo-item::after:hover {
background-color: #dd0000;
color: white;
}
.todo-item:hover {
background-color: #0EB0FF;
color: white;
}
.completed {
text-decoration: line-through;
opacity: 0.5;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 18 - Event Delegation</title>
<link rel='stylesheet' href='main.css' />
</head>
<body>
<div>
<h1>To-Do List</h1>
<ul class='todo-list'>
<li class='todo-item'>4L 2% Milk
<span class='remove'></span>
</li>
<li class='todo-item'>Butter, Unsalted
<span class='remove'></span>
</li>
<li class='todo-item'>Dozen Eggs
<span class='remove'></span>
</li>
<li class='todo-item'>Walk the dog
<span class='remove'></span>
</li>
<li class='todo-item'>Cut the lawn
<span class='remove'></span>
</li>
<li class='todo-item'>Laundry
<span class='remove'></span>
</li>
<li class='todo-new'>
<input id='new-item-text' type='text' onkeypress="return handle(event)" />
<a id='add-item' href='#'>+</a>
</li>
</ul>
</div>
<script src='main.js'></script>
</body>
</html>
I believe that the key code for enter is 13. See below.
function handle(e){
if(e.keyCode === 13){
}
return false;
}