Repeat script through multiple elements - javascript

I have created a script that converts the HTML value from an element into a percentage, the percentage value then determines the width of another element (in this case a bar).
This is all well and good for a single element (as you will see), however, does not work when I have an element echoing through a page. Can I be pointed in the right direction here?
Current JS Fiddle: http://jsfiddle.net/ctalke/27no66rm/
//==================================== Bar Percentage Start ================================//
var a = document.getElementsByClassName('term')[0].innerHTML;
var b = document.getElementsByClassName('age')[0].innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
document.getElementsByClassName('barv')[0].style.width = Math.round(e) + '%';
document.getElementsByClassName('barv')[0].innerHTML = Math.round(e) + '%';
//==================================== Bar Percentage End =================================//
//===================================== Bar Colour Start ==================================//
var a1 = document.getElementById("barv");
if (e < 50) {
a1.className += " green";
} else if (e < 99) {
a1.className += " yellow";
} else {
a1.className += " red";
}
//===================================== Bar Colour End ==================================//
.bar {
text-align: center;
height: 20px;
border: 1px solid black;
color: white;
}
.hide {
display: none;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
color: black!important;
}
.green {
background-color: green;
}
<!-- Term -->
<div class="term hide">36</div>
<!-- Age -->
<div class="age hide">35</div>
<!-- Progress Bar -->
<div class="bar barv red"></div>
<br>
<!-- Term 1 -->
<div class="term hide">36</div>
<!-- Age 1 -->
<div class="age hide">2</div>
<!-- Progress Bar 1 -->
<div class="bar barv yellow"></div>
<br>
<!-- Term 2 -->
<div class="term hide">36</div>
<!-- Age 2 -->
<div class="age hide">15</div>
<!-- Progress Bar 2 -->
<div class="bar barv green"></div>

You just need to iterate over the snippet using a for loop instead.
var bars = document.getElementsByClassName('bar');
for (i = 0; i < bars.length; i++) {
// Your code here
}
And replace [0] with [i]
//==================================== Bar Percentage Start ================================//
var bars = document.getElementsByClassName('bar');
for (i = 0; i < bars.length; i++) {
var a = document.getElementsByClassName('term')[i].innerHTML;
var b = document.getElementsByClassName('age')[i].innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
document.getElementsByClassName('barv')[i].style.width = Math.round(e) + '%';
document.getElementsByClassName('barv')[i].innerHTML = Math.round(e) + '%';
//==================================== Bar Percentage End =================================//
//===================================== Bar Colour Start ==================================//
var a1 = document.getElementsByClassName("barv")[i];
if (e < 50) {
a1.className += " green";
} else if (e < 99) {
a1.className += " yellow";
} else {
a1.className += " red";
}
}
//===================================== Bar Colour End ==================================//
.bar {
text-align: center;
height: 20px;
border: 1px solid black;
color: white;
}
.hide {
display: none;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
color: black!important;
}
.green {
background-color: green;
}
<!-- Term -->
<div class="term hide">36</div>
<!-- Age -->
<div class="age hide">35</div>
<!-- Progress Bar -->
<div class="bar barv red"></div>
<br>
<!-- Term 1 -->
<div class="term hide">36</div>
<!-- Age 1 -->
<div class="age hide">2</div>
<!-- Progress Bar 1 -->
<div class="bar barv yellow"></div>
<br>
<!-- Term 2 -->
<div class="term hide">36</div>
<!-- Age 2 -->
<div class="age hide">15</div>
<!-- Progress Bar 2 -->
<div class="bar barv green"></div>
You can reduce the repetition of same selectors by caching them in a variable instead.
//==================================== Bar Percentage Start ================================//
var bars = document.querySelectorAll('.bar');
for (i = 0; i < bars.length; i++) {
var bar = bars[i];
var term = document.querySelectorAll('.term')[i];
var age = document.querySelectorAll('.age')[i];
var a = term.innerHTML;
var b = age.innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
bar.style.width = Math.round(e) + '%';
bar.innerHTML = Math.round(e) + '%';
//==================================== Bar Percentage End =================================//
//===================================== Bar Colour Start ==================================//
if (e < 50) {
bar.classList.add("green");
} else if (e < 99) {
bar.classList.add("yellow");
} else {
bar.classList.add("red");
}
}
//===================================== Bar Colour End ==================================//

I might be misreading your question, but are you asking about looping through all of the elements? If you're trying to do something to more than 1 element, try something like this
const arrayOfElements1 = document.querySelectorAll('yourCSSselectorGoesHere');
const arrayOfElements2 = document.querySelectorAll('yourCSSselectorGoesHere');
for (let i = 0; i < arrayOfElements.length; i += 1) {
arrayOfElements1[i].doStuff;
}
In the doStuff above you can do arrayOfElements1[i].innerHTML / arrayOfElements2[i].innerHTML * 100. I'm not entirely clear on what you're needing so let me know if I've misunderstood.

Just put your code in a for loop.
var barvs = document.getElementsByClassName("barv");
for (var index=0; index<barvs.length ;index++) {
var a = document.getElementsByClassName('term')[index].innerHTML;
var b = document.getElementsByClassName('age')[index].innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
barvs[index].style.width = Math.round(e) + '%';
barvs[index].innerHTML = Math.round(e) + '%';
var a1 = barvs[index];
if (e < 50) {
a1.className += " green";
} else if (e < 99) {
a1.className += " yellow";
} else {
a1.className += " red";
}
}

Related

Score not incrementing

I am programming a simple game in javascript and when the user hovers on the given coordinates it's score increases. My problem is the score does not increment after 1.
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
//Generating Co-ordinates
function generate() {
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
function points(x, y) {
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
points(x, y);
}
})
Even after adding a global count variable, your code is not working properly because of your if (xco == x && yco == y) condition fails after first run. Here you are comparing randomly generated x and y with xco, yco and updating score and calling generate again.
On your generate function you are creating new local variable x and y, not updating the global x and y. And the subsequent comparison (xco == x && yco == y) will fail because it still using the old x and y.
On your generate function, updating the global x and y should fix this issue,
x = Math.floor(Math.random() * 500) + 150;
y = Math.floor(Math.random() * 500) + 150;
Here is the complete code, I also made some minor changes, removed some redundant and duplicate codes
// Code goes here
$(document).ready(function(){
//on clicking let's play
var t = 120;
var count = 0;
$("button.play").click(function(event){
event.preventDefault();
$(".fadeout").fadeOut(2000, function(){
$(".heading").text("Click on the Start button when you're ready");
});
$(".hidden").attr("hidden", false);
});
function start(){
//init game timer
var Timer = setInterval(function(){
document.getElementById("time1").innerHTML = t;
--t;
if(t < 0){
clearInterval(Timer);
document.getElementById("timeout").innerHTML = "Time's Up |";
$("div.frame").attr("hidden",true);
}
},1000);
var x = Math.floor(Math.random()*500)+150;
var y = Math.floor(Math.random()*500)+150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function(event){
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
points(xco, yco);
})
$("div.frame").mouseout(function(event){
document.getElementById("display1").innerHTML = " ";
document.getElementById("display2").innerHTML = " ";
})
//Generating Co-ordinates
function generate(){
x = Math.floor(Math.random()*500) + 150;
y = Math.floor(Math.random()*500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
}
function points(xco, yco){
if(x == xco && y == yco){
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
}
$("button.start").click(function(event){
event.preventDefault();
start();
$(this).fadeOut(1500);
$(this).attr("disabled",true);
$(".afterstart").fadeOut(1500);
});
});
/* Styles go here */
body{
height: 1200px;
background-size: cover;
}
.jumbotron{
margin-top: 250px;
padding: 20px;
height: 350px;
background-size: cover;
background-attachment: fixed;
}
.heading{
font-size: 30px;
margin-top: 100px;
}
.frame{
height: 1000px;
width: 1500px;
border: 10px solid black;
}
ul {
background: #40475A;
padding: 10px;
width: 100%;
}
.stats{
font-size: 30px;
margin-top: 80px;
}
.info{
font-size: 30px;
color:aliceblue;
}
.bold{
font-size: 25px;
color:antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Irritate</title>
</head>
<body>
<div>
<ul class="nav nav-pills pl-5 fixed-top d-flex justify-content-center" style="font-size: 25px">
<li class="nav-item">
<a class="nav-link" data-toggle="pill" id="display1"></a>
</li>
<li class="nav-item">
<a class="nav-link" id="display2"></a>
</li>
</ul>
</div>
<div class="jumbotron fadeout">
<div class="display-3 text-muted d-flex justify-content-center"> Hand-Job </div>
<p class="info"> All you have to do is try to match the co-ordinates that will display on the screen </p>
<p class="bold"><kbd>PS:</kbd>This game will test your patience</p>
<form>
<div class="input-group w-75">
<div class="input-group-prepend">
<span class="input-group-text">Name:</span>
</div>
<input type="text" class="form-control" value="">
<div class="input-group-append">
<button class="btn btn-outline-success play">Let's Play</button>
</div>
</div>
</form>
</div>
<div class="hidden" hidden="true">
<div>
<p class="text-danger heading afterstart"></p>
<button class="btn btn-danger w-25 start">Start</button>
<div class="d-flex d-flex-inline stats">
<p class="ml-3">X Co-ordinate:<span id="demo1" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Y Co-ordinate:<span id="demo2" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Time Left:<span id="time1" class="ml-2"></span> <span> | </span></p>
<p id="timeout" class="ml-3"></p>
<p>Score: <span id="score"></span></p>
</div>
</div>
<div class="frame ml-2">
</div>
<p id="result"></p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
Here is plunker url for the above code https://plnkr.co/edit/7ia7MkMimzlsAxTCWAc9?p=preview
i think its because your count variable is local and only live in if block if you want to have count in other place please declare it as global variable
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
var count = 0;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
...
})

Not displaying sections with javascript calendar

I need to display a calendar on the homepage and have staff add their birthdays to the calendar but it's not displaying the dates, duration and Name section.
Here is the code for the homepage (excluding css files etc.)
<!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap.min.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
<link href="bootstrap-responsive.css" rel="stylesheet" />
<link href="bootstrap-responsive.min.css" rel="stylesheet" />
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap.min.css" rel="stylesheet" />
<script src="bootstrap.js"></script>
<script src="bootstrap.min.js"></script>
<script src="lightbox.js"></script>
<link href="lightbox.css" rel="stylesheet" />
<style>
body {
font-family: Verdana, sans-serif;
margin: 0;
}
* {
box-sizing: border-box;
}
.row > .column {
padding: 0 8px;
}
.row:after {
content: "";
display: table;
clear: both;
}
.column {
float: left;
width: 25%;
}
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
width: 90%;
max-width: 1200px;
}
/* The Close Button */
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.mySlides {
display: none;
}
.cursor {
cursor: pointer
}
/* Next & previous buttons */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
img {
margin-bottom: -4px;
}
.caption-container {
text-align: center;
background-color: black;
padding: 2px 16px;
color: white;
}
.demo {
opacity: 0.6;
}
.active,
.demo:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}
</style>
</head>
<body>
<div id="page">
<nav align="center">
<br /><img src="images/logo.png" /><br /><br />
Home |
Create Meeting |
Join Meeting
</nav>
<div class="clearfix"><br /><br /></div>
<div class="row">
<div class="column">
<img src="images/img1.jpg" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="images/img2.jpg" style="width:100%" onclick="openModal();currentSlide(2)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="images/img3.jpg" style="width:100%" onclick="openModal();currentSlide(3)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="images/img4.jpg" style="width:100%" onclick="openModal();currentSlide(4)" class="hover-shadow cursor">
</div>
<div class="column">
<br /><img src="images/img6.jpg" align="right" style="width:100%" onclick="openModal();currentSlide(5)" class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal-content">
<div class="mySlides">
<div class="numbertext">1 / 5</div>
<img src="images/img1.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">2 / 5</div>
<img src="images/img2.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">3 / 5</div>
<img src="images/img3.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">4 / 5</div>
<img src="images/img4.jpg" style="width:100%">
</div>
<div class="mySlides" align="center">
<div class="numbertext">5 / 5</div>
<br /><br /><img src="images/img6.jpg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
<div class="caption-container">
<p id="caption"></p>
</div>
<div class="column">
<img class="demo cursor" src="images/img1.jpg" style="width:100%" onclick="currentSlide(1)" alt="">
</div>
<div class="column">
<img class="demo cursor" src="images/img2.jpg" style="width:100%" onclick="currentSlide(2)" alt="">
</div>
<div class="column">
<img class="demo cursor" src="images/img3.jpg" style="width:100%" onclick="currentSlide(3)" alt="">
</div>
<div class="column">
<img class="demo cursor" src="images/img4.jpg" style="width:100%" onclick="currentSlide(4)" alt="">
</div>
<div class="column">
<br /><br /><img class="demo cursor" src="images/img6.jpg" style="width:100%" onclick="currentSlide(5)" alt="" align="middle">
</div>
</div>
</div>
<script>
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (n > slides.length) { slideIndex = 1 }
if (n < 1) { slideIndex = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
captionText.innerHTML = dots[slideIndex - 1].alt;
}
</script>
<section align="left">
<img src="images/hdsplitter.png" align="middle" /><br /><br />
<h1 style="color:#0099ff">Welcome to <b>Systeque</b></h1>
<br />
<div class="col-lg-6 col-md-6 col-sm-6">
<div align="left">
<br />
<h3 style="color:#0099ff"><b>Who We Are</b></h3>
<p><b style="color:#0099ff">Systeque</b> was established in 1998 and has grown to be one of South Africa's leading IT Solution and Service Providers. Systeque is based in the Hyde Park, Sandton in Johannesburg. Systeque’s core focus is to provide total solutions to all customers by bringing new and innovative concepts and cost effective ideas to market. Our strengths lie in Infrastructure Architecture, Cloud Computing and Managed Services. Since inception, Systeque has developed in areas that have shown a definite market requirement. With implementations in all business sectors.</p>
<br /><h3 style="color:#0099ff"><b>My role at the Company</b></h3>
<p>As Operations Manager my duties include co-ordination of our technical team to ensure daily operational functions of the business are running, this also entails ensuring the sales function of the business is processing quotations and orders in accordance with client requirements. Client relations being one of my key areas involves consulting with clients on their daily requirements and projects they are running or planning. Other vital areas of my role includes continous research into products, services and technologies that will further streamline our processes and grow our revenue.</p>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<img src="images/img5.jpg" alt="service" width="450" />
<br /><br /><br />
</div>
</section>
<section align="center">
<h1 style="color:#0099ff"><b>Calender</b></h1>
</section>
</div>
And here is the code for the Assignment page
<html>
<head>
<script type ="text/javascript">
var celebration = new Array();
var months = new Array(12);
var times = new Array(9);
var duration = new Array(9);
var attends = new Array();
var mNum, yNum, dNum, smon, sdate, dif, stimes, sdur;
var Cname, Cmonth, Cdate, Ctime, Cduration, Cvenue, Cnum, Crefresh;
function upDate()
{
document.f1.date.length = 0;
var j;
var mSel = document.f1.month.selectedIndex;
mSel = mSel + mNum;
if((mSel>11) && (mSel<=14))
{
mSel = mSel - 12;
}
if((mSel===0) || (mSel==2) || (mSel==4) || (mSel==6) || (mSel==7) || (mSel==9) || (mSel==11))
{
j = 31;
}
else if((mSel==3) || (mSel==5) || (mSel==8) || (mSel==10))
{
j = 30;
}
else if(mSel==1)
{
if((yNum%4)===0)
{
j = 29;
}
else
{
j = 28;
}
}
else
{
alert("Error with system time");
}
for(var i=0; i<j; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
if(document.f1.month.selectedIndex===0)
{
for(i=(dNum-1); i>=0; i--)
{
document.f1.date.options[i] = null;
}
if(document.f1.date.length===0)
{
document.f1.month.options[0].disabled = true;
document.f1.month.selectedIndex = 1;
upDate();
}
}
if(document.f1.month.selectedIndex==3)
{
document.f1.date.length = 0;
var dn = dNum;
if(dn>j)
{
dn = j;
}
for(;i<dn; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
}
capture();
}
function validate()
{
capture();
if(Cname==="")
{
alert("Celebration cannot be created - Name required");
document.f1.n.focus();
}
else if(Cnum==="")
{
alert("Celebration cannot be created - Description required");
document.f1.num.focus();
}
else if(Cvenue==="")
{
alert("Celebration cannot be created - Venue required");
document.f1.ven.focus();
}
else
{
bookCelebration();
}
}
function capture()
{
Cname = document.f1.n.value;
Cnum = document.f1.num.value;
Cmonth = document.f1.month.selectedIndex;
Cmonth = document.f1.month.options[Cmonth].value;
Cmonth = months[Cmonth];
Cdate = document.f1.date.selectedIndex;
Cdate = document.f1.date.options[Cdate].value;
Ctime = document.f1.time.selectedIndex;
Ctime = document.f1.time.options[Ctime].value;
Cduration = document.f1.dur.selectedIndex;
Cduration = document.f1.dur.options[Cduration].value;
Cvenue = document.f1.ven.value;
if(document.f1.refresh.checked === true)
{
Crefresh = "true";
}
else
{
Crefresh = "false";
}
}
function bookMeeting()
{
var index = meetings.length;
meetings[index] = new Array(8);
celebration[index][0] = Cname;
celebration[index][1] = Cnum;
celebration[index][2] = Cmonth;
celebration[index][3] = Cdate;
celebration[index][4] = Ctime;
celebration[index][5] = Cduration;
celebration[index][6] = Cvenue;
celebration[index][7] = Crefresh;
addBooking(index);
}
function addBooking(index)
{
var opt = new Option(Cname, Cnum, Cmonth, Cdate, Ctime, Cduration, Cvenue, Crefresh);
document.f2.nm.options[index] = opt;
alert("Booking successful");
clearInput();
if(celebration.length===0)
{
document.f2.v.disabled = true;
}
else
{
document.f2.v.disabled = false;
}
}
function search()
{
var inp = document.f2.nm.selectedIndex;
var pos;
inp = celebration[inp][0];
for(var i=0; i<celebration.length; i++)
{
if (inp==celebration[i][0])
{
pos = i;
}
}
document.f1.n.value = celebration[pos][0];
document.f1.num.value = celebration[pos][1];
smon = celebration[pos][2];
for (var j=0; j<months.length; j++)
{
if(months[j] == smon)
{
smon = j;
}
}
smon = smon - mNum;
document.f1.month.selectedIndex = smon;
upDate();
sdate = celebration[pos][3];
if (smon===0)
{
dif = sdate - dNum;
dif = dif -1;
}
else
{
dif = sdate - 1;
}
document.f1.date.selectedIndex = dif;
stimes = celebration[pos][4];
for (; j<times.length; j++)
{
if(times[j] == stimes)
{
stimes = j;
}
}
document.f1.time.selectedIndex = stimes;
sdur = celebration[pos][5];
for (; j<duration.length; j++)
{
if(duration[j] == sdur)
{
sdur = j;
}
}
document.f1.dur.selectedIndex = sdur;
document.f1.ven.value = celebration[pos][6];
if(celebration[pos][7]=="true")
{
document.f1.refresh.checked = true;
}
else if(celebration[pos][7]=="false")
{
document.f1.refresh.checked = false;
}
document.f2.join.disabled = false
}
function joinCelebration()
{
var index = attends.length;
attends[index] = new Array(5);
attends[index][0] = window.prompt("Enter first name");
attends[index][1] = window.prompt("Enter surname");
attends[index][2] = window.prompt("Enter email address");
attends[index][3] = window.prompt("Enter office number");
attends[index][4] = window.prompt("Enter celebration name");
var x = document.f2.nm.selectedIndex;
attends[index][4] = document.f2.nm.options[x].value;
y = attends[index][4];
var nat = 0;
for(var a=0; a<attends.length;a++)
{
if(attends[a][4] = y)
{
nat = nat +1;
}
}
document.f3.atnd.value = nat;
var g = celebration[index][5];
var drt;
for (var h=0; h<duration.length; h++)
{
if(duration[h] == g)
{
drt = h;
}
}
if(drt < 2)
{
document.f3.sgref.value = "Tea & Biscuits";
}
else if(drt < 4)
{
document.f3.sgref.value = "Finger Lunch";
}
else
{
document.f3.sgref.value = "Sit down Lunch";
}
clearInput();
}
function popMonths()
{
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
}
function popDuration()
{
duration[0] = "30 mins";
duration[1] = "1 hour";
duration[2] = "2 hours";
duration[3] = "3 hours";
duration[4] = "4 hours";
duration[5] = "5 hours";
duration[6] = "6 hours";
duration[7] = "7 hours";
duration[8] = "8 hours";
}
function curDate()
{
var now = new Date();
mNum = now.getMonth();
yNum = now.getFullYear();
dNum = now.getDate();
}
function updateMonth()
{
var opt1 = new Option(months[mNum], mNum, false, false);
document.f1.month.options[0] = opt1;
var opt2 = new Option(months[mNum + 1], mNum + 1, false, false);
document.f1.month.options[1] = opt2;
var opt3 = new Option(months[mNum + 2], mNum + 2, false, false);
document.f1.month.options[2] = opt3;
var opt4 = new Option(months[mNum + 3], mNum + 3, false, false);
document.f1.month.options[3] = opt4;
}
function upDate()
{
document.f1.date.length = 0;
var j;
var mSel = document.f1.month.selectedIndex;
mSel = mSel + mNum;
if((mSel>11) && (mSel<=14))
{
mSel = mSel - 12;
}
if((mSel===0) || (mSel==2) || (mSel==4) || (mSel==6) || (mSel==7) || (mSel==9) || (mSel==11))
{
j = 31;
}
else if((mSel==3) || (mSel==5) || (mSel==8) || (mSel==10))
{
j = 30;
}
else if(mSel==1)
{
if((yNum%4)===0)
{
j = 29;
}
else
{
j = 28;
}
}
else
{
alert("Error with system time");
}
for(var i=0; i<j; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
if(document.f1.month.selectedIndex===0)
{
for(i=(dNum-1); i>=0; i--)
{
document.f1.date.options[i] = null;
}
if(document.f1.date.length===0)
{
document.f1.month.options[0].disabled = true;
document.f1.month.selectedIndex = 1;
upDate();
}
}
if(document.f1.month.selectedIndex==3)
{
document.f1.date.length = 0;
var dn = dNum;
if(dn>j)
{
dn = j;
}
for(; i<dn; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
}
capture();
}
function popTimes()
{
times[0] = "8:00am";
times[1] = "9:00am";
times[2] = "10:00am";
times[3] = "11:00am";
times[4] = "12:00pm";
times[5] = "1:00pm";
times[6] = "2:00pm";
times[7] = "3:00pm";
times[8] = "4:00pm";
}
function upTimes()
{
for(var i=0; i<times.length; i++)
{
var opt = new Option(times[i]);
document.f1.time.options[i] = opt;
}
}
function upDur()
{
for(var i=0; i<duration.length; i++)
{
var opt = new Option(duration[i]);
document.f1.dur.options[i] = opt;
}
}
function clearInput()
{
initialize();
document.f1.n.value = "";
document.f1.num.value = "";
document.f1.ven.value = "";
document.f1.refresh.checked = false;
}
function initialize()
{
popMonths();
popTimes();
curDate();
popDuration();
updateMonth();
upDate();
upTimes();
upDur();
document.f1.n.focus();
if(celebration.length===0)
{
document.f2.v.disabled = true;
}
else
{
document.f2.v.disabled = false;
}
}
</script>
</head>
<body onload = "initialize()">
<form name = "f1">
<h1> Create a celebration </h1>
<table border = "0" cellpadding = "5">
<tr>
<td>
Birthday of
<input type = "text" name = "n"/>
</td>
</tr>
<tr>
<td>
Birthday Message
<input type = "text" name = "num" onchange = "capture()"/>
</td>
</tr>
<tr>
<td>
Date: Month
<select name = "month" onchange = "upDate()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
<td>
Date
<select name = "date" onchange = "capture()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
</tr>
<tr>
<td>
Time
<select name = "time" onchange = "capture()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
<td>
Duration
<select name = "dur" onchange = "capture()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
</tr>
<tr>
<td>
Venue
<input type = "text" name = "ven" onchange = "capture()"/>
</td>
<td>
Refreshments
<input type = "checkbox" name = "refresh" onchange = "capture()" onclick = "capture()"/>
</td>
</tr>
<tr>
<td align = "center">
<input type = "button" value = "Create" onclick = "validate()"/>
</td>
<td align = "right">
<input type = "button" name = "del" value = "Delete" disabled = "true" onclick = "deleteBooking()"/>
<input type = "button" value = "Clear" onclick = "clearInput()"/>
</td>
</tr>
</table>
</form>
<form name = "f2">
<h1> Sign-up for celebration </h1>
<table border = "0" cellpadding = "5">
<tr>
<td>
Name
<select name = "nm"/>
<option value = "0">
None
</option>
</select>
</td>
</tr>
<tr>
<td align = "center">
<input type = "button" value = "Search" name = "v"onclick = "search()"/>
</td>
<td align = "center">
<input type = "button" name = "join" value = "Join" disabled = "true"/ onclick = "joinCelebration()">
</td>
</tr>
</table>
</form>
<form name = "f3">
<h1>Celebration details</h1>
<table border = "0" cellpadding = "5">
<tr>
<td>
Number of attendees
<input type = "text" name = "atnd"/>
</td>
</tr>
<tr>
<td>
Suggested refreshments
<input type = "text" name = "sgref"/>
</td>
</tr>
</table>
</form>
</body>
</html>
When you click on any dropdown it says "nothing" instead of the options.
this probably because you are missing the jquery file. jquery is a must when you used bootstrap. have you check the Starter template here: http://getbootstrap.com/docs/4.1/getting-started/introduction/
Found the solution - the reason the dropdowns were not showing the options from the JavaScript code was because testing against 0 needs to have ===.
if((mSel===0) || (mSel==2) || (mSel==4) || (mSel==6) || (mSel==7) || (mSel==9) || (mSel==11))
{
Now however the calander does not show on the home page. The assignment page needs to be a page to create birthday celebrations for staff members and the home page must have calendar showing links to celebrations that have already been created.
That is the main thing so it needs capture and show it.

Get the color range of a rating bar [duplicate]

This question already has answers here:
Calculate color HEX having 2 colors and percent/position
(4 answers)
Closed 5 years ago.
I want to create a simple HTML rating bar. My rating bar got has a dynamic number of containers. For example 5:
And I need to calculate the color values [first+2,last-1]. The first and last colors are given.
$(document).ready(function() {
ratingElements = $(".ratingEle"); // Find all rating containers
ratingColors.push(initialColorDefault); // if not selected, set the container to gray // index 0
ratingColors.push(initialColorMin); // red color // index 1
// !! Calculate the missing colors here !!
// from index 2 to ratingColors.length - 1
// ratingColors.push("#" + hexValue);
updateRatingBar(0); // set all containers to gray
$(ratingElements).each(function(index, element) { // add some event handlers to the containers
var ele = $(element);
var i = index + 1;
ele.click(function() {
setRating(i);
});
ele.hover(function() {
updateRatingBar(i);
});
});
});
var ratingElements;
var ratingColors = [];
var initialColorDefault = "#cccccc"; // pre set colors
var initialColorMin = "#ff0000";
var initialColorMax = "#80ff00";
function setRating(currentValue) { // click handler
$("#ratingOutput").html(currentValue + " / " + ratingElements.length);
updateRatingBar(currentValue);
}
function updateRatingBar(currentValue) { // set colors
$(ratingElements).each(function(index, element) {
var i = index;
if (i > currentValue) {
i = 0;
}
$(element).css('background-color', ratingColors[i]);
});
}
.ratingEle {
float: left;
cursor: pointer;
height: 10px;
width: 30px;
margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rating">
<div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
</div>
<div>
<p id="ratingOutput"></p>
</div>
</div>
So as you can see, I need to calculate the colors to make it work. I set a missing part in my JS file and need help, calculating it.
I don't know if I should go for hex or rgb values.
When hovering over the containers the colors should get updated automatically. When clicking a container, it should set a value.
But I already archieved this I just need to calculate the missing color range.
With this answer as base
$(function() {
var color1 = 'ff0000';
var color2 = '80ff00';
var ratio = 1 / $('.ratingEle').length;
var hex = function(x) {
x = x.toString(16);
return (x.length == 1) ? '0' + x : x;
};
$i=1;
$('.ratingEle').each(function() {
var r = Math.ceil(parseInt(color1.substring(0,2), 16) * (ratio*$i) + parseInt(color2.substring(0,2), 16) * (1-(ratio*$i)));
var g = Math.ceil(parseInt(color1.substring(2,4), 16) * (ratio*$i) + parseInt(color2.substring(2,4), 16) * (1-(ratio*$i)));
var b = Math.ceil(parseInt(color1.substring(4,6), 16) * (ratio*$i) + parseInt(color2.substring(4,6), 16) * (1-(ratio*$i)));
var color = hex(r) + hex(g) + hex(b);
$(this).css('background-color', '#'+color);
$i++;
});
});
.ratingEle {
float: left;
cursor: pointer;
height: 10px;
width: 30px;
margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rating">
<div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
</div>
<div>
<p id="ratingOutput"></p>
</div>
</div>
with more elements
$(function() {
var color1 = 'ff0000';
var color2 = '80ff00';
var ratio = 1 / $('.ratingEle').length;
var hex = function(x) {
x = x.toString(16);
return (x.length == 1) ? '0' + x : x;
};
$i=1;
$('.ratingEle').each(function() {
var r = Math.ceil(parseInt(color1.substring(0,2), 16) * (ratio*$i) + parseInt(color2.substring(0,2), 16) * (1-(ratio*$i)));
var g = Math.ceil(parseInt(color1.substring(2,4), 16) * (ratio*$i) + parseInt(color2.substring(2,4), 16) * (1-(ratio*$i)));
var b = Math.ceil(parseInt(color1.substring(4,6), 16) * (ratio*$i) + parseInt(color2.substring(4,6), 16) * (1-(ratio*$i)));
var color = hex(r) + hex(g) + hex(b);
$(this).css('background-color', '#'+color);
$i++;
});
});
.ratingEle {
float: left;
cursor: pointer;
height: 10px;
width: 30px;
margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rating">
<div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
<div class="ratingEle"></div>
</div>
<div>
<p id="ratingOutput"></p>
</div>
</div>

Fill a circle over time

I am doing a project where I created a countdown timer using JavaScript. It features stop-, start-, and reset buttons.
I want to create a fill effect animation starting from the bottom, based on the countdown timer. I want the fill effect to fill a certain percentage of the circle so that when the countdown reaches 0, the whole circle will be filled.
I want to use vanilla JavaScript. No jQuery or SVG.
Here is my code so far for the basic timer starting with HTML, then CSS and my Javascript code.
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<h1>Pomodoro Clock</h1>
<div class="container">
<div class="row">
<h3>Session Length</h3>
<div class="row button1">
<button type="button" onclick="decreaseTime()">-</button>
<span id="SessionLength">25</span>
<button type="button" onclick="increaseTime()">+</button>
</div>
</div>
<!--My Start/Stop/Reset buttons-->
<div class="row">
<div class="myButtons">
<button type="button" onclick="startTime()">Start</button>
<button type="button" onclick="stopTime()">Stop</button>
<button type="button" onclick="resetTime()">Reset</button>
</div>
</div>
<!--My Circle-->
<div class="row">
<div class="circleDraw">
<h2 class="text-center">Session</h2>
<h1 id="output">25:00</h1>
</div>
</div>
</div>
h1{
text-align: center;
}
h3{
text-align: right;
padding-right: 30%;
}
.myButtons{
text-align: center;
padding-top: 10%;
}
.circleDraw{
border-radius: 50%;
border: 2px solid;
width: 300px;
height: 300px;
margin: 50px auto;
}
.text-center{
text-align: center;
padding: 30px;
}
.txt-center{
text-align: center;
}
.button1{
text-align: right;
padding-right: 35%
}
var time = 1500;
var running = 0;
var myStopID;
var startTime = function(){
running = 1;
if(running == 1){
timer();
}
}
var stopTime = function(){
clearTimeout(myStopID);
running = 0;
}
var resetTime = function(){
if(running == 0){
time = 1500;
}
var min = Math.floor(time / 60);
var sec = time % 60;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
document.getElementById('output').innerHTML= min;
document.getElementById('SessionLength').innerHTML= min;
}
var timer = function(){
if(running == 1){
myStopID = setTimeout(function(){
time--;
var min = Math.floor(time / 60);
var sec = time % 60;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
document.getElementById("output").innerHTML= min + ":" + sec;
timer();
}, 1000);
}
}
function decreaseTime(){
if(time <= 0){
return 0;
}
time = time - 60;
var min = Math.floor(time/60);
document.getElementById('SessionLength').innerHTML= min;
document.getElementById('output').innerHTML= min;
}
function increaseTime(){
if(time >= 5940){
return 5940;
}
time = time + 60;
var min = Math.floor(time/60);
document.getElementById('SessionLength').innerHTML= min;
document.getElementById('output').innerHTML= min;
}
What you have done so far looks good. I'd look at using the canvas element and the arc() method on that to draw the circle and partial fill.
More info here...
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
And basic Canvas and SVG example for drawing a circle in this answer...
https://stackoverflow.com/a/6936351/4322803

drag & drop functionality in ibooks app of ipad

I want to use drag & drop functionality for ibooks app of ipad using Javascript. Attached is the code that i have used in file, though it is working on browser but am not able to see it in ipad. It would be great if someone will help me with the same.
dfgdf
<style type="text/css" xml:space="preserve">
/* DEMO CSS */
body{
width:100%;
margin:0px;
padding:0px;
font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; /* Font to use */
}
#heading{
height:100px;
}
/* END DEMO CSS */
#dragScriptContainer{ /* BIG div containing HTML needed for the entire script */
width:400px;
margin:0 auto;
border:1px solid #000;
height:400px;
margin-top:20px;
padding:3px;
-moz-user-select:no;
}
#questionDiv{ /* Big div for all the questions */
float:left;
height:100%;
width:100px;
border:1px solid #000;
padding:2px;
}
#answerDiv{ /* Big div for all the answers */
float:right;
height:100%;
width:50px;
border:1px solid #000;
padding:2px;
}
#questionDiv div,#answerDiv div,#dragContent div{ /* General rules for small divs - i.e. specific questions and answers */
width:45px;
height:20px;
line-height:20px;
float:left;
margin-right:2px;
margin-bottom:2px;
text-align:center;
}
#dragContent div{ /* Drag content div - i.e. specific answers when they are beeing dragged */
border:1px solid #000;
}
#answerDiv .dragDropSmallBox{ /* Small answer divs */
border:1px solid #000;
cursor:pointer;
}
#questionDiv .dragDropSmallBox{ /* Small answer divs */
border:1px solid #000;
cursor:pointer;
background-color:#E2EBED; /* Light blue background color */
}
#questionDiv div div{ /* div after it has been dragged from right to left box */
margin:0px;
border:0px;
padding:0px;
background-color:#FFF;
}
#questionDiv .destinationBox{ /* Small empty boxes for the questions - i.e. where answers could be dragged */
border:0px;
background-color:#DDD;
width:47px;
height:22px;
}
#questionDiv .correctAnswer{ /* CSS indicating correct answer */
background-color:green;
color:#fff;
border:1px solid #000;
}
#questionDiv .wrongAnswer{ /* CSS indicating wrong answer */
background-color:red;
color:#fff;
border:1px solid #000;
}
#dragContent div{
background-color:#FFF;
}
#questionDiv .dragContentOver{ /* Mouse over question boxes - i.e. indicating where dragged element will be appended if mouse button is relased */
border:1px solid #F00;
}
#answerDiv.dragContentOver{ /* Mouse over answer box - i.e. indicating where dragged element will be appended if mouse button is relased */
border:1px solid #F00;
}
/* NEVER CHANGE THIS */
#dragContent{
position:absolute;
display:none;
}
</style>
<script type="text/javascript">
//<![CDATA[
/************************************************************************************************************
(C) www.dhtmlgoodies.com, November 2005
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
Thank you!
www.dhtmlgoodies.com
Alf Magne Kalleland
************************************************************************************************************/
var shuffleQuestions = true; /* Shuffle questions ? */
var shuffleAnswers = true; /* Shuffle answers ? */
var lockedAfterDrag = false; /* Lock items after they have been dragged, i.e. the user get's only one shot for the correct answer */
function quizIsFinished()
{
// This function is called when everything is solved
}
/* Don't change anything below here */
var dragContentDiv = false;
var dragContent = false;
var dragSource = false;
var dragDropTimer = -1;
var destinationObjArray = new Array();
var destination = false;
var dragSourceParent = false;
var dragSourceNextSibling = false;
var answerDiv;
var questionDiv;
var sourceObjectArray = new Array();
var arrayOfEmptyBoxes = new Array();
var arrayOfAnswers = new Array();
function getTopPos(inputObj)
{
if(!inputObj || !inputObj.offsetTop)return 0;
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue;
}
function getLeftPos(inputObj)
{
if(!inputObj || !inputObj.offsetLeft)return 0;
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
function cancelEvent()
{
return false;
}
function initDragDrop(e)
{
if(document.all)e = event;
if(lockedAfterDrag && this.parentNode.parentNode.id=='questionDiv')return;
dragContentDiv.style.left = e.clientX + Math.max(document.documentElement.scrollLeft,document.body.scrollLeft) + 'px';
dragContentDiv.style.top = e.clientY + Math.max(document.documentElement.scrollTop,document.body.scrollTop) + 'px';
dragSource = this;
dragSourceParent = this.parentNode;
dragSourceNextSibling = false;
if(this.nextSibling)dragSourceNextSibling = this.nextSibling;
if(!dragSourceNextSibling.tagName)dragSourceNextSibling = dragSourceNextSibling.nextSibling;
dragDropTimer=0;
timeoutBeforeDrag();
return false;
}
function timeoutBeforeDrag(){
if(dragDropTimer>=0 && dragDropTimer<10){
dragDropTimer = dragDropTimer +1;
setTimeout('timeoutBeforeDrag()',10);
return;
}
if(dragDropTimer>=10){
dragContentDiv.style.display='block';
dragContentDiv.innerHTML = '';
dragContentDiv.appendChild(dragSource);
}
}
function dragDropMove(e)
{
if(dragDropTimer<10){
return;
}
if(document.all)e = event;
var scrollTop = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
dragContentDiv.style.left = e.clientX + scrollLeft + 'px';
dragContentDiv.style.top = e.clientY + scrollTop + 'px';
var dragWidth = dragSource.offsetWidth;
var dragHeight = dragSource.offsetHeight;
var objFound = false;
var mouseX = e.clientX + scrollLeft;
var mouseY = e.clientY + scrollTop;
destination = false;
for(var no=0;no<destinationObjArray.length;no++){
var left = destinationObjArray[no]['left'];
var top = destinationObjArray[no]['top'];
var width = destinationObjArray[no]['width'];
var height = destinationObjArray[no]['height'];
destinationObjArray[no]['obj'].className = 'destinationBox';
var subs = destinationObjArray[no]['obj'].getElementsByTagName('div');
if(!objFound && subs.length==0){
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destinationObjArray[no]['obj'].className='dragContentOver';
destination = destinationObjArray[no]['obj'];
objFound = true;
}
}
}
sourceObjectArray['obj'].className='';
if(!objFound){
var left = sourceObjectArray['left'];
var top = sourceObjectArray['top'];
var width = sourceObjectArray['width'];
var height = sourceObjectArray['height'];
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destination = sourceObjectArray['obj'];
sourceObjectArray['obj'].className='dragContentOver';
}
}
return false;
}
function dragDropEnd()
{
if(dragDropTimer<10){
dragDropTimer = -1;
return;
}
dragContentDiv.style.display='none';
sourceObjectArray['obj'].style.backgroundColor = '#FFF';
if(destination){
destination.appendChild(dragSource);
destination.className='destinationBox';
// Check if position is correct, i.e. correct answer to the question
if(!destination.id || destination.id!='answerDiv'){
var previousEl = dragSource.parentNode.previousSibling;
if(!previousEl.tagName)previousEl = previousEl.previousSibling;
var numericId = previousEl.id.replace(/[^0-9]/g,'');
var numericIdSource = dragSource.id.replace(/[^0-9]/g,'');
if(numericId==numericIdSource){
dragSource.className='correctAnswer';
checkAllAnswers();
}
else
dragSource.className='wrongAnswer';
}
if(destination.id && destination.id=='answerDiv'){
dragSource.className='dragDropSmallBox';
}
}else{
if(dragSourceNextSibling)
dragSourceNextSibling.parentNode.insertBefore(dragSource,dragSourceNextSibling);
else
dragSourceParent.appendChild(dragSource);
}
dragDropTimer = -1;
dragSourceNextSibling = false;
dragSourceParent = false;
destination = false;
}
function checkAllAnswers()
{
for(var no=0;no<arrayOfEmptyBoxes.length;no++){
var sub = arrayOfEmptyBoxes[no].getElementsByTagName('div');
if(sub.length==0)return;
if(sub[0].className!='correctAnswer'){
return;
}
}
quizIsFinished();
}
function resetPositions()
{
if(dragDropTimer>=10)return;
for(var no=0;no<destinationObjArray.length;no++){
if(destinationObjArray[no]['obj']){
destinationObjArray[no]['left'] = getLeftPos(destinationObjArray[no]['obj'])
destinationObjArray[no]['top'] = getTopPos(destinationObjArray[no]['obj'])
}
}
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
}
function initDragDropScript()
{
dragContentDiv = document.getElementById('dragContent');
answerDiv = document.getElementById('answerDiv');
answerDiv.onselectstart = cancelEvent;
var divs = answerDiv.getElementsByTagName('div');
var answers = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='dragDropSmallBox'){
divs[no].onmousedown = initDragDrop;
answers[answers.length] = divs[no];
arrayOfAnswers[arrayOfAnswers.length] = divs[no];
}
}
if(shuffleAnswers){
for(var no=0;no<(answers.length*10);no++){
var randomIndex = Math.floor(Math.random() * answers.length);
answerDiv.appendChild(answers[randomIndex]);
}
}
sourceObjectArray['obj'] = answerDiv;
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
sourceObjectArray['width'] = answerDiv.offsetWidth;
sourceObjectArray['height'] = answerDiv.offsetHeight;
questionDiv = document.getElementById('questionDiv');
questionDiv.onselectstart = cancelEvent;
var divs = questionDiv.getElementsByTagName('div');
var questions = new Array();
var questionsOpenBoxes = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='destinationBox'){
var index = destinationObjArray.length;
destinationObjArray[index] = new Array();
destinationObjArray[index]['obj'] = divs[no];
destinationObjArray[index]['left'] = getLeftPos(divs[no])
destinationObjArray[index]['top'] = getTopPos(divs[no])
destinationObjArray[index]['width'] = divs[no].offsetWidth;
destinationObjArray[index]['height'] = divs[no].offsetHeight;
questionsOpenBoxes[questionsOpenBoxes.length] = divs[no];
arrayOfEmptyBoxes[arrayOfEmptyBoxes.length] = divs[no];
}
if(divs[no].className=='dragDropSmallBox'){
questions[questions.length] = divs[no];
}
}
if(shuffleQuestions){
for(var no=0;no<(questions.length*10);no++){
var randomIndex = Math.floor(Math.random() * questions.length);
questionDiv.appendChild(questions[randomIndex]);
questionDiv.appendChild(questionsOpenBoxes[randomIndex]);
destinationObjArray[destinationObjArray.length] = destinationObjArray[randomIndex];
destinationObjArray.splice(randomIndex,1);
questionsOpenBoxes[questionsOpenBoxes.length] = questionsOpenBoxes[randomIndex];
questionsOpenBoxes.splice(randomIndex,1);
questions[questions.length] = questions[randomIndex];
questions.splice(randomIndex,1);
}
}
questionDiv.style.visibility = 'visible';
answerDiv.style.visibility = 'visible';
document.documentElement.onmouseup = dragDropEnd;
document.documentElement.onmousemove = dragDropMove;
setTimeout('resetPositions()',150);
window.onresize = resetPositions;
}
/* Reset the form */
function dragDropResetForm()
{
for(var no=0;no<arrayOfAnswers.length;no++){
arrayOfAnswers[no].className='dragDropSmallBox'
answerDiv.appendChild(arrayOfAnswers[no]);
}
}
window.onload = initDragDropScript;
//]]>
</script>
</head>
<body>
<div id="dragScriptContainer">
<div id="questionDiv">
<div class="dragDropSmallBox" id="q1">
5x1
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q2">
5x2
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q3">
5x3
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q4">
5x4
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q5">
5x5
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q6">
5x6
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q7">
5x7
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q8">
5x8
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q9">
5x9
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q10">
5x10
</div>
<div class="destinationBox"></div>
</div>
<div id="answerDiv">
<div class="dragDropSmallBox" id="a1">
5
</div>
<div class="dragDropSmallBox" id="a2">
10
</div>
<div class="dragDropSmallBox" id="a3">
15
</div>
<div class="dragDropSmallBox" id="a4">
20
</div>
<div class="dragDropSmallBox" id="a5">
25
</div>
<div class="dragDropSmallBox" id="a6">
30
</div>
<div class="dragDropSmallBox" id="a7">
35
</div>
<div class="dragDropSmallBox" id="a8">
40
</div>
<div class="dragDropSmallBox" id="a9">
45
</div>
<div class="dragDropSmallBox" id="a10">
50
</div>
</div>
</div>
<div id="dragContent"></div>
<input type="button" onclick="dragDropResetForm();return false"
value="Reset" />
</body>
</html>

Categories