Why does on Hover quit working after it is selected once? - javascript

<!DOCTYPE html>
<html>
<head>
<style>
.menu{
background-color: cornflowerblue;
}
.btn-group .button {
background-color: #4CAF50; /* Green */
border: 1px solid green;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
width: 150px;
display: block;
}
.btn-group .button:hover {
background-image: linear-gradient(to bottom, rgb(92, 88, 46),
rgb(247, 229, 41),
rgb(92,88,46));
color:red;
}
</style>
</head>
<body onload="fnOnLoad()">
<div class="menu">
<div class="btn-group">
<button id = "WhatsNew" onclick="btnClick('WhatsNew')" class="button">What's New</button>
<button id = "Button1" onclick="btnClick('Button1')" class="button">Button1</button>
<button id = "Button2" onclick="btnClick('Button2')" class="button">Button2</button>
<button id = "Button3" onclick="btnClick('Button3')" class="button">Button3</button>
<button id = "Button4" onclick="btnClick('Button4')" class="button">Button4</button>
</div>
</div>
</body>
<script>
let curBtn = "WhatsNew";
function fnOnLoad(){
/*alert("In OnLoad"); */
btnClick("WhatsNew");
}
function btnClick(btnName){
/*alert("Setting button colors. curBtn = " + curBtn + " btnName = " + btnName);*/
document.getElementById(curBtn).style.backgroundColor = "rgb(33, 31, 31)";
document.getElementById(curBtn).style.backgroundImage = "none";
document.getElementById(curBtn).style.color = "rgb(255, 234, 0)";
document.getElementById(btnName).style.color = "rgb(17, 15, 15)";
document.getElementById(btnName).style.backgroundImage = "linear-gradient(to bottom, rgb(92, 88, 46), rgb(247, 229, 41), rgb(92,88,46))";
curBtn = btnName;
/*alert("after curBtn = " + curBtn);*/
}
</script>
</body>
</html>
I want the menu items to change to the gradient when hovered or when selected. The way it's working now it works until you select that menu item. Once you click another menu item the ones previously selected do not do the gradient anymore.
This site won't let me post without more details.... If you try the above code the first item is highlighted when it starts. As you hover over the other items you see them highlighted. After you select a new item the old one no longer highlights when you hover over it. Why?
Thanks for any ideas.
Alan

When you set a style rule with JS you erase the one you wrote with css so it wont work anymore after being unset.
I suggest you use JS only to set class names to your element and let CSS in charge of setting the rules.
Careful to write the rules in the right order.
let curBtn = "WhatsNew";
function btnClick(btnName) {
document.getElementById(curBtn).classList.add("visited");
document.getElementById(curBtn).classList.remove("selected");
document.getElementById(btnName).classList.add("selected");
curBtn = btnName;
}
.menu {
background-color: cornflowerblue;
}
.btn-group .button {
background-color: #4CAF50;
/* Green */
border: 1px solid green;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
width: 150px;
display: block;
}
.btn-group .button.visited {
background-color: rgb(33, 31, 31);
background-image: none;
color: rgb(255, 234, 0);
}
.btn-group .button.selected {
color: rgb(17, 15, 15);
background-image: linear-gradient(to bottom, rgb(92, 88, 46), rgb(247, 229, 41), rgb(92, 88, 46));
}
.btn-group .button:hover {
background-image: linear-gradient(to bottom, rgb(92, 88, 46),
rgb(247, 229, 41),
rgb(92, 88, 46));
color: red;
}
<div class="menu">
<div class="btn-group">
<button id="WhatsNew" onclick="btnClick('WhatsNew')" class="button">What's New</button>
<button id="Button1" onclick="btnClick('Button1')" class="button">Button1</button>
<button id="Button2" onclick="btnClick('Button2')" class="button">Button2</button>
<button id="Button3" onclick="btnClick('Button3')" class="button">Button3</button>
<button id="Button4" onclick="btnClick('Button4')" class="button">Button4</button>
</div>
</div>

Related

Change div id on button click function, to create a darkmode

I'm trying to write a JavaScript that makes an id change its id on click. Basically, I would like to create a dark mode toggle button. Not sure what I'm doing wrong though.
HTML
<button id="nottebottone" class="notte">Attiva modalità notturna</button>
CSS
#Sito {
max-width: 1024px;
margin: auto;
text-align: center;
background-color: rgb(221, 241, 235);
border: black ridge;
border-width: 0.03cm;
}
Which I'm trying to change to:
#Nightmode {
max-width: 1024px;
margin: auto;
text-align: center;
background-color: rgb(0, 0, 0);
border: rgb(255, 255, 255) ridge;
border-width: 0.03cm;
color: white;
}
JavaScript:
let bottonedarkmode = document.getElementById("nottebottone");
function attivadarkmode() {
if (document.div.id == "Sito") {
document.div.id = "Nightmode";
}
else {
documento.div.id = "Sito";
}
}
bottonedarkmode.addEventListener('click', attivadarkmode);
Click the button nottebottone to enable the id switch, but nothing happens.
You should do it like this:
let darkModeBtn = document.querySelector(".notte");
function attivadarkmode() {
darkModeBtn.classList.toggle('light');
darkModeBtn.classList.toggle('dark');
}
darkModeBtn.addEventListener('click', attivadarkmode);
.notte {
max-width: 1024px;
margin: auto;
text-align: center;
}
.light {
background-color: rgb(221, 241, 235);
border: black ridge;
border-width: 0.03cm;
}
.dark {
background-color: rgb(0, 0, 0);
border: rgb(255, 255, 255) ridge;
border-width: 0.03cm;
color: white;
}
<button id="nottebottone" class="notte light">Attiva modalità notturna</button>
At a first glance, I'm assuming the issue is that you typed documento instead of document in the else portion of your function, though I didn't check thouroughly.
I hope this will help you for changing ID:
document.getElementById('nottebottone').id = 'Nightmode';

How to dynamically change color of clicked elements using color-picker

I wanted to change color according to user preference dynamically like when a user selects a color then it is applied synchronously to the element .
Like when an element is clicked color picker opens and then it works like developer tools color-picker , when a color is chosen from the picker it is applied to element and if user wants to change the color again in same picker than that also applied
Tried to went through following questions but couldn't find answer :
Change background colors dynamically using input event
how to dynamically select a color from a color picker by using jQuery?
HTML Input Color Picker, Apply Changes In Sync With Color Picker Selection
I wanted to code work like this in below snippet, whichever element is clicked than colors are changes of that element.
In original code html is like this :
<div id="clockOuterCircle"><div id="clockStyleCircle"></div></div> which can be solved by bubbling/capturing
var reed = document.getElementById("clockOuterCircle");
var reed1 = document.getElementById("clockStyleCircle");
reed.addEventListener('click', deed)
reed1.addEventListener('click', deed)
function deed() {
var reed2 = document.getElementById("colorClock");
reed2.click();
var reed3 = reed2.value;
// reed1.addEventListener('change', function() {
this.style.backgroundColor = reed3;
document.getElementById("demo").innerHTML = reed3;
//})
}
#clockStyleCircle {
position: absolute;
width: 16vw;
height: 16vw;
text-align: center;
padding: 0%;
top: 28.5%;
left: 28.5%;
border-radius: 50%;
border: 3px solid black;
background-color: rgb(255, 233, 35);
}
#clockOuterCircle {
display: flex;
justify-content: center;
align-items: center;
width: 42vw;
height: 42vw;
margin: auto;
border-radius: 50%;
border: 4px solid rgb(255, 62, 62);
background-color: rgb(253, 133, 133);
user-select: none;
}
<div id="clockStyleCircle"></div>
<div id="clockOuterCircle"></div>
<div id="demo"></div>
<input type="color" name="colorClock" id="colorClock">
Possible answer of dynamically changing color can be like this in below snippet, like using
input event separately on each element.
var reed = document.getElementById("clockOuterCircle");
var reed1 = document.getElementById("clockStyleCircle");
reed.addEventListener('click', deed)
reed1.addEventListener('click', deed)
//function deed() {
// var reed2 = document.getElementById("colorClock");
// reed2.click();
// var reed3 = reed2.value;
// reed1.addEventListener('change', function() {
// this.style.backgroundColor = reed3;
// document.getElementById("demo").innerHTML = reed3;
//})
//}
reed2 = document.getElementById("colorClock");
reed2.addEventListener('input', deed)
function deed() {
var reed3 = reed2.value;
reed.style.backgroundColor = reed3;
}
reed4 = document.getElementById("colorClock2");
reed4.addEventListener('input', deed1)
function deed1() {
var reed5 = reed4.value;
reed1.style.backgroundColor = reed5;
}
#clockStyleCircle {
position: absolute;
width: 16vw;
height: 16vw;
text-align: center;
padding: 0%;
top: 28.5%;
left: 28.5%;
border-radius: 50%;
border: 3px solid black;
background-color: rgb(255, 233, 35);
}
#clockOuterCircle {
display: flex;
justify-content: center;
align-items: center;
width: 42vw;
height: 42vw;
margin: auto;
border-radius: 50%;
border: 4px solid rgb(255, 62, 62);
background-color: rgb(253, 133, 133);
user-select: none;
}
<div id="clockStyleCircle"></div>
<div id="clockOuterCircle"></div>
<div id="demo"></div>
<input type="color" name="colorClock" id="colorClock">
<input type="color" name="colorClock" id="colorClock2">
But in above method color is not changing of clicked element instead a fixed element color is changed which is defined beforehand . So have to apply code to different elements separately, as there are many elements so wanted to apply both ways
Thanks for the help in advance.
Updated to stop bubbling with event.stopPropagation()
If I've understood you correctly, you want to launch a colour picker every time any particular element in your page is clicked which allows you to change that element's background colour.
This solution adds and then launches a colour picker when any element with the class circle is clicked, then removes it again after a colour has been selected.
The colour picker input is hidden with display:none but the dialog box is visible.
let body = document.body;
let circles = document.querySelectorAll('.circle');
circles.forEach((circle) => {
circle.addEventListener('click', () => {
let existingColourPickers = document.querySelectorAll('input.colour-picker')
existingColourPickers.forEach((existingColourPicker) => {
if (body.contains(existingColourPicker)) {
body.removeChild(existingColourPicker);
}
});
event.stopPropagation();
let colourPicker = document.createElement("input");
colourPicker.type = "color";
colourPicker.className = "colour-picker";
body.appendChild(colourPicker);
colourPicker.click();
colourPicker.addEventListener("input", () => {
circle.style.backgroundColor = event.target.value;
}, false);
colourPicker.addEventListener("change", () => {
body.removeChild(colourPicker);
}, false);
});
});
#clockStyleCircle {
position: absolute;
width: 16vw;
height: 16vw;
text-align: center;
padding: 0%;
top: 28.5%;
left: 28.5%;
border-radius: 50%;
border: 3px solid black;
background-color: rgb(255, 233, 35);
z-index:1;
}
#clockOuterCircle {
display: flex;
justify-content: center;
align-items: center;
width: 42vw;
height: 42vw;
margin: auto;
border-radius: 50%;
border: 4px solid rgb(255, 62, 62);
background-color: rgb(253, 133, 133);
user-select: none;
}
#another-circle {
width:50px;
height:50px;
border-radius: 50%;
border: 4px green solid;
background-color:blue;
position:absolute;
top:20px;
left:20px;
}
.colour-picker {
display:none;
}
<body>
<div id="clockOuterCircle" class="circle">
<div id="clockStyleCircle" class="circle"></div>
</div>
<!-- another circle -->
<div id="another-circle" class="circle"></div>
<!-- ... -->
</body>
What you had was pretty close. I just separated the color picking code into a new function. Try this..
var reed = document.getElementById("clockOuterCircle");
var reed1 = document.getElementById("clockStyleCircle");
reed.addEventListener('click', deed)
reed1.addEventListener('click', deed)
async function deed() {
var color = await getUserColor();
this.style.backgroundColor = color;
document.getElementById("demo").innerHTML = color;
}
function getUserColor() {
return new Promise(done => {
var color_picker = document.createElement('input');
color_picker.setAttribute('type', 'color');
color_picker.style.opacity = 0;
document.body.appendChild(color_picker);
color_picker.addEventListener('change', function() {
var color = this.value;
this.remove();
done(color);
});
color_picker.click();
});
}
#clockStyleCircle {
position: absolute;
width: 16vw;
height: 16vw;
text-align: center;
padding: 0%;
top: 28.5%;
left: 28.5%;
border-radius: 50%;
border: 3px solid black;
background-color: rgb(255, 233, 35);
}
#clockOuterCircle {
display: flex;
justify-content: center;
align-items: center;
width: 42vw;
height: 42vw;
margin: auto;
border-radius: 50%;
border: 4px solid rgb(255, 62, 62);
background-color: rgb(253, 133, 133);
user-select: none;
}
<div id="clockStyleCircle"></div>
<div id="clockOuterCircle"></div>
<div id="demo"></div>
Your example defines the background-color using two different methods class and style, which may produce unexpected results.
Here is an example using the most basic form of JavaScript, that does not set the background-color via class.
When you click an area, it will change to the selected color and when you select a color, the last area clicked, will change to the same color.
To keep it brief and simple, the example does not check, if the elements it operates on, are well defined.
// The last area clicked
var div_last_clicked = 0;
// Called when the document has finished loading
function myonload() {
// Detect when an area is clicked
let elems = document.querySelectorAll('.mydiv');
for(let i = 0; i < elems.length; ++i) {
let elem = elems[i];
elem.addEventListener('click', mydiv_clicked);
}
// Detect when the color changes
let ob = document.querySelector('.mycolor');
ob.addEventListener('change', mycolor_changed);
}
// Called when an area is clicked
function mydiv_clicked(e) {
let ob = document.querySelector('.mycolor');
div_last_clicked = e.target;
div_last_clicked.style = "background-color:" + ob.value;
}
// Called when the color changes
function mycolor_changed(e) {
if(div_last_clicked)
div_last_clicked.style = "background-color:" + e.target.value;
}
.mydiv {
height:30px;
width: 200px;
border:1px solid black;
margin-bottom:2px;
}
<body onload="myonload()">
<input class="mycolor" type="color" value="#ff0000" />
<p>When you click an area below, it will change to the selected color.</p>
<p>When you change the color, the last area clicked will also change
to the same color.</p>
<div class="mydiv">First area</div>
<div class="mydiv">Second area</div>
<div class="mydiv">Third area</div>
</body>
Based on your additional info, if you want to have a single colour input on the page, you can add a data-id attribute to each of your circles, and use that as a reference for which element the colour input should update when changed:
var restyleBG = document.querySelectorAll(".restyleBackground")
var colorPicker = document.getElementById("colorClock");
var selected;
restyleBG.forEach((restyle) => {
restyle.addEventListener('click', changeBGcolor, false)
})
function changeBGcolor(event) {
event.stopPropagation()
selected = document.querySelector(`[data-id="${event.srcElement.dataset.id}"]`);
colorPicker.click();
}
colorPicker.addEventListener('input', (event) => {
selected.style.backgroundColor = colorPicker.value;
})
#clockStyleCircle {
position: absolute;
width: 16vw;
height: 16vw;
text-align: center;
padding: 0%;
top: 28.5%;
left: 28.5%;
border-radius: 50%;
border: 3px solid black;
background-color: rgb(255, 233, 35);
z-index: 1;
}
#clockOuterCircle {
display: flex;
justify-content: center;
align-items: center;
width: 42vw;
height: 42vw;
margin: auto;
border-radius: 50%;
border: 4px solid rgb(255, 62, 62);
background-color: rgb(253, 133, 133);
user-select: none;
}
#another-circle {
width: 50px;
height: 50px;
border-radius: 50%;
border: 4px green solid;
background-color: blue;
position: absolute;
top: 20px;
left: 20px;
}
#colorClock {
display: none;
}
<body>
<input type="color" name="colorClock" id="colorClock">
<div id="clockOuterCircle" class="restyleBackground" data-id="1">
<div id="clockStyleCircle" class="restyleBackground" data-id="2"></div>
</div>
<!-- another circle -->
<div id="another-circle" class="restyleBackground" data-id="3"></div>
<!-- ... -->
</body>

How can I passing data from jquery codes to my project backend

I did create a form and A submit button in my website
but I do not know How can I passing data from javascript codes to My asp.net core codes
My Html jquery css codes Here:
*{
box-sizing: border-box;
}
body{
padding:20px 25px 70px 25px;
}
#all-questions-preview>.content{
display: flex;
flex-direction: column;
}
#all-questions-preview>.content>.question-container{
width:100%;
background: #fefefe;
border-radius: 8px;
box-shadow: 0 1px 5px 1px rgba(0,0,0,0.2);
padding:12px 18px 70px 18px;
position: relative;
margin-bottom:15px;
}
#all-questions-preview>.content>.question-container>.question-title{
color: #444;
font-weight: bold;
}
#all-questions-preview>.content>.question-container>.question-title::before{
content: ":.";
}
#all-questions-preview>.content>.question-container>.close{
position:absolute;
padding:5px;
color: #f02f24;
font-size: 1.3em;
font-weight: bold;
transform: rotate(45deg);
top:10px;
right:10px;
background-color:#f6f6f6;
border:none !important;
outline: none !important;
cursor:pointer;
border-radius:100%;
display: flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
}
#all-questions-preview>.content>.question-container input{
background: none !important;
outline: none !important;
border:none;
font-weight: bold;
}
#all-questions-preview>.content>.question-container .question-sentence{
display:inline-block;
width:100%;
font-size:1.2em;
padding:5px 10px;
border-bottom:2px solid #71c9db;
color: #61adbb;
}
#all-questions-preview>.content>.question-container .answer-span{
display:inline-block;
margin-right:20px;
margin-top:20px;
width:20%;
min-width: 150px;
position: relative;
/*text-align: right;*/
/*border:1px solid red;*/
}
#all-questions-preview>.content>.question-container .answer-input{
display:inline-block;
padding:5px 10px;
border-bottom:2px solid #e171ae;
color: #be3e89;
width:calc(100% - 50px)
}
#all-questions-preview>.content>.question-container .answer-span .close{
position:absolute;
padding:5px;
color: #f02f24;
font-size: 1.2em;
transform: rotate(45deg);
top:15px;
right:22px;
background-color:transparent;
border:none !important;
outline: none !important;
cursor:pointer;
border-radius:100%;
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
}
#all-questions-preview>.content>.question-container .add-answer{
display: inline-block;
margin-top:15px;
background-color: rgba(243, 200, 86, 0.48);
border:2px solid rgb(221, 177, 84);
color: rgb(153, 122, 58);
padding:10px 20px;
border-radius: 5px;
cursor: pointer;
position: absolute;
right:15px;
bottom:10px;
}
#all-questions-preview> .add-question{
display: inline-block;
background-color: rgba(60, 243, 71, 0.48);
border:2px solid rgb(69, 198, 59);
color: rgb(32, 114, 31);
padding:10px 20px;
border-radius: 5px;
cursor: pointer;
position: absolute;
margin-top: -62px;
margin-left:10px;
font-weight: bold;
}
#all-questions-preview> .submit{
display: block;
width:90%;
margin:15px auto 15px auto;
background-color: rgba(74, 148, 243, 0.48);
border:2px solid rgb(74, 148, 243);
color: rgb(39, 77, 127);
padding:15px 20px;
font-weight: bold;
box-shadow: 0 5px 5px 1px rgba(61, 122, 200, 0.5);
border-radius: 5px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="content">
<form action="#" method="post" id="all-questions-preview">
<div class="content">
</div>
<button class="add-question" type="button">Add new question</button>
<br>
<button type="submit" class="submit">Submit</button>
</form>
<form action="test.php" id="all-questions-main" method="post" style="display: none">
<input type="hidden" name="data" id="questions-data">
</form>
</div>
<script>
$(document).ready(function() {
createQuestion($('#all-questions-preview')); //default one question added
$('#all-questions-preview').on('submit', previewFormSubmit);
$('#all-questions-preview .add-question').on('click', addQuestion);
});
function previewFormSubmit(ev) {
ev.preventDefault();
let data = [];
getQuestions($(this)).each(function() {
let question = $(this);
let question_data = {};
question_data['question_sentence'] = question.find('.question-sentence').eq(0).val();
let question_answers = [];
getAnswers(question).each(function() {
let answer = $(this);
let answer_input = answer.find('.answer-input').val();
if (answer_input.trim() !== "") {
question_answers.push(answer_input)
}
});
question_data['question_answers'] = question_answers;
data.push(question_data);
});
$('#all-questions-main>#questions-data').val(JSON.stringify(data));
$('#all-questions-main')[0].submit();
}
function addAnswer(event) {
let question_container = $(this).parents('.question-container').eq(0);
createAnswer(question_container);
}
function createAnswer(question_container) {
let answers = getAnswers(question_container);
let answer_span = $("<span>").addClass('answer-span');
let closeBtn = null;
if (answers.length > 0) {
closeBtn = $("<button>").attr({
type: 'button',
class: 'close'
}).text('+').on('click', deleteAnswer);
}
let answer_input = $("<input>").addClass('answer-input').attr({
type: 'text',
name: 'answer',
placeholder: 'answer' + (answers.length + 1)
});
if (answers.length === 0) {
answer_input.attr('required', 'required')
}
let container_answers = question_container.find('.answers-container').eq(0);
answer_span.append(closeBtn, answer_input);
container_answers.append(answer_span);
return answer_span;
}
function getAnswers(question_container) {
return (question_container.find(".answers-container .answer-span"));
}
function addQuestion(event) {
let all_questions_form = $(this).parents("#all-questions-preview").eq(0);
createQuestion(all_questions_form);
}
function getQuestions(all_question_form) {
return (all_question_form.find('.question-container'));
}
function createQuestion(all_questions_form) {
let all_questions_form_content = all_questions_form.find(">.content").eq(0);
let questions = getQuestions(all_questions_form);
let new_question = $("<div>").addClass('question-container');
let question_title = $("<h4>").addClass('question-title').text('Question number' + (questions.length + 1));
let closeBtn = null;
if (questions.length > 0) {
closeBtn = $("<button>").attr({
type: 'button',
class: 'close'
}).text('+').on('click', deleteQuestion);
}
let question_sentence = $("<input>").addClass('question-sentence').attr({
type: 'text',
name: 'question_sentence',
placeholder: 'question' + (questions.length + 1),
required: 'required'
});
let container_answers = $("<div>").addClass('answers-container');
let add_answer_btn = $("<button>").addClass('add-answer').attr('type', 'button').text('Add answer').on('click', addAnswer);
new_question.append(question_title, closeBtn, question_sentence, container_answers, add_answer_btn);
all_questions_form_content.append(new_question);
createAnswer(new_question);
return new_question;
}
function deleteQuestion() {
let question_container = $(this).parents('.question-container').eq(0);
let all_questions_form = $(this).parents("#all-questions-preview").eq(0);
let questions = getQuestions(all_questions_form);
if (questions.index(question_container) !== 0) {
question_container.fadeOut(200, function() {
$(this).remove();
})
}
}
function deleteAnswer() {
let question_container = $(this).parents('.question-container').eq(0);
let answer_span = $(this).parents('.answer-span').eq(0);
let all_questions_form = $(this).parents("#all-questions-preview").eq(0);
let answers = getAnswers(question_container);
if (answers.index(answer_span) !== 0) {
answer_span.fadeOut(200, function() {
$(this).remove();
})
}
}
</script>
</body>
</html>
In fact I want when The user clicks submit button The Data passes To Asp.net core codes
Please help me, I have been involved in this issue for several days
Thanks
Binding model does not happen in your HTML that is sent to the action method with a submit . You can transfer array question and answer with Ajax.
I find the reason why you can't get the model in backend code.
Because the data you passed is string format, so we can installNewtonsoft.Json library. And deserialize the string to object.
public class list_questions {
public string question_sentence { get; set; }
public List<string> question_answers { get; set; }
}
STEPS
In your .cshtml, you code should like below.
<form action="/ForTest/get_data" id="all-questions-main" method="post" style="display: none">
<input type="hidden" name="data" id="questions-data">
</form>
My /ForTest/get_data method
My test result

How can I insert a break between (multiple choice) answers in javascript?

I am making a quiz using javascript as a fun thing for my website. I followed a tutorial using https://www.sitepoint.com/simple-javascript-quiz/ , and after a bit of trial and error got it working with one question. But, as it is a multiple choice quiz, there are different choices to click on. The choices are all on one line. How can I change the code so that they are on separate lines? To help with any misconceptions, here are the choices and the code:
. a : 28 . b : 34 . c : 33 . d : More Information needed
<!DOCTYPE>
<html>
<style>
#sometext {
background-color: black;
border-radius: 10px;
border-left: 2px solid black;
border-right: 2px solid black;
border-top: 2px solid black;
border-bottom: 2px solid black;
color: white;
}
/* Add padding to containers */
.container {
padding: 16px;
background-color: #9999;
}
.navbar {
overflow: hidden;
background-color: #333;
font-family: Arial, Helvetica, sans-serif;
}
.navbar a {
float: left;
font-size: 16px;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.navbar a:hover{
background-color: red;
}
body {
font-family: Verdana, sans-serif;
margin: 0;
text-align: center;
background-color: rgb(150, 175, 200);
}
#p {
position: relative;
font-family: sans-serif;
text-transform: uppercase;
font-size: 2em;
letter-spacing: 4px;
overflow: hidden;
background: linear-gradient(90deg, #000, #fff, #000);
background-repeat: no-repeat;
background-size: 80%;
animation: animate 3s linear infinite;
-webkit-background-clip: text;
-webkit-text-fill-color: rgba(255, 255, 255, 0);
}
#Header {
background-color: rgb(150, 175, 200);
color: Black;
font-family: Courier;
font-size: 50px;
background-position: center;
text-shadow: 0 1px 0 #ccc,
0 2px 0 #c9c9c9,
0 3px 0 #bbb,
0 4px 0 #b9b9b9,
0 5px 0 #aaa,
0 6px 1px rgba(0,0,0,.1),
0 0 5px rgba(0,0,0,.1),
0 1px 3px rgba(0,0,0,.3),
0 3px 5px rgba(0,0,0,.2),
0 5px 10px rgba(0,0,0,.25),
0 10px 10px rgba(0,0,0,.2),
0 20px 20px rgba(0,0,0,.15);
}
#keyframes animate {
0% {
background-position: -500%;
}
100% {
background-position: 500%;
}
}
</style>
<body>
<nav class="navbar">
<a href = "file:///C:/Users/xenia/De
sktop/InfoSpace/Home.html">Home</a>
<a href = "file:///C:/Users/xe
nia/Desktop/InfoSpace/Profile.html">My Profile</a>
<a href = "file:///C:/Users/xenia/Desktop
/InfoSpace/Articles.html">Articles</a>
<a href = "file:///C:/Users/xenia
/Desktop/InfoSpace/Reviews.html">Reviews</a>
<a href = "file:///C:/Users/xenia/Desktop
/InfoSpace/Tutorials.html">Tutorials</a>
<a href = "file:///C:/Users/xe
nia/Desktop/InfoSpace/Help.html">Help</a>
</nav>
<h1 id="Header"><strong>INFOSPACE</strong></h1>
<p id="sometext">
<br />
This site is dedicated to provide information for budding scientists.
We aim to give you
a enjoyable and informative experience. If you experience a bug in
the
site please email Samuel Crawford at samuelhbc#icloud.com. Our blogs are reviews of products.
In each one there is a link to the product. If the link is no longer relevent please email samuelhbc#icloud.com.
Thank you for your attention and enjoy!!!
<br />
<br />
</p>
<br />
<br />
<h1><strong>IQ Test</strong></h1>
<div id = "quiz">
</div>
<button id = "submit"><h1>Submit Quiz</h1></button>
<div id = "results">
</div>
<br />
<br />
<p id="p">A website for young scientists.</p>
</body>
<script>
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
const myQuestions = [
{
question: "What is the next number in this sequence:
1,1,2,3,5,8,13,21...",
answers: {
a: "28",
b: "34",
c: "33",
d: "More Information needed"
},
correctAnswer: "b"
},
];
function buildQuiz() {
const output = [];
myQuestions.forEach(
(currentQuestion, questionNumber) => {
const answers = [];
for(letter in currentQuestion.answers){
answers.push(
`<label>
<input type="radio" name="question${questionNumber}"
value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
output.push(
`<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join('')} </div>`
);
}
);
quizContainer.innerHTML = output.join('');
}
function showResults() {
const answerContainers = quizContainer.querySelectorAll('.answers');
let numCorrect = 0;
myQuestions.forEach( (currentQuestion, questionNumber) => {
const answerContainer = answerContainers[questionNumber];
const selector = 'input[name=question'+questionNumber+']:checked';
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
if(userAnswer===currentQuestion.correctAnswer){
numCorrect++;
answerContainers[questionNumber].style.color = 'lightgreen';
}
else{
answerContainers[questionNumber].style.color = 'red';
}
});
resultsContainer.innerHTML = numCorrect + ' out of ' +
myQuestions.length;
}
buildQuiz();
submitButton.addEventListener('click', showResults);
</script>
</html>
One relatively easy way to do this would be to use Flexbox. In this case, you would add the following styles to your document:
.answers {
display: flex;
flex-direction: column;
}
display: flex makes the .answers divs flex elements, and flex-direction: column displays the div's content from top to bottom instead of from left to right. Once you have that, you can apply other flex properties to arrange the answers even more precisely to your liking. If you want to read more about how to use Flexbox, this article is a good place to get started.
One note about Flexbox though: It doesn't work especially well on older browsers (e.g. IE 11) if that is a concern.

How can I Disable a Clickable div right after onclick is initiated?

I couldnt find any answers on stack overflow to this specific question. I am trying to use pure javascript ONLY, so please no jquery answers.
So I posted all of my code as a general reference but my problem I believe lies in the javascript section. My question is, how can I make it so that my div "signup" is unclickable right AFTER it is clicked ONCE?
I tried putting a disable statement before frame and fadeOut are called inside the HideLogin() function. I also tried with css pointer-events. Nothing works and everytime I click SignUp, the animations repeat. Thank you in advance for the help.
function HideLogin() {
var login = document.getElementById("login");
var SignUpSheet = document.getElementById("SignUpSheet");
var titlecard = document.getElementById("titlecard");
var signup = document.getElementById("signup");
SignUpSheet.style.display = "block";
titlecard.style.display = "block";
frame(signup);
fadeOut(login);
/*fadeIn(document.getElementById("SignUpSheet"));
fadeIn(document.getElementById("titlecard")); */
}
function frame(signup) {
var pos = 125;
var id = setInterval(function() {
if (pos == 0) {
clearInterval(id);
} else {
pos--;
signup.style.top = pos + 'px';
}
}, 1);
}
function fadeOut(element) {
var op = 1; // initial opacity
var timer = setInterval(function() {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 20);
}
function fadeIn(element) {
var op = 0.1; // initial opacity
var timer = setInterval(function() {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.display = "block";
op += 0.1;
}, 20);
}
body,
html {
min-height: 100%;
}
body
/* Background handeling*/
{
color: white;
background: url(images/Hunter.jpg) center no-repeat;
background-size: cover;
background-color: #444;
}
/*------------------------------------------------------------- */
#logBox
/*Div that holds two links */
{
position: relative;
//border: 2px solid white;
height: 300px;
width: 300px;
margin-left: 70px;
margin-top: 50px;
}
#login
/* login link */
{
position: absolute;
cursor: pointer;
display: block;
//border: 2px solid white;
background: -webkit-linear-gradient(red, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-family: papyrus;
font-size: 70px;
color: red;
text-shadow: 2px 2px black;
transition: text-shadow 0.5s ease;
}
#login:hover {
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 4px 4px black;
}
#signup
/* sign up link */
{
position: absolute;
cursor: pointer;
display: block;
//border: 2px solid white;
background: -webkit-linear-gradient(red, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
top: 125px;
font-family: papyrus;
font-size: 70px;
color: red;
text-shadow: 2px 2px black;
transition: text-shadow 0.5s ease;
}
#signup:hover {
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 4px 4px black;
}
/*--------------------------------------------------------------- */
/* Div that holds two sheets */
#LogInSheet {
display: none;
}
#LoginTitle {}
#SignUpSheet {
display: none;
}
#SignUpTitle {}
/*--------------------------------------------------------------- */
#titlecard
/*title display */
{
position: absolute;
display: none;
bottom: 0px;
right: 50px;
//border: 2px solid white;
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 45px;
color: gray;
text-align: center;
font-family: papyrus;
text-shadow: 2px 2px black;
}
<!doctype html>
<html>
<head>
<title>The Prime Legion</title>
<link rel="stylesheet" type="text/css" href="page1.css">
<script type="text/javascript" src="page1.js"></script>
</head>
<body>
<div id="logBox">
<div id="login" onclick="HideSignin()">
Log In
</div>
<div id="signup" onclick="HideLogin()">
Sign Up
</div>
</div>
<div id="LogInSheet">
<div id="LoginTitle">
<p>
<h4>Hello</h4>
</p>
</div>
</div>
<div id="SignUpSheet">
<div id="SignupTitle">
<p>
<h4>Welcome</h4>
</p>
</div>
</div>
<div id="titlecard">
<p>
<h1>The Prime Legion</h1>
</p>
</div>
</body>
</html>
Unless you have a particular need to use <div>s for your buttons, you could change the HTML to use <button> elements instead. That way you could disable it using the disabled attribute and it should prevent any further clicks without having to store and track any additional JavaScript variables.
<button id="signup" onclick="HideLogin()">Sign Up</button>
function HideLogin() {
document.getElementById("signup").disabled = true;
...
}
I would suggest the following:
define a global variable loginCliked=false
then in your HideLogin function:
HideLogin = function(){
if(!loginClicked){
loginClicked=true;
// Do everything else
}
}
So that with the first click it will set loginClicked to true. If you click the button for the second time it does nothing

Categories

Resources