I'm making a lottery random number generator and have it working, all I want to do is change the background colour of the ball varying on what number range its called between. The second block of code is what I have come up with so far.
For example
o 1-9: White
o 10-19: Blue
o 20-29: Ping,
o 30-39: Green,
o 40-49: Yellow
<!DOCTYPE html>
<head>
<!-- meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>NRONLINE - Buckinghamshire Web Design, Digital Marketing Workshops and Kofax Consultancy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
body {
background: #444;
font-family: sans-serif;
font-size: 18px;
font-weight: 100;
}
ul {
position: absolute;
padding: 0;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
list-style-type: none;
width: 690px;
height: 100px;
}
ul li {
float: left;
width: 100px;
height: 100px;
border-radius: 50px;
margin-right: 10px;
color: white;
text-align: center;
line-height: 100px;
font-size: 36px;
}
ul li:nth-child(5n) {
margin-right: 40px;
}
.ball-placeholder {
background: #222222;
background: -moz-linear-gradient(-45deg, #222222 0%, black 100%);
background: -webkit-gradient(linear, left top, right bottom, color-stop(0%, #222222), color-stop(100%, black));
background: -webkit-linear-gradient(-45deg, #222222 0%, black 100%);
background: -o-linear-gradient(-45deg, #222222 0%, black 100%);
background: -ms-linear-gradient(-45deg, #222222 0%, black 100%);
background: linear-gradient(135deg, #222222 0%, black 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222222', endColorstr='#000000',GradientType=1 );
}
.next-ball, .play-again {
position: absolute;
right: 0;
left: 0;
margin: auto;
border: 0;
color: white;
}
.next-ball {
bottom: 20px;
width: 100px;
height: 40px;
font-size: 16px;
background: #7ac9ed;
}
.play-again {
display: none;
bottom: 20px;
width: 200px;
height: 80px;
font-size: 24px;
background: #d74d2f;
}
.white-ball {
background: #fff;
color:#101010;
}
.blue-ball {
background: #99ccff;
color:#101010;
}
.pink-ball {
background: #ffccff;
color:#101010;
}
.green-ball {
background: #00cc66;
color:#101010;
}
.yellow-ball {
background: #fac600;
color:#101010;
}
</style>
</head>
<body role="document">
<ul class="ball-placeholders">
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
</ul>
<ul class="lottery"></ul>
<button class="next-ball">Next Ball</button>
<button class="play-again">Play Again!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var arr = new Array();
$('.next-ball').on('click', function(){
//generate random number between 1 and 50
var random = Math.floor(Math.random()*50 ) + 1;
// array to store css class references
var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];
console.log(random);
//if index of random number is less than 50
if( arr.indexOf(random) == -1){
//generate random number
arr.push(random);
//add css class to lottery-ball class relevant to array value range
$('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
}
// if the number already exists ignore and generate a new number
else {
console.log(random);
}
console.log(arr);
//if lottery number calls is greater than 5 then switch button classes and send an alert to the user
if ( $('.lottery').children().length > 5 ) {
$('.next-ball').hide();
$('.play-again').show();
alert('Did You Win?');
}
});
//If once the game is finished the user chooses to play again switch button classes
$('.play-again').on('click', function(){
$('.lottery').children().remove();
arr = [];
$('.next-ball').show();
$('.play-again').hide();
});
</script>
</body>
</html>
Your idea should work, but since the only thing that changes is the class of the li it could be more compact. Here I've stored the class names in an array, and used the first digit of the ball number - Math.floor(random/10) to find the right element. Also your indexOf line had a bug - a return of zero from indexOf means the element was found at the start of the array, so check for -1.
var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];
if( arr.indexOf(random) == -1){
arr.push(random);
$('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
}
Another alternative could be CSS attribute selectors. We could use the 'starts with' selector ^, which will target all elements whose attribute in question... well, starts with a particular string.
Say we give each li representing a ball a data-* attribute equal to its number. Then we can style their backgrounds like so:
li[data-number^=0] {
/*target numbers less than 10
Need to append 0 in front of numbers <10
for this to work*/
background: white;
}
li[data-number^=1] {
/*target numbers in the teens*/
background: blue;
}
li[data-number^=2] {
/*target numbers in the twenties*/
background:pink;
}
/*...and so on...*/
Then the JS is somewhat simplified to:
if (arr.indexOf(random) == -1) {
arr.push(random);
$('.lottery').append('<li class="lottery-ball" data-number="' + (random < 10 ? '0' : '') + random + '">' + random + '</li>';
}
EDIT: here's a link for other types of attribute selectors.
Related
I would like to be able to add an item to the list, and view it when I reload the page. I am not sure how to go about doing this. I do not need it stored in a database or anything, I would just like it to be there on screen until I manually delete the list item. Is this possible?
I believe this would be kept on sharepoint, and used with multiple users adding and editing the content, but when I get to that step, I may need additional help with that as well, if that makes any difference to the current question of keeping the LI information.
$("ul").on("click", "li", function(){
$(this).toggleClass("completed");
});
$("ul").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text']").keypress(function(event){
if(event.which === 13){
var name = $('#name').val();
$('#name').val("");
var number = $('#number').val();
$('#number').val("");
var exception = $('#exception').val();
$('#exception').val("");
var date = $('#date').val();
$('#date').val("");
$("ul").append("<li><span><i class='fa fa-trash'></i></span> " + name + " | " + number + " | " + exception + " | " + date + "</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text']").fadeToggle();
});
body {
font-family: Roboto;
background: -webkit-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* Chrome 10+, Saf5.1+ */
background: -moz-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* FF3.6+ */
background: -ms-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* IE10 */
background: -o-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* Opera 11.10+ */
background: linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* W3C */
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 20px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
.fa-plus {
float: right;
}
li {
background: #fff;
height: 40px;
line-height: 40px;
color: #666;
}
li:nth-child(2n){
background: #f7f7f7;
}
span {
background: #e74c3c;
height: 40px;
margin-right: 20px;
text-align: center;
color: white;
width: 0;
display: inline-block;
transition: 0.2s linear;
opacity: 0;
}
li:hover span {
width: 40px;
opacity: 1.0;
}
input {
font-size: 18px;
color: #2980b9;
background-color: #f7f7f7;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
}
input:focus{
background: #fff;
border: 3px solid #2980b9;
outline: none;
}
#container {
width: 360px;
margin: 100px auto;
background: #f7f7f7;
box-shadow: 0 0 3px rgba(0,0,0, 0.1);
}
.completed {
color: gray;
text-decoration: line-through;
}
<!DOCTYPE html>
<html>
<head>
<title>Exceptions</title>
<link rel="stylesheet" type="text/css" href="assets/css/todos.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700,500' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css">
<script type="text/javascript" src="assets/js/lib/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="container">
<h1>2223A Exceptions <i class="fa fa-plus"></i></h1>
<input id="name" type="text" placeholder="Employee Name:">
<input id="number" type="text" placeholder="Employee Number:">
<input id="exception" type="text" placeholder="Employee Exception:">
<input id="date" type="text" placeholder="Employee Date:">
<ul>
<li><span><i class="fa fa-trash"></i></span> #303974 | R. Roberts | SN | 6/25 - 6/27</li>
<li><span><i class="fa fa-trash"></i></span> #303354 | B. Smith | SN | 6/15 & 6/27</li>
<li><span><i class="fa fa-trash"></i></span> #328937 | K. Stull | NO | 6/26</li>
</ul>
</div>
<script type="text/javascript" src="assets/js/todos.js"></script>
</body>
</html>
Well written question.
Change
$("ul").append("<li><span><i class='fa fa-trash'></i></span> " + name + " | " + number + " | " + exception + " | " + date + "</li>")
To
let li = "<li><span><i class='fa fa-trash'></i></span> " + name + " | " + number + " | " + exception + " | " + date + "</li>";
localStorage.setItem('li', localStorage.getItem('li') + li);
$("ul").append(li);
localStorage is an API that allows you to store data in the browser. All I have done here is stored the li as part of a concatenated string of lis. Then place the new li on the page the way you did before.
Now, your next task is the retrieve the lis from localStorage upon page load. So something like this will work:
// assuming document.ready
let lis = localStorage.getItem('li');
$("ul").append(lis);
That should get you very close.
EDIT: I've modified your jsFiddle to accomplish this goal (adding a new item). You can find it here: https://jsfiddle.net/tsbm02hd/
U can indeed use localstorage or you can use JavaScript Cookie manager for this.
Only downside is that the user has some control since he would bve able to clear his browser and therefor his localstorage and/or Cookies...
I still believe for things like this it is best to use an API call and save this data on the server side....
I have a bar graph created in JavaScript to display values using colors. I am having trouble resetting the bar graph. Basically what needs to happen is when the "reset" button is clicked, all bars clear values and reset to "0". Then the button needs to give the option to "Generate" and the previous values are shown again. Also, this is my first time using constant velocity to ease the bars up and down as the button is clicked to give it a little flair. Not sure what I am missing to have the data clear and be set to zero on the bottom line of the graph while using constant velocity to make it ease down and when button is clicked to restore the values to previous state. Any help is appreciated. Here is the code so far:
HTML
/*
* Some base values.
*/
var millisecondsPerFrame = 30;
/*
* Helper function for managing button event handlers.
*/
var setupButton = function(button, label, onclickHandler) {
button.value = label;
button.onclick = onclickHandler;
button.disabled = false;
};
var startConstantVelocityAnimation = function() {
// Grab the desired velocity.
var velocity = parseFloat(document.getElementById("chart").value);
// Grab the object to animate, and initialize if necessary.
var colors = document.getElementById("colors");
chart.style.bottom = chart.style.bottom || "0px";
// Start animating.
var intervalID = setInterval(function() {
var newBottom = parseInt(box.style.bottom) + velocity;
if ((newBottom < 0) || (newBottom > maxBottom)) {
velocity = -velocity;
} else {
chart.style.bottom = newBottom + "px";
}
}, millisecondsPerFrame);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"), "Reset", function() {
clearInterval(intervalID);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"),
"Generate", startConstantVelocityAnimation);
});
};
window.onload = function() {
// Set up the initial event handlers.
document.getElementById("Reset").onclick = startConstantVelocityAnimation;
};
**
* Graph JS Code ** *
function createBarChart(data) {
// Start with the container.
var chart = document.createElement("div");
// The container must have position: relative.
chart.style.position = "relative";
// The chart's height is the value of its largest
// data item plus a little margin.
var height = 0;
for (var i = 0; i < data.length; i += 1) {
height = Math.max(height, data[i].value);
}
chart.style.height = (height + 10) + "px";
// Give the chart a bottom border.
chart.style.borderBottomStyle = "solid";
chart.style.borderBottomWidth = "1px";
// Iterate through the data.
var barPosition = 0;
// We have a preset bar width for the purposes of this
// example. A full-blown chart module would make this
// customizable.
var barWidth = 48.30;
for (i = 0; i < data.length; i += 1) {
// Basic column setup.
var dataItem = data[i];
var bar = document.createElement("div");
bar.style.position = "absolute";
bar.style.left = barPosition + "px";
bar.style.width = barWidth + "px";
bar.style.backgroundColor = dataItem.color;
bar.style.height = dataItem.value + "px";
bar.style.borderStyle = "ridge";
bar.style.borderColor = dataItem.color;
// Visual flair with CSS Level 3 (for maximum compatibility
// we set multiple possible properties to the same value).
// Hardcoded values here just for illustration; a
// full module would allow major customizability.
bar.style.MozBoxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.WebkitBoxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.boxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.MozBorderRadiusTopleft = "8px";
bar.style.WebkitBorderTopLeftRadius = "8px";
bar.style.borderTopLeftRadius = "8px";
bar.style.MozBorderRadiusTopright = "8px";
bar.style.WebkitBorderTopRightRadius = "8px";
bar.style.borderTopRightRadius = "8px";
bar.style.backgroundImage =
"-moz-linear-gradient(" + dataItem.color + ", black)";
bar.style.backgroundImage =
"-webkit-gradient(linear, 0% 0%, 0% 100%," +
"color-stop(0, " + dataItem.color + "), color-stop(1, black))";
bar.style.backgroundImage =
"linear-gradient(" + dataItem.color + ", black)";
// Recall that positioning properties are treated *relative*
// to the corresponding sides of the containing element.
bar.style.bottom = "-1px";
chart.appendChild(bar);
// Move to the next bar. We provide an entire bar's
// width as space between columns.
barPosition += (barWidth * 2);
}
return chart;
};
window.onload = function() {
var colors = [{
color: "red",
value: 40
},
{
color: "blue",
value: 10
},
{
color: "green",
value: 100
},
{
color: "black",
value: 65
},
{
color: "yellow",
value: 75
},
{
color: "purple",
value: 120
},
{
color: "grey",
value: 121
},
{
color: "orange",
value: 175
},
{
color: "olive",
value: 220
},
{
color: "maroon",
value: 275
},
{
color: "brown",
value: 300
},
{
color: "teal",
value: 15
}
];
var chart = createBarChart(colors);
document.querySelector("#wrapper").appendChild(chart); // keeps chart inside wrapper div
};
#wrapper {
margin-left: auto;
margin-right: auto;
width: 85%;
border: groove;
border-color: white;
padding: 2px;
}
#loginwrap {
margin-left: auto;
margin-right: auto;
padding: 3px;
text-align: center;
}
body {
font-family: Georgia;
padding: 10px;
background: #f1f1f1;
font-weight: bold;
}
/* top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* three columns next to each other */
.column1 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #aaa;
}
.column2 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #bbb;
}
.column3 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #aaa;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Card-like background for each section */
.card {
background-color: white;
padding: 30px;
margin-top: 20px;
overflow: auto;
}
/* Align about section image to right */
.aboutimg {
float: right;
}
/* Footer */
.footer {
padding: 20px;
background: #ddd;
margin-top: 20px;
}
.copyright {
margin-right: auto;
margin-left: auto;
width: 85%;
text-align: center;
font-size: 10px;
padding: 5px;
}
/*Chart Color Legend*/
.legend .legend-scale ul {
margin: 0;
padding: 0;
float: left;
list-style: none;
}
.legend .legend-scale ul li {
display: block;
float: left;
width: 50px;
margin-bottom: 6px;
text-align: center;
font-size: 80%;
list-style: none;
}
.legend ul.legend-labels li span {
display: block;
float: left;
height: 15px;
width: 50px;
}
.legend a {
color: #777;
}
.subs {
font-size: 10px;
font-style: italic;
padding: 5px;
text-align: center;
}
.reset-button {
text-align: right;
padding-top: 2px;
padding-right: 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tissue: Titan Issue Tracking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Issue Tracking System" />
<meta name="author" content="S Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
<script src="js/animation.js"></script>
</head>
<body>
<div id="wrapper">
<h2>TISSUE: Sales Subscription Dashboard</h2>
<div class="topnav">
Home
Tracker Login
</div>
<div>
<div class="legend">
<div class="legend-scale">
<div class="reset-button">
<input type="button" value="Reset Graph" id="Reset">
</div>
<ul class="legend-labels">
<li><span></span>40</li>
<li><span></span>10</li>
<li><span></span>100</li>
<li><span></span>65</li>
<li><span></span>75</li>
<li><span></span>120</li>
<li><span></span>121</li>
<li><span></span>175</li>
<li><span></span>220</li>
<li><span></span>275</li>
<li><span></span>300</li>
<li><span></span>15</li>
</ul>
</div>
</div>
<div class="legend">
<div class="legend-scale">
<ul class="legend-labels">
<li><span style='background:red;'></span>Jan</li>
<li><span style='background:blue;'></span>Feb</li>
<li><span style='background:green;'></span>March</li>
<li><span style='background:black;'></span>Apr</li>
<li><span style='background:yellow;'></span>May</li>
<li><span style='background:purple;'></span>June</li>
<li><span style='background:grey;'></span>July</li>
<li><span style='background:orange;'></span>Aug</li>
<li><span style='background:olive;'></span>Sept</li>
<li><span style='background:maroon;'></span>Oct</li>
<li><span style='background:brown;'></span>Nov</li>
<li><span style='background:teal;'></span>Dec</li>
</ul>
</div>
</div>
<br><br><br><br>
<hr>
<div class="subs">***Subscribers in Thousands***</div>
<script src="js/subscriptions_graph.js"></script>
</div>
</div>
<div class="copyright">
Copyright © 2018 Titan Issue Tracker
</div>
</body>
</html>
I couldnt find any answers on stack overflow to this specific question. I am trying to use pure javascript ONLY, so please no jquery answers.
So I posted all of my code as a general reference but my problem I believe lies in the javascript section. My question is, how can I make it so that my div "signup" is unclickable right AFTER it is clicked ONCE?
I tried putting a disable statement before frame and fadeOut are called inside the HideLogin() function. I also tried with css pointer-events. Nothing works and everytime I click SignUp, the animations repeat. Thank you in advance for the help.
function HideLogin() {
var login = document.getElementById("login");
var SignUpSheet = document.getElementById("SignUpSheet");
var titlecard = document.getElementById("titlecard");
var signup = document.getElementById("signup");
SignUpSheet.style.display = "block";
titlecard.style.display = "block";
frame(signup);
fadeOut(login);
/*fadeIn(document.getElementById("SignUpSheet"));
fadeIn(document.getElementById("titlecard")); */
}
function frame(signup) {
var pos = 125;
var id = setInterval(function() {
if (pos == 0) {
clearInterval(id);
} else {
pos--;
signup.style.top = pos + 'px';
}
}, 1);
}
function fadeOut(element) {
var op = 1; // initial opacity
var timer = setInterval(function() {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 20);
}
function fadeIn(element) {
var op = 0.1; // initial opacity
var timer = setInterval(function() {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.display = "block";
op += 0.1;
}, 20);
}
body,
html {
min-height: 100%;
}
body
/* Background handeling*/
{
color: white;
background: url(images/Hunter.jpg) center no-repeat;
background-size: cover;
background-color: #444;
}
/*------------------------------------------------------------- */
#logBox
/*Div that holds two links */
{
position: relative;
//border: 2px solid white;
height: 300px;
width: 300px;
margin-left: 70px;
margin-top: 50px;
}
#login
/* login link */
{
position: absolute;
cursor: pointer;
display: block;
//border: 2px solid white;
background: -webkit-linear-gradient(red, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-family: papyrus;
font-size: 70px;
color: red;
text-shadow: 2px 2px black;
transition: text-shadow 0.5s ease;
}
#login:hover {
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 4px 4px black;
}
#signup
/* sign up link */
{
position: absolute;
cursor: pointer;
display: block;
//border: 2px solid white;
background: -webkit-linear-gradient(red, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
top: 125px;
font-family: papyrus;
font-size: 70px;
color: red;
text-shadow: 2px 2px black;
transition: text-shadow 0.5s ease;
}
#signup:hover {
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 4px 4px black;
}
/*--------------------------------------------------------------- */
/* Div that holds two sheets */
#LogInSheet {
display: none;
}
#LoginTitle {}
#SignUpSheet {
display: none;
}
#SignUpTitle {}
/*--------------------------------------------------------------- */
#titlecard
/*title display */
{
position: absolute;
display: none;
bottom: 0px;
right: 50px;
//border: 2px solid white;
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 45px;
color: gray;
text-align: center;
font-family: papyrus;
text-shadow: 2px 2px black;
}
<!doctype html>
<html>
<head>
<title>The Prime Legion</title>
<link rel="stylesheet" type="text/css" href="page1.css">
<script type="text/javascript" src="page1.js"></script>
</head>
<body>
<div id="logBox">
<div id="login" onclick="HideSignin()">
Log In
</div>
<div id="signup" onclick="HideLogin()">
Sign Up
</div>
</div>
<div id="LogInSheet">
<div id="LoginTitle">
<p>
<h4>Hello</h4>
</p>
</div>
</div>
<div id="SignUpSheet">
<div id="SignupTitle">
<p>
<h4>Welcome</h4>
</p>
</div>
</div>
<div id="titlecard">
<p>
<h1>The Prime Legion</h1>
</p>
</div>
</body>
</html>
Unless you have a particular need to use <div>s for your buttons, you could change the HTML to use <button> elements instead. That way you could disable it using the disabled attribute and it should prevent any further clicks without having to store and track any additional JavaScript variables.
<button id="signup" onclick="HideLogin()">Sign Up</button>
function HideLogin() {
document.getElementById("signup").disabled = true;
...
}
I would suggest the following:
define a global variable loginCliked=false
then in your HideLogin function:
HideLogin = function(){
if(!loginClicked){
loginClicked=true;
// Do everything else
}
}
So that with the first click it will set loginClicked to true. If you click the button for the second time it does nothing
Can someone please tell me why my fluid box isn't working for my photo. I've followed all of the instructions to create the code for the fluidbox, but my photo doesn't show up on the webpage. But when you click on where it is supposed to be on the webpage, it takes you to another page that has my photo in it. Here is my codes:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootswatch: Cosmo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./bootstrap.css" media="screen">
<link rel="stylesheet" href="bootstrap-lightbox.css">
<link rel="stylesheet" href="portfoliostyle.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../bower_components/html5shiv/dist/html5shiv.js"></script>
<script src="../bower_components/respond/dest/respond.min.js"></script>
<![endif]-->
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-23019901-1']);
_gaq.push(['_setDomainName', "bootswatch.com"]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script src="jquery.js"></script>
<script src="imagelightbox.js"></script>
<script>
$( function()
{
$( 'a' ).imageLightbox();
});
</script>
</head>
<body>
<ul class="navigation">
<li class="nav-item">Home</li>
<li class="nav-item">Portfolio</li>
<li class="nav-item">About</li>
<li class="nav-item">Blog</li>
<li class="nav-item">Contact</li>
</ul>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger"></label>
<div class="site-wrap">
<div class="gallery">
<a class="space" href="images/spacetime.jpg" title="A Space in Time" data-fluidbox>
<img src="images/spacetime.jpg" />
</a>
<a href="images/spacetime.jpg" data-fluidbox>
<div class="fluidbox-wrap">
<img src="images/spacetime.jpg" />
<div class="fluidbox-ghost"></div>
</div>
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
$(function () {
// Global variables
var $fb = $('a[data-fluidbox');
vpRatio; // To store viewport aspect ratio
// Add class to all Fluidboxes
$fb.addClass('fluidbox');
// Create fluidbox modal background
$('body').append('<div id="fluidbox-overlay"></div>');
// Functions:
// 1. to close any opened Fluidbox
// 2. to position Fluidbox dynamically
var closeFb = function (){
$('a[data-fluidbox].fluidbox-opened').trigger('click');
},
positionFb = function ($activeFb){
// Get elements
var $img = $activeFb.find('img'),
$ghost = $activeFb.find('.fluidbox-ghost');
// Calculate offset and scale
var offsetY = $(window).scrollTop()-$img.offset().top+0.5*($img.data('imgHeight')*($img.data('imgScale')-1))+0.5*($(window).height()-$img.data('imgHeight')*$img.data('imgScale')),
offsetX = 0.5*($img.data('imgWidth')*($img.data('imgScale')-1))+0.5*($(window).width()- $img.data('imgWidth')*$img.data('imgScale')) - $img.offset().left,
scale = $img.data('imgScale');
// Animate wrapped elements
// Parse integers:
// 1. Offsets can be integers
// 2. Scale is rounded to nearest 2 decimal places
$ghost.css({ 'transform': 'translate('+parseInt(offsetX*10)/10+'px,'+parseInt(offsetY*10)/10+'px) scale('+parseInt(scale*1000)/1000+')' });
}
// The following events will force FB to close
// ... when the opqaue overlay is clicked upon
$('#fluidbox-bg').click(closeFb);
})();
$fb.imagesLoaded().done(function (){
$fb
.wrapInner('<div class="fluidbox-wrap" />')
.find('img')
.css({ opacity: 1 })
.after('<div class="fluidbox-ghost" />');
// Listen to resize event for calculations
$(window).resize(function (){
// Get viewport aspect ratio (#1)
vpRatio = $(window).width() / $(window).height();
// Get dimensions and aspect ratios
$fb.each(function (){
var $img = $(this).find('img'),
$ghost = $(this).find('.fluidbox-ghost'),
$wrap = $(this).find('.fluidbox-wrap'),
data = $img.data();
// Save image dimensions as jQuery object (#2)
data.imgWidth = $img.width();
data.imgHeight = $img.height();
data.imgRatio = $img.width() / $img.height();
// Resize ghost element (#3)
$ghost.css({
width: $img.width(),
height: $img.height(),
top: $img.offset().top - $wrap.offset().top,
left: $img.offset().left - $wrap.offset().left
});
// Calculate scale based on orientation (#4)
if(vpRatio > data.imgRatio) {
data.imgScale = $(window).height()*.95 / $img.height();
} else {
data.imgScale = $(window).width()*.95 / $img.width();
}
});
}).resize();
// Bind click event
$fb.click(function (e){
// Variables
var $img = $(this).find('img'),
$ghost = $(this).find('.fluidbox-ghost'),
$wrap = $(this).find('.fluidbox-wrap');
if($(this).data('fluidbox-state') == 0 || !$(this).data('fluidbox-state')) {
// State: Closed
// Action: Open Fluidbox
$(this)
.data('fluidbox-state', 1)
.removeClass('fluidbox-closed')
.addClass('fluidbox-opened');
// Show overlay
$('#fluidbox-overlay').fadeIn();
// Set thumbnail image source as background image first.
// We also show the ghost element
$ghost.css({
'background-image': 'url('+$img.attr('src')+')',
opacity: 1
});
// Hide original image
$img.css({ opacity: 0 });
// Preload ghost image
var ghostImg = new Image();
ghostImg.onload = function (){ $ghost.css({ 'background-image': 'url('+$activeFb.attr('href')+')' } ); };
ghostImg.src = $(this).attr('href');
// Position Fluidbox
positionFb($(this));
} else {
// State: Opened
// Action: Close Fluidbox
/// Switch state
$(this)
.data('fluidbox-state', 0)
.removeClass('fluidbox-opened')
.addClass('fluidbox-closed');
// Hide overlay
$('#fluidbox-overlay').fadeOut();
// Show original image
$img.css({ opacity: 1 });
// Hide ghost image
$ghost.css({ opacity: 0 });
// Reverse animation on wrapped elements
$ghost
.css({ 'transform': 'translate(0,0) scale(1)' })
.one('webkitTransitionEnd MSTransitionEnd oTransitionEnd transitionend', function (){
// Wait for transntion to run its course first
$ghost.css({ opacity: 0 });
});
}
});
</script>
CSS:
/* Navigation Menu - Background */
.navigation {
/* critical sizing and position styles */
width: 100%;
height: 100%;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 0;
/* non-critical appearance styles */
list-style: none;
background: #111;
}
/* Navigation Menu - List items */
.nav-item {
/* non-critical appearance styles */
width: 200px;
border-top: 1px solid #111;
border-bottom: 1px solid #000;
}
.nav-item a {
/* non-critical appearance styles */
display: block;
padding: 1em;
background: linear-gradient(135deg, rgba(0,0,0,0) 0%,rgba(0,0,0,0.65) 100%);
color: white;
font-size: 1.2em;
text-decoration: none;
transition: color 0.2s, background 0.5s;
}
.nav-item a:hover {
color: #c74438;
background: linear-gradient(135deg, rgba(0,0,0,0) 0%,rgba(75,20,20,0.65) 100%);
}
.site-wrap {
min-width: 100%;
min-height: 100%;
background-color: #fff;
position: absolute;
top: 0;
bottom: 100%;
left: 0;
z-index: 1;
padding: 4em;
background-image: linear-gradient(135deg,
rgb(254,255,255) 0%,
rgb(221,241,249) 35%,
rgb(160,216,239) 100%);
background-size: 200%;
}
.name {
position: absolute;
top: 60%;
right:40%;
}
h3{
text-align: center;
top: 65%;
}
/* Nav Trigger */
.nav-trigger {
/* critical styles - hide the checkbox input */
position: absolute;
clip: rect(0, 0, 0, 0);
}
label[for="nav-trigger"] {
/* critical positioning styles */
position: fixed;
left: 15px; top: 15px;
z-index: 2;
/* non-critical apperance styles */
height: 30px;
width: 30px;
cursor: pointer;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' x='0px' y='0px' width='30px' height='30px' viewBox='0 0 30 30' enable-background='new 0 0 30 30' xml:space='preserve'><rect width='30' height='6'/> <rect y='24' width='30' height='6'/><rect y='12' width='30' height='6'/></svg>");
background-size: contain;
}
/* Make the Magic Happen */
.nav-trigger + label, .site-wrap {
transition: left 0.2s;
}
.nav-trigger:checked + label {
left: 215px;
}
.nav-trigger:checked ~ .site-wrap {
left: 200px;
box-shadow: 0 0 5px 5px rgba(0,0,0,0.5);
}
body {
/* Without this, the body has excess horizontal scroll when the menu is open */
overflow-x: hidden;
}
/* Additional non-critical styles */
h1, h3, p {
max-width: 600px;
margin: 0 auto 1em;
}
code {
padding: 2px;
background: #ddd;
}
/* Micro reset */
*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border- box;margin:0;padding:0;}
html, body { height: 100%; width: 100%; font-family: Helvetica, Arial, sans-serif; }
/* Image Lightbox Galley */
a[data-fluidbox] {
background-color: #eee;
border: none;
cursor: -webkit-zoom-in;
cursor: -moz-zoom-in;
margin-bottom: 1.5rem;
}
a[data-fluidbox].fluidbox-opened {
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out;
}
a[class^='float'] {
margin: 1rem;
margin-top: 0;
width: 33.33333%;
}
a.float-left {
float: left;
margin-left: 0;
}
a.float-right {
float: right;
margin-right: 0;
}
a[data-fluidbox] img {
display: block;
margin: 0 auto;
opacity: 0;
max-width: 100%;
transition: all .25s ease-in-out;
}
#fluidbox-overlay {
background-color: rgba(255,255,255,.85);
cursor: pointer;
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out;
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 500;
}
.fluidbox-wrap {
background-position: center center;
background-size: cover;
margin: 0 auto;
position: relative;
z-index: 400;
transition: all .25s ease-in-out;
}
.fluidbox-opened .fluidbox-wrap {
z-index: 600;
}
.fluidbox-ghost {
background-size: cover;
background-position: center center;
position: absolute;
transition: all .25s ease-in-out;
}
.space img{
height: 25%;
width: 50%
}
My question is: I have a list of colors that jquery uses to select a random color for the box divs in my HTML. If you click on the "Random me" button, everything works and random colors are picked for each square. However, I want to make sure that adjacent squares don't get the same color (i.e. Square 1 color = black, Square 2 color = red,
Square 3 color = yellow, Square 4 color = purple). I want each Square to have its own unique color that is selected from a pool of say, 20 colors. So I don't want red, red, yellow, purple or red, yellow, red, purple, etc.
Below is all my code (HTML with CSS added as a style element in the head) and (jQuery added at the bottom of the page just before the closing body tag).
You guys are awesome. Thanks in advance for all your help. Jason
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Square Test</title>
<!-- CSS styles -->
<style>
.nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
.ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
.sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
.se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
div {
-webkit-box-sixing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#question {
position: absolute;
top: 44%;
left: 37%;
bottom: 50%;
color: red;
width: 30%;
height: 5%;
background-color: #fff;
border: 3px solid black;
text-align: center;
font-size: 24px;
border-radius: 30px;
}
#square1 {
position: absolute;
top: 20%;
left: 20%;
color: #fff;
font-weight: bold;
font-size: 24px;
}
#square2 {
position: absolute;
top: 20%;
left: 70%;
color: #fff;
font-weight: bold;
font-size: 24px;
}
#square3 {
position: absolute;
top: 70%;
left: 20%;
color: #fff;
font-weight: bold;
font-size: 24px;
}
#square4 {
position: absolute;
top: 70%;
left: 70%;
color: #fff;
font-weight: bold;
font-size: 24px;
}
</style>
</head>
<body>
<!-- the divs that the jQuery acts on -->
<div onclick="change_color(1)" id="div_color_1" class="nw change_color" style="background-color: rgb(224, 216, 200);">
</div>
<div onclick="change_color(2)" id="div_color_2" class="ne change_color" style="background-color: rgb(94, 198, 49);">
</div>
<div onclick="change_color(3)" id="div_color_3" class="sw change_color" style="background-color: rgb(84, 51, 38);">
</div>
<div onclick="change_color(4)" id="div_color_4" class="se change_color" style="background-color: rgb(169, 215, 220);">
</div>
<!-- Random me button that selects a random color for each square -->
<input id="question" type="button" onclick="colorfy_me()" value="Random me">
<!-- the squares -->
<p id="square1">Square 1</p>
<p id="square2">>Square 2</p>
<p id="square3">>Square 3</p>
<p id="square4">>Square 4</p>
<!-- jQuery scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var myColors = [
'#7F8C8D', '#95A5A6', '#BDC3C7', '#003946', '#BDC3C7',
'#ECF0F1', '#BDC3C7', '#ECF0F1', '#C0392B', '#E74C3C',
'#D35400', '#E67E22', '#F39C12', '#F1C40F', '#22313f',
'#2C3E50', '#34495E', '#8E44AD', '#9B59B6', '#2980B9',
'#3498DB', '#27AE60', '#2ECC71', '#16A085'
];
$(function(){
$.each(myColors, function(i, v){
$('#div_color' + (+i + 1)).css('background-color', v);
})
})
function colorfy_me() {
var colors = {};
$.each(myColors, function(i, v){
colors[i] = 0;
})
$('div.change_color').each(function() {
var color = Math.floor(Math.random() * myColors.length);
$(this).css('background-color', myColors[color]);
colors[color] = colors[color] + 1;
});
$.each(colors, function(i, v){
$('#div_color' + (+i + 1)).html(colors[i])
});
}
</script>
</body>
</html>
This version of color_me implements the algorithm alexmac is trying to describe. It removes each color from the copy as it goes so that the shrinking color array contains only unused colors.
colorfy_me = function() {
var colors = myColors.slice(0)
$('div.change_color').each(function() {
// find a random color that's not already used.
var color = Math.floor(Math.random() * colors.length);
$(this).css('background-color', colors[color]);
$(this).html( colors[color] )
colors = colors.slice(0,color-1).concat(
colors.slice(color+1,colors.length-1) )
});
$.each(colors, function(i, v){
$('#div_color_' + (+i + 1)).html(colors[i])
});
}
there were a few other issues with your code, so I did have to make a few changes. See working example on http://jsfiddle.net/cQB38/1/
Defining only colors that are unique, that's trickier. One option is to break your colors into 4 sets of similar colors, and then pull one random color from each of the 4 sets. I think it's probably possible to determine how dissimilar two colors are, based on comparing the differences between and sums of their individual red, green, and blue components, but that sounds complicated.
assign myColors to a temp array and get color for background-color from temp array then remove the color from temp array using splice method
change your colorfy_me() like following and try
function colorfy_me() {
var colors = {};
$.each(myColors, function(i, v){
colors[i] = 0;
})
testColor=myColors;
$('div.change_color').each(function() {
var color = Math.floor(Math.random() * myColors.length);
$(this).css('background-color', testColor[color]);
testColor.splice(color,1);
colors[color] = colors[color] + 1;
});
$.each(colors, function(i, v){
$('#div_color' + (+i + 1)).html(colors[i])
});
}