Why my buttons are overlapping my input fiels? - javascript

I am following a tutorial to make a quiz in js. I am not very good especially with css. Can someone help me to figure it out why at question 3 my answers(from 1-5) are behind the buttons? I want the button to always be under the answers
This is how it should look like:
enter image description here
And this is how it looks:
enter image description here
(function () {
const quizContainer = document.getElementById("quiz");
const resultsContainer = document.getElementById("results");
const submitButton = document.getElementById("submit");
const myQuestions = [
{
question: `Apa pe care o consum este plata, oligoelementala, in recipient de sticla, structurata sau filtrata de la robinet`,
factor: 2,
},
{
question: `Sunt iubitor/consumator de lactate proaspete/ lactate maturate`,
factor:2,
},
{
question: `Am o toleranta buna (pot consuma fara sa dezvolt reactie cutanata/ digestiva/ respiratorie) la
ton, peste spada, rechin, somon, scoici, fructe de mare, alti pesti oceanici
produse care contin gluten: paine, cereale, biscuiti, prajituri, paste, fainoase
alune, migdale, seminte de floarea soarelui, capsuni, alte fructe de padure
mazare, fasole, linte, naut, varza, brocoli, conopida`,
factor:2,
},
{
question: `Consum de 3x/saptamana oua de pasare/icre de peste`,
factor:2,
},
{
question: `Mananc saptamanal stridii, fructe de mare, nuci si seminte, ciocolata neagra`,
factor:2,
},
{
question: `Mananc zilnic fructe de culoare mov/ negre sau rosii`,
factor:2,
},
{
question: `Mananc zilnic ulei de masline/ cocos/ unt/ulei de germeni de grau/ ulei de canepa`,
factor:2,
},
{
question: `Mananc zilnic legume cu frunze verzi : Salata verde/ spanac / rucola / leurda / nasturel /creson de apa / cicoare / andive / patrunjel`,
factor:1,
},
{
question: `Mananc zilnic dulciuri procesate, prajituri, crème`,
factor:2,
},
{
question: `Mananc zilnic proteina animala de tip carne de porc/ vita/pasare`,
factor:2,
},
{
question: `Mananc saptamanal mezeluri/patiserie/conserve sau alte alimente care contin conservanti sintetici`,
factor:1,
},
{
question: `Consum zilnic bauturi alcoolice: spirtoase/ vin/ bere/ alte bauturi alcoolice`,
factor:2,
},
{
question: `Consum zilnic minerale/ vitamine/ pulberi alcaline/ pulberi de super alimente/ ceai verde`,
factor:2,
},
{
question: `Sunt alergic la praf/ polen/ fan/ plante de sezon/ ambrozie/ artemisia/ par animale/ intepaturi insecte/ mucegaiuri/ medicamente`,
factor:1,
},
{
question: `Locuiesc intr-un oras aglomerat cu aer poluat`,
factor:1,
},
{
question: `Locuiesc intr-o zona cu linii de inalta tensiune/ antene de telecomunicatii/dorm cu telefonul mobil deschis langa pat`,
factor:1,
},
{
question: `Am afectiuni cronice diagnosticate pentru care primesc medicatie`,
factor:1,
},
{
question: ` Sunt frecvent in situatia de a apela la antibiotice pentru rezolvarea unor probleme de sanatate`,
factor:1,
},
{
question: `Am tulburari de tranzit intestinal (de exemplu mai putin de 2 scaune zilnice)`,
factor:1,
},
{
question: `Am afectiuni inflamatorii de piele sau la nivelul sitemului osteoarticular (oaselor si incheieturilor)`,
factor:2,
},
{
question: `Fac miscare zilnic sau practic sporturi de tip jogging, cardio, aerobic, sarituri`,
factor:2,
},
{
question: `Viata familiala/ profesionala/ sociala e caracterizata de stress intens`,
factor:2,
},
{
question: `Am stare de oboseala accentuata la trezire si manifest scaderea capacitatii de concentrare/ deconectare /detensionare`,
factor:1,
},
{
question: `Merg la culcare pana in ora 23:00 si am un somn odihnitor`,
factor:2,
},
{
question: `Am trecut printr-o trauma emotionala in ultimii 5 ani de tip: deces al unui membru al familiei/ divort/ accident /imbolnavire`,
factor:1,
},
];
const answersToQuiz =
[
"Niciodata",
"Rar",
"Ocazional",
"Frecvent",
"Intodeauna"
]
function buildQuiz() {
// variable to store the HTML output
const output = [];
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
// variable to store the list of possible answers
const answers = [];
// and for each available answer...
for (const number in answersToQuiz) {
// ...add an HTML radio button
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${number}">
${parseInt(number) + 1} :
${answersToQuiz[number]}
</label>`
);
}
// add this question and its answers to the output
output.push(
`<div class="slide">
<div class="question">${parseInt(questionNumber) + 1}. ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>`
);
});
// finally combine our output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join("");
}
function showResults() {
// gather answer containers from our quiz
const answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
let currentScore = 0;
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
if(userAnswer === undefined)
{
alert("Va rugam sa raspundeti la toate intrebarile");
}
currentScore += (parseInt(userAnswer) + 1) * myQuestions[questionNumber].factor;
});
//display a slider
// show number of correct answers out of total
resultsContainer.innerHTML = `Curent score ${currentScore}`;
}
function showSlide(n) {
slides[currentSlide].classList.remove('active-slide');
slides[n].classList.add('active-slide');
currentSlide = n;
if(currentSlide === 0){
previousButton.style.display = 'none';
}
else{
previousButton.style.display = 'inline-block';
}
if(currentSlide === slides.length-1){
nextButton.style.display = 'none';
submitButton.style.display = 'inline-block';
}
else{
nextButton.style.display = 'inline-block';
submitButton.style.display = 'none';
}
}
function showNextSlide() {
showSlide(currentSlide + 1);
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
// display quiz right away
buildQuiz();
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
showSlide(0);
// on submit, show results
submitButton.addEventListener("click", showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
})();
#import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);
body{
font-size: 20px;
font-family: 'Work Sans', sans-serif;
color: #333;
font-weight: 300;
text-align: center;
background-color: #f8f6f0;
}
h1{
font-weight: 300;
margin: 0px;
padding: 10px;
font-size: 20px;
background-color: #444;
color: #fff;
}
.question{
font-size: 30px;
margin-bottom: 10px;
}
.answers {
margin-bottom: 20px;
text-align: left;
display: inline-block;
}
.answers label{
display: block;
margin-bottom: 10px;
}
button{
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #279;
color: #fff;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-bottom: 20px;
margin-top: 20px;
z-index: 3;
position: relative;
}
button:hover{
background-color: #38a;
}
.slide{
position: absolute;
left: 0px;
top: 0px;
width: 100%;
z-index: 1;
opacity: 0;
transition: opacity 0.5s;
}
.active-slide{
opacity: 1;
z-index: 2;
}
.quiz-container{
position: relative;
height: 200px;
margin-top: 40px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="quiz-container">
<div id="quiz"></div>
</div>
<button id="previous">Intrebarea precedenta</button>
<button id="next">Urmatoare intrebare</button>
<button id="submit">Afla rezultatul</button>
<div id="results"></div>
<script src="QuizLogic.js"></script>
<link rel="stylesheet" href="QuizTransition.css">
</body>
</html>

You have a strict height of your main div 200px. You can do
1) Increase height depend on your content
2) Put your buttons in div after your main div
Main problem is that you don`t have a content grid. So you have to create it before put something into page

Related

Can't replace image when I click panel croussel item

I can't seem to find a way to replace an image (used cats as an example) when I click one panel that isn't the one i've clicked before.
if (clicked=="panel1" && (document.getElementById("imagemLat1").style.visibility == "hidden")) || (clicked=="panel1" && ((document.getElementById("imagemLat2").style.visibility == "visible") || (document.getElementById("imagemLat3").style.visibility == "visible")))
This doesn't seem to work, and I'm not quite sure why.
Also, i'm not quite sure how to have all three images in the same spot; I've tried to have them all inside the same div, with no success.
Finally, is it possible to have only one panel open? My idea was if we click one, the previously opened one was supposed to close.
var el_down = document.getElementById("accordion");
<!-- var cliques = document.getElementById("cliques"); -->
var div = 0;
<!-- var height = document.panel.style.height; -->
document.getElementById("imagemLat1").style.visibility = "hidden";
document.getElementById("imagemLat2").style.visibility = "hidden";
document.getElementById("imagemLat3").style.visibility = "hidden";
function clicado(clicked){
el_down.innerHTML = "ID = "+clicked;
div++;
//<!-- el_down.innerHTML = "painel = "+height; -->
if (clicked=="panel1" && div%2!="0"){
//if (clicked=="panel1" && (document.getElementById("imagemLat1").style.visibility == "hidden")) || (clicked=="panel1" && ((document.getElementById("imagemLat2").style.visibility == "visible") || (document.getElementById("imagemLat3").style.visibility == "visible"))){
document.getElementById("imagemLat1").style.visibility = "visible";
document.getElementById("imagemLat2").style.visibility = "hidden";
document.getElementById("imagemLat3").style.visibility = "hidden";
}
else {
document.getElementById("imagemLat1").style.visibility = "hidden";
}
if (clicked=="panel2" && div%2!="0"){
// document.getElementById("imagemLat1").style.visibility = "hidden"; -->
document.getElementById("imagemLat2").style.visibility = "visible";
// document.getElementById("imagemLat3").style.visibility = "hidden"; -->
}
else{
document.getElementById("imagemLat2").style.visibility = "hidden";
}
if (clicked=="panel3" && div%2!="0"){
document.getElementById("imagemLat3").style.visibility = "visible";
}
else{
document.getElementById("imagemLat3").style.visibility = "hidden";
}
}
var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName("panel");
var el_down = document.getElementById("accordion");
var cliques = document.getElementById("cliques");
var div = 0;
var i;
for (i = 0; i < acc.length ; i++) {
acc[i].addEventListener("click", function(clicado) {
this.classList.toggle("toggle");
div++;
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
);
}
.accordion {
/* background-color: #777; */
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active, .accordion:hover {
/* background-color: #ccc; */
}
.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
.toggle:after {
content: "\2212";
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://use.fontawesome.com/releases/v5.15.4/js/all.js" crossorigin="anonymous"></script>
<!-- Google fonts-->
<link href="https://fonts.googleapis.com/css?family=Merriweather+Sans:400,700" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic" rel="stylesheet" type="text/css" />
<!-- Third party plugin CSS-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script>
<!-- Third party plugin JS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script>
<!-- Core theme JS-->
<script src="js/scripts_test.js"></script>
<!-- Scroll function !-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<div class="row d-flex justify-content-start">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-7">
<br><div class="h4 text-white-75 mb-2"><h3><i class="fa fa-lightbulb" aria-hidden="true"></i> Ambiente</h3></div>
<p id = "accordion"> </p>
<button class="accordion" id="panel1" onclick="clicado(this.id)">Dimensionamento do espaço</button>
<div class="panel">
<br><p>Quantas vezes já ouviu queixas sobre a sua cozinha com pouca luz ou sentiu dores de cabeça e desconforto com luz demasiado forte?</p>
<p style="text-align: justify; text-justify: inter-word;">É fundamental determinar a quantidade de luz e de luminárias para cada ambiente, uma vez que a iluminação excessiva pode causar desconforto ocular e aumentar despesas com a eletricidade, e uma iluminação insuficiente pode causar diversos problemas graves para a sua saúde física, mental e social.</p>
<p style="text-align: justify; text-justify: inter-word;">Com uma análise cuidada dos objetivos para cada ambiente em estudo e das especificações que o cliente pretende, é possível calcular e projetar soluções adequadas às necessidades dos clientes de forma eficiente e sustentável.</p>
</div>
<button class="accordion" id="panel2" onclick="clicado(this.id)">Posicionamento de luminárias para um melhor aproveitamento</button>
<div class="panel">
<br><p style="text-align: justify; text-justify: inter-word;">No decorrer da realização do estudo luminotécnico, o tipo de iluminação pretendido e os objetos existentes no espaço em estudo, são de extrema relevância, pois estes são indispensáveis para projetar uma iluminação eficiente, posicionando as luminárias da melhor forma, tendo sempre em conta as atividades que serão realizadas no ambiente em estudo.</p>
</div>
<button class="accordion" id="panel3" onclick="clicado(this.id)">Personalizar ambientes de acordo com a necessidade</button>
<div class="panel">
<br><p style="text-align: justify; text-justify: inter-word;">Cada cliente tem as suas próprias especificações e necessidades, e cada espaço tem uma função especifica.<br>O estudo luminotécnico permite personalizar e adaptar o espaço às necessidades reais de cada cliente. </p>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-5"><br><br><br>
<div class="sidebar-image">
<div class="imagemLateral">
<a id="imagemLat1" href="testMain.html"><span style="display: block;" id= "cliques"><img id="logo1" src="https://i.ytimg.com/vi/fleIpdMXopc/maxresdefault.jpg"></span></a>
</div>
</div>
<div class="sidebar-image">
<div class="imagemLateral">
<a id="imagemLat2" href="testMain.html"><span style="display: block;" id= "cliques"><img id="logo2" src="https://www.pets4homes.co.uk/images/classifieds/2013/10/02/438916/large/lovely-1-year-old-tabby-cat-female-524c0ebc2c3f1.jpg"></span></a>
</div>
</div>
<div class="sidebar-image">
<div class="imagemLateral">
<a id="imagemLat3" href="testMain.html"><span style="display: block;" id= "cliques"><img id="logo3" src="https://www.pets4homes.co.uk/images/classifieds/2013/08/21/398215/large/1-year-old-male-fluffy-white-cat-52147ca5d8b39.jpg"></span></a>
</div>
</div>
</div>
</div>
</body>
</html>
Well you can achieve this by the following ways in below snippet .
The first code which is commented in JS is dynamic one but it don't work as you need ( that is when one accordion is clicked then others are closed ) but it is fast because you can work with as many accordion as you want using single JS .
//function panelClick(reed) {
// reed.classList.toggle("active");
// var daad = reed.nextElementSibling;
// if (daad.style.display === "block") {
// daad.style.display = "none";
// } else {
// daad.style.display = "block";
// }
//}
function panelClick1() {
document.getElementsByClassName("panel")[1].style.display = "none";
document.getElementsByClassName("panel")[2].style.display = "none";
var daad = document.getElementById("panel1Content");
if (daad.style.display === "block") {
daad.style.display = "none";
} else {
daad.style.display = "block";
}
var reed = document.getElementById("panel1Img");
if (reed.style.display === "block") {
reed.style.display = "none";
} else {
reed.style.display = "block";
}
document.getElementById("panel2Img").style.display = "none";
document.getElementById("panel3Img").style.display = "none";
}
function panelClick2() {
document.getElementsByClassName("panel")[0].style.display = "none";
document.getElementsByClassName("panel")[2].style.display = "none";
var daad = document.getElementById("panel2Content");
if (daad.style.display === "block") {
daad.style.display = "none";
} else {
daad.style.display = "block";
}
document.getElementById("panel1Img").style.display = "none";
var reed = document.getElementById("panel2Img");
if (reed.style.display === "block") {
reed.style.display = "none";
} else {
reed.style.display = "block";
}
document.getElementById("panel3Img").style.display = "none";
}
function panelClick3() {
document.getElementsByClassName("panel")[0].style.display = "none";
document.getElementsByClassName("panel")[1].style.display = "none";
var daad = document.getElementById("panel3Content");
if (daad.style.display === "block") {
daad.style.display = "none";
} else {
daad.style.display = "block";
}
document.getElementById("panel1Img").style.display = "none";
document.getElementById("panel2Img").style.display = "none";
var reed = document.getElementById("panel3Img");
if (reed.style.display === "block") {
reed.style.display = "none";
} else {
reed.style.display = "block";
}
}
.accordion {
/* background-color: #777; */
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active,
.accordion:hover {
background-color: #ccc;
}
.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
.panel {
padding: 0 18px;
background-color: white;
display: none;
}
.panelImg {
display: none
}
<div>
<button class="accordion" id="panel1" onclick="panelClick1()"> Panel1</button>
<div class="panel" id="panel1Content">
<p>This is 1st pannel content</p>
</div>
<button class="accordion" id="panel2" onclick="panelClick2()">Panel2</button>
<div class="panel" id="panel2Content">
<p>This is 2nd pannel content</p>
</div>
<button class="accordion" id="panel3" onclick="panelClick3()">Panel3</button>
<div class="panel" id="panel3Content">
<p>This is 3rd pannel content</p>
</div>
<div id="demo"></div>
</div>
<img src="#1" alt="#1" id="panel1Img" class="panelImg">
<img src="#2" alt="#2" id="panel2Img" class="panelImg">
<img src="#3" alt="#3" id="panel3Img" class="panelImg">
Also , instead of changing images put them in panelContent's <div> element so they will hide and show with accordion and it will reduce some of the code making execution a little bit fast

How to create a form with modal windows?

I know how to create a form, I know how to create a modal window. My concern is to combine the two.
For the moment I managed to make sure that at the click on the first element of research, a window opens.
However I have to do that on every element of the form. How to associate each search element with its own modal window? Do I have to repeat the javascript code as many times as research items, or is there a cleaner way? thank you so much
$(document).ready(function() {
// Lorsque l'on clique sur show on affiche la fenêtre modale
$('#show').click(function(e) {
//On désactive le comportement du lien
e.preventDefault();
showModal();
});
// Lorsque l'on clique sur le fond on cache la fenetre modale
$('#fond').click(function() {
hideModal();
});
// Lorsque l'on modifie la taille du navigateur la taille du fond change
$(window).resize(function() {
resizeModal()
});
});
function showModal() {
var id = '#modal';
$(id).html('Voici ma fenetre modale<br/>Fermer la fenetre');
// On definit la taille de la fenetre modale
resizeModal();
// Effet de transition
$('#fond').fadeIn(1000);
$('#fond').fadeTo("slow", 0.8);
// Effet de transition
$(id).fadeIn(2000);
$('.popup .close').click(function(e) {
// On désactive le comportement du lien
e.preventDefault();
// On cache la fenetre modale
hideModal();
});
function hideModal() {
// On cache le fond et la fenêtre modale
$('#fond, .popup').hide();
$('.popup').html('');
}
}
function resizeModal() {
var modal = $('#modal');
// On récupère la largeur de l'écran et la hauteur de la page afin de cacher la totalité de l'écran
var winH = $(document).height();
var winW = $(document).width();
// le fond aura la taille de l'écran
$('#fond').css({
'width': winW,
'height': winH
});
// On récupère la hauteur et la largeur de l'écran
var winH = $(window).height();
}
#fond {
position: absolute;
z-index: 9000;
background-color: #0F3C68;
display: none;
}
.popup {
position: fixed;
display: none;
z-index: 9999;
padding: 20px;
background-color: white;
left: 40%;
}
#modal {
width: 760px;
height: 440px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="fond"></div>
<div id="modal" class="popup"></div>
Ville(s) de Départ
You can use the code for the same model but will have to pass the data you want to show against every element of the form. I have updated your showModal method which now accepts message as input and shows that message. You can use the same methodology for complex modal as well i.e. pass some parameter as input to the modal and based on that parameters, show the appropriate response to user
$(document).ready(function() {
// Lorsque l'on clique sur show on affiche la fenêtre modale
$('#message1').click(function(e) {
e.preventDefault();
showModal('First Message Clicked');
});
$('#nessage2').click(function(e) {
e.preventDefault();
showModal('Second Message Clicked');
});
// Lorsque l'on clique sur le fond on cache la fenetre modale
$('#fond').click(function() {
hideModal();
});
// Lorsque l'on modifie la taille du navigateur la taille du fond change
$(window).resize(function() {
resizeModal()
});
});
function showModal(message) {
var id = '#modal';
$(id).html('<br>' + message + '<br/>Close');
// On definit la taille de la fenetre modale
resizeModal();
// Effet de transition
$('#fond').fadeIn(1000);
$('#fond').fadeTo("slow", 0.8);
// Effet de transition
$(id).fadeIn(2000);
$('.popup .close').click(function(e) {
// On désactive le comportement du lien
e.preventDefault();
// On cache la fenetre modale
hideModal();
});
function hideModal() {
// On cache le fond et la fenêtre modale
$('#fond, .popup').hide();
$('.popup').html('');
}
}
function resizeModal() {
var modal = $('#modal');
// On récupère la largeur de l'écran et la hauteur de la page afin de cacher la totalité de l'écran
var winH = $(document).height();
var winW = $(document).width();
// le fond aura la taille de l'écran
$('#fond').css({
'width': winW,
'height': winH
});
// On récupère la hauteur et la largeur de l'écran
var winH = $(window).height();
}
#fond {
position: absolute;
z-index: 9000;
background-color: #0F3C68;
display: none;
}
.popup {
position: fixed;
display: none;
z-index: 9999;
padding: 20px;
background-color: white;
left: 40%;
}
#modal {
width: 760px;
height: 440px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="fond"></div>
<div id="modal" class="popup"></div>
First Message
<br/>
Second Message

opening multiple divs with javascript

I'm trying to open up a div on the right side, and change the animation div on the same time, that works when I use the same div ID, but that gives me problems with css positions. So when I press 1 the intro animation disappears and the animation div that loads data_1.json appears.
http://bolink.eu/demo/
Current js code :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('a').click(function () {
var divtitle= this.title;
$("#"+divtitle).show("slow").siblings().hide(1000);
});
});
</script>
<script>
$(function() {
$("#slideshow > div:gt(0)").hide();
setInterval(function() {
$('#slideshow > div:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#slideshow');
}, 3000);
});
</script>
Here the rest of the source code:
<!DOCTYPE html>
<html lang="nl">
<head>
<title>KVL</title>
<meta charset="UTF-8">
<meta name="robots" content="index,follow">
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Open+Sans');
#font-face {
font-family: Bree;
src: url(Bree.otf) format("opentype");
}
body {
margin: 0 0 600px;
font-family: 'Open Sans', sans-serif;
color:black;
}
*{
margin:0;
padding:0;
}
a {
color:#f6f0e3;
text-decoration:none;
}
.rhombus{
width:90px;
height:90px;
background:#d5c2f4;
margin:36px;
transform:rotate(-45deg);
float:left;
font-family: Bree;
}
.rhombus p{
transform:rotate(45deg) translate(10px,5px);
text-align:center;
font-size: 62px;
font-family: Bree;
}
#footer {
position: absolute;
left: 0;
bottom: 0;
height: 400px;
width: 100%;
text-align:center;
}
div.rechts {
color:black;
position: absolute;
right: 200px;
top: 150px;
margin-right: 30px;
width: 500px;
text-align: justify;
font-size: 24px;
}
h1 {
font-family: Bree;
font-size: 64px;
}
.bodymovin {
background-color:white;
width: 800px;
height:500px;
display:block;
overflow: hidden;
transform: translate3d(0,0,0);
margin: 20px;
position: absolute;
top: 10px;
left: 10px;
}
p.titel {
font-style: italic;
margin-bottom: 30px;
margin-top: 30px;
}
a.meer {
font-family: Bree;
font-size: 40px;
}
p.onder {
text-align: center;
margin: 50px;
}
</style>
<script src="bodymovin.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('a').click(function () {
var divtitle= this.title;
$("#"+divtitle).show("slow").siblings().hide(1000);
});
});
</script>
<script>
$(function() {
$("#slideshow > div:gt(0)").hide();
setInterval(function() {
$('#slideshow > div:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#slideshow');
}, 3000);
});
</script>
</head><body>
<div id="footer">
<div class="rhombus" style="background-color: #DCCD00;"><p>1</p></div>
<div class="rhombus" style="background-color: #EDA400;"><p>2</p></div>
<div class="rhombus" style="background-color: #39AA36;"><p>3</p></div>
<div class="rhombus" style="background-color: #3AA8DD;"><p>4</p></div>
<div class="rhombus" style="background-color: #00A79F;"><p>5</p></div>
<div class="rhombus" style="background-color: #808080;"><p>6</p></div>
</div>
<div>
<div id="content1" class="rechts" style="display: none">
<h1 style="color: #DCCD00;">Data Strategy</h1>
<p class="titel">Identificeren van kansen door beter datagebruik.</p>
<p class="verhaal">Met een quick scan identificeren we de mogelijkheden om met analytics de omzet en winst te laten groeien en prestaties verder te verbeteren. Vervolgens bepalen we samen met stakeholders een roadmap. Daarin leggen we vast hoe we relevante data in de organisatie optimaal identificeren, verzamelen, opslaan, beheren, delen en gebruiken.</p>
<p class="onder"><a class="meer" style="color: #DCCD00;" href="#">Lees meer</a></p>
</div>
<div id="content2" class="rechts" style="display: none">
<h1 style="color: #EDA400;">Data Economy</h1>
<p class="titel">Versterken van data-ecosystemen</p>
<p class="verhaal">Met pragmatische en schaalbare data-engineering helpen wij om bestaande en nieuwe data slim te structureren en op te slaan. Zodat alle betrokkenen in een organisatie de data eenvoudig kunnen vinden en gebruiken.</p>
<p class="onder"><a class="meer" style="color: #EDA400;" href="#">Lees meer</a></p>
</div>
<div id="content3" class="rechts" style="display: none">
<h1 style="color: #39AA36;">Business Intelligence</h1>
<p class="titel">Ontsluiten van relevante business-informatie</p>
<p class="verhaal">We gaan op zoek naar de toegevoegde waarde van gecombineerde bedrijfsdata. Hierbij gebruiken we geavanceerde data-analytics en data-visualisatie oplossingen, die bruikbaar zijn voor zowel data-experts en gewone gebruikers in uw organisatie.</p>
<p class="onder"><a class="meer" style="color: #39AA36;" href="#">Lees meer</a></p>
</div>
<div id="content4" class="rechts" style="display: none">
<h1 style="color: #3AA8DD;">Business Impact</h1>
<p class="titel">Creëren van nieuwe inzichten</p>
<p class="verhaal">Van data naar inzicht. Met state-of-the-artmodellen en -benaderingen ondersteunen wij gebruikers op alle niveaus in uw organisatie om op een intuïtieve manier nieuwe inzichten voor uw business te genereren. Waar nodig combineren we uw data met de business-kennis binnen uw bedrijf.</p>
<p class="onder"><a class="meer" style="color: #3AA8DD;" href="#">Lees meer</a></p>
</div>
<div id="content5" class="rechts" style="display: none">
<h1 style="color: #00A79F;">Business Analytics</h1>
<p class="titel">Implementeren van slimme actie voor business value</p>
<p class="verhaal">Wij helpen uw medewerkers om nieuwe verkregen inzichten door te vertalen in concrete groei- en verbeteracties. Ook monitoren we de impact hiervan op uw business. Zo laten wij uw medewerkers ervaren hoe een juist gebruik van data een groot verschil kan maken voor uw business.</p>
<p class="onder"><a class="meer" style="color: #00A79F;" href="#">Lees meer</a></p>
</div>
<div id="content6" class="rechts" style="display: none">
<h1 style="color: #808080;">KVL Academy</h1>
<p class="titel">Kennis vergroten is kennis delen.</p>
<p class="verhaal">Daarom investeren we in de ontwikkeling van onze eigen collega's. En trainen we de medewerkers van onze opdrachtgevers. Op alle domeinen binnen ons vakgebied. Ook bouwen we aan een nieuwe generatie data-experts met ons programma Scherp Talent.</p>
<p class="onder"><a class="meer" style="color: #808080;" href="#">Lees meer</a></p>
</div>
<div id="ani0" class="bodymovin"></div>
<script>
var anim;
var elem = document.getElementById('ani0')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_intro.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
<div class="bodymovin" id="content1" style="display:none"></div>
<script>
var anim;
var elem = document.getElementById('content1')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_1.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
<div id="content2" style="display:none" class="bodymovin"></div>
<script>
var anim;
var elem = document.getElementById('content2')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_2.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
<div id="content3" style="display:none" class="bodymovin"></div>
<script>
var anim;
var elem = document.getElementById('content3')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_3.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
<div id="content4" style="display:none" class="bodymovin"></div>
<script>
var anim;
var elem = document.getElementById('content4')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_4.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
<div id="content5" style="display:none" class="bodymovin"></div>
<script>
var anim;
var elem = document.getElementById('content5')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_5.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
<div id="content6" style="display:none" class="bodymovin"></div>
<script>
var anim;
var elem = document.getElementById('content6')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_6.json'
};
anim = bodymovin.loadAnimation(animData);
</script>
</div>
</body>
</html>
Hope someone can help!
You cannot use an ID more than once! That's why it's called an ID.
This also invalidates the HTML:
https://validator.w3.org/nu/?doc=http%3A%2F%2Fbolink.eu%2Fdemo%2F
Use class selectors. They can used in jQuery too:
$("."+divtitle)
I've put the animations in a different div container (animations) then the right side divs (right), and then renamed the animations code to ani1-ani6.
I've changed the following js code:
<script>
$(document).ready(function(){
$('a').click(function () {
var divtitle= "content"+this.title;
var anititle= "ani"+this.title;
$("#"+divtitle).show("slow").siblings().hide(1000);
$("#"+anititle).show("slow").siblings().hide(1000);
});
});
</script>
Hope it helps someone!

Flexbox carousel transition issue

I'm trying to build a simple carousel with flexbox for a mobile website.
I found some examples I used to build mine.
I have a last issue I cannot resolve.
When I swipe left, the transition does not work.
The current image disapears before the transition begins.
When I swipe right, it works fine.
Thanks for your help.
Here is my code :
<!DOCTYPE html>
<html lang="fr-FR">
<head>
<meta name="viewport" content="target-densitydpi=device-dpi; width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<style>
.flex, .flex-c
{
display: box;
display: flexbox;
display: flex;
}
.flex-c
{
flex-direction: column;
}
.carousel-container
{
overflow: hidden;
}
.carousel-element
{
flex: 1 0 100%;
transform: translateX(0);
order: 2;
}
.carousel-swipeleft
{
transform: translateX(100%);
}
.carousel-swiperight
{
transform: translateX(-100%);
}
.carousel-transition
{
transform: none !important;
transition: transform 0.5s cubic-bezier(0.23, 1, 0.32, 1);
}
.carousel-ocontainer
{
margin: 10px 0;
justify-content: center;
}
.carousel-o
{
background: lightgray none repeat scroll 0 0;
-ms-border-radius: 5px;
border-radius: 5px;
height: 10px;
margin: 0 5px;
outline: 0 none;
text-indent: -9999px;
width: 10px;
padding-bottom: 10px;
}
.carousel-oactive
{
background: black none repeat scroll 0 0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript">
$.mobile.pushStateEnabled = false;
Oog = function () {};
Oog.Carousel = function (containerClass, loop)
{
var self = this;
self.loop = loop;
self.elementClass = "carousel-element";
self.LazyClass = "carousel-lazy";
self.oContainerClass = containerClass + "-carousel-ocontainer";
self.oClass = "carousel-o";
self.oActiveClass = "carousel-oactive";
self.swipeleftClass = "carousel-swipeleft";
self.swiperightClass = "carousel-swiperight";
self.transitionClass = "carousel-transition";
self.containerSelector = "." + containerClass;
self.elementSelector = self.containerSelector + " ." + self.elementClass;
self.LazySelector = self.containerSelector + " ." + self.LazyClass;
self.findLazySelector = "." + self.LazyClass;
self.oContainerSelector = "." + self.oContainerClass;
self.oSelector = self.oContainerSelector + " ." + self.oClass;
};
Oog.Carousel.prototype =
{
initialize: function()
{
var self = this;
// Bullet points
var elements = $(self.elementSelector);
var html = "<div class='" + self.oContainerClass + " / carousel-ocontainer / flex'>";
for (var i = 0; i < elements.length; i++)
{
html = html + "<p class='" + self.oClass + "' data-id='" + $(elements[i]).data("id") + "'> O </p> ";
}
html = html + "</div>";
$(html).insertAfter(self.containerSelector);
// Affiche les bullets points si et seulement si le carousel est affiché
// -> nécessite que l'event existe (créé dans oog-mobile-script.js)
var oContainerSelector = self.oContainerSelector;
$(self.containerSelector).bind("displayChanged", function ()
{
if ($(this).css("display") === "none")
{
$(oContainerSelector).hide();
} else
{
$(oContainerSelector).show();
}
});
// Affichage du 1er élément du carousel
$(self.LazySelector).first().attr("src", $(self.LazySelector).first().data("src"));
$(self.oContainerSelector).hide();
$(self.oSelector).first().addClass(self.oActiveClass);
// Gestion des déplacements vers la gauche ou la droite
$(self.elementSelector).on("swipeleft", function ()
{
self.swipe(this, "swipeleft");
});
$(self.elementSelector).on("swiperight", function ()
{
self.swipe(this, "swiperight");
});
},
swipe: function(element, swipe)
{
var self = this;
var elements = $(self.elementSelector);
var nextElement;
if (swipe === "swipeleft")
{
elements.removeClass(self.swiperightClass);
elements.addClass(self.swipeleftClass);
nextElement = self.next(element, self.loop);
}
else
{
elements.removeClass(self.swipeleftClass);
elements.addClass(self.swiperightClass);
nextElement = self.prev(element, self.loop);
}
if (nextElement.length > 0)
{
$(self.oSelector).removeClass(self.oActiveClass);
$(self.oSelector + '[data-id="' + nextElement.data("id") + '"]').addClass(self.oActiveClass);
nextElement.find(self.findLazySelector).attr("src", nextElement.find(self.findLazySelector).data("src"));
for (var i = 0; i < elements.length; i++)
{
nextElement.css("order", (i + 1).toString());
nextElement = self.next(nextElement, true);
}
elements.removeClass(self.transitionClass);
setTimeout(function () { elements.addClass(self.transitionClass) }, 50);
}
},
next: function(element, loop)
{
var self = this;
return self.nextorprev(element, "swipeleft", loop);
},
prev: function (element, loop)
{
var self = this;
return self.nextorprev(element, "swiperight", loop);
},
nextorprev: function (element, swipe, loop) {
var self = this;
var elements = $(self.elementSelector);
var current = $(element);
var next;
if (swipe === "swipeleft") {
next = current.next();
if (next.length === 0 && loop) {
next = elements.first();
}
} else {
next = current.prev();
if (next.length === 0 && loop) {
next = elements.last();
}
}
return next;
}
};
$(document).ready(function()
{
var accessoryCarousel = new Oog.Carousel("product-tabAccessories", false);
accessoryCarousel.initialize();
});
</script>
</head>
<body class="body">
<div class="product-tabs / flex">
<div class="product-tab / product-tabAccessories / carousel-container / flex" data-tab="Accessories">
<a href="/prod-16768-Plaque-ONDUVILLA-217m2-rouge-ombre.html" title="Plaque ONDUVILLA rouge ombré, plusieurs surfaces disponibles" class="product-accessory / carousel-element / flex" data-id="16768">
<img class="carousel-lazy" alt="Plaque ONDUVILLA 2.17m² rouge ombré" data-src="http://media.oogarden.com/Product/0290/0290-0007-Thumb.jpg"/>
<div class="flex-c" style="justify-content: space-around; margin-left: 10px;">
<label>Plaque ONDUVILLA rouge ombré, plusieurs surfaces disponibles</label>
</div>
</a>
<a href="/prod-16769-Pointes-pour-feutre-bitumeux-x1200.html" title="Pointes pour bardeaux et feutres bitumeux " class="product-accessory / carousel-element / flex" data-id="16769">
<img class="carousel-lazy" alt="Pointes pour bardeaux et feutres bitumeux " data-src="http://media.oogarden.com/Product/0290/0290-0008-Thumb.jpg"/>
<div class="flex-c" style="justify-content: space-around; margin-left: 10px;">
<label>Pointes pour bardeaux et feutres bitumeux </label>
</div>
</a>
<a href="/prod-16782-Bardoline-100-3m2-bleu-ardoise.html" title="Bardoline couleur ardoise surface 3 m²" class="product-accessory / carousel-element / flex" data-id="16782">
<img class="carousel-lazy" alt="Bardoline couleur ardoise surface 3 m²" data-src="http://media.oogarden.com/Product/0290/0290-0004-Thumb.jpg"/>
<div class="flex-c" style="justify-content: space-around; margin-left: 10px;">
<label>Bardoline couleur ardoise surface 3 m²</label>
</div>
</a>
</div>
</div>
</body>
</html>

Time-delay between user input and system output chatbot

This is a code for a fakechat. I want a timedelay between user input and system output. I´ve tryed setTimeout and other methods without success but I´m a beginner on JS. How can I do it? Thanks to all!
<!DOCTYPE html>
<html lang="pt">
<head>
<title>Clarice Lispector</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Chat online com Clarice Lispector">
<style>
body {
background-color: buttonface;
font-family: Helvetica;
font-size: 10pt;
margin-top: 10px;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 10px;
}
.button {
font-family: Helvetica;
font-size: 10pt;
width: 92px;
}
textarea {
font-family: arial;
font-size: 10pt;
}
select {
font-family: arial;
font-size: 10pt;
width: 350px;
margin-left: 0px;
}
td {
font-family: arial;
font-size: 10pt;
}
</style>
<script type="text/javascript">
//----Data Declarations----
var convpatterns = new Array (
new Array (".*estás aí.*" , "Olá." , "aqui estou"),
new Array (".*ola.*|.*olá.*" , "Olá.","Tudo bem?"),
new Array ("bom dia" , "bom dia"),
new Array ("boa tarde" , "boa tarde"),
new Array ("que horas são" , "boa tarde"),
new Array ("boa noite" , "boa noite"),
new Array (".*de onde voce é.*|.*você é de onde.*|.*voce é de onde.*|.*és de onde.*" , "do Brasil. Ainda que tenha nascido na Europa vim com 2 anos para o Brasil."),
new Array ("obrigado pelo seu conselho" , "Obrigado a você pela companhia."),
new Array ("obrigado|obrigada" , "Obrigado a você." , "Não tem de quê."),
new Array (".*como gosta de ser tratada.*" , "pode me tratar por Clarice."),
new Array ("(.*?)[\?]" , "Não sei responder a essa questão", "... estou procurando, estou procurando. Estou tentando entender." , "Não tenho dados suficientes para responder", "desculpe, mas não sei responder"),
new Array (".*" , "pois..." , "... estou procurando, estou procurando. Estou tentando entender." , "não percebo" , "Ainda bem que sempre existe outro dia. E outros sonhos. E outros risos. E outras pessoas. E outras coisas..." , "Desculpa, mas não entendo. Pouco ou metades nunca me completaram." , "neste momento não sei responder. Pode enviar a sua questão para o meu email."));
uinput = ""
soutput = ""
dialog = ""
//-----The Core Code------
//-------
function mainroutine() {
uinput = document.mainscreen.BasicTextArea4.value;
dialog = dialog + "Você: " + uinput + '\r' + "\n";
conversationpatterns()
dialog = dialog + '\r' + "\n";
updatescreen();
var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;
}
//-------
function conversationpatterns() {
for (i=0; i < convpatterns.length; i++) {
re = new RegExp (convpatterns[i][0], "i");
if (re.test(uinput)) {
len = convpatterns[i].length - 1;
index = Math.ceil( len * Math.random());
reply = convpatterns[i][index];
soutput = uinput.replace(re, reply);
soutput = initialCap(soutput);
dialog = dialog + "Clarice: " + soutput + '\r' + "\n";
break;
}
}
}
//-------
function initScreen() {
updatescreen()
}
//-------
function updatescreen() {
document.mainscreen.BasicTextArea1.value = dialog
document.mainscreen.BasicTextArea2.value = soutput
document.mainscreen.BasicTextArea3.value = uinput
document.mainscreen.BasicTextArea4.value = ""
}
//-------
function initialCap(field) {
field = field.substr(0, 1).toUpperCase() + field.substr(1);
return field
}
//----Supplemental Code To Test System---
//------
function runtest(){
var testdata = new Array (
new Array ("Oi."),
new Array ("como gosta de ser tratada?"),
new Array ("qual o seu conselho?"),
new Array ("nunca serei capaz de escrever um livro"),
new Array ("obrigado pelo seu conselho.")
);
for (train=0; train < testdata.length; train++) {
document.mainscreen.BasicTextArea4.value = testdata[train];
mainroutine()
}
}
</script>
</head>
<body onLoad="initScreen()">
<div style="height:300px; color:white; background-color:black;margin:0px; padding:0; background-image:url(lispector.jpg); background-size: 100% 100%; ">
<br><br>
<div style="color:white; font-size:20px; line-height:150%; width:; margin:0 auto; padding:0; text-align: center">
<h1 style="font-weight:100">Conversa com Clarice Lispector</h1>
<p style="font-family: 'Neucha', cursive; letter-spacing:4px"><br>a partir de textos e entrevistas da autora</p>
</div>
<br>
<br>
</div>
<form name="mainscreen" onkeypress = "if(event.keyCode == 13) {mainroutine();return false}">
<table align="center">
<tr>
<td>
<br><br>
<textarea placeholder="Escreva a sua mensagem e pressione 'Enter'" name="BasicTextArea4" rows="2" cols="75"></textarea><br />
<textarea id="textarea_id" name="BasicTextArea1" rows="15" cols="75" ></textarea><br />
<textarea style="display:none" name="BasicTextArea2" rows="2" cols="75"></textarea><br />
<textarea style="display:none" name="BasicTextArea3" rows="2" cols="75"></textarea>
</td>
</tr>
</table>
<p align = "center">
<input id=runbutton class="button" type="button" value="Teste" name="run_button" onClick="runtest()">
<input id=helpbutton class="button" type="button" value="Ajuda" name="help_button" onClick="showhelp()">
</p>
</form>
<script>
function showhelp() {
alert("Algumas dicas para fazer conversa: \n\na escrita\no amor\nos livros\nconselhos\ngostos\ndados biográficos\nviagens...");
}
</script>
</body>
</html>
This is because dialog contains both the user & computer text in a single variable. Make a new variable for the computer dialog and another for the user dialog, finally send them at different times.
Something like this:
textareaElement.value = userDialog
setTimeout(function(){
textareaElement.value = computerDialog
}, 1000)

Categories