-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
56 lines (48 loc) · 1.32 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Exercise 2: Color picker */
var color_list=[];
$(document).ready(function() {
window.addEventListener("keydown", keydownHandler, false);
function keydownHandler(event) {
if(event.keyCode === 13) {
var color = $("input#color").val();
setPreview(color);
}
}
$(document).on('click', '#add-to-favorite', function() {
var color = $("input#color").val();
addBox(color);
});
});
function setPreview(color) {
$(".preview").css('background-color', color);
}
function addBox(color) {
var isEqual = false;
if (color_list.length === 0) {
var content = "<div class='item' style='background-color:" + color + ";'></div>";
$("#colors").prepend(content);
$("#color").val("");
setPreview("white");
color_list.push(color);
}
else if($(".item").length<16) {
for(var i = 0; i < color_list.length; i++) {
if(color_list[i] === color) {
isEqual = true;
}
}
if(!isEqual) {
var content = "<div class='item' style='background-color:" + color + ";'></div>";
$("#colors").prepend(content);
$("#color").val("");
setPreview("white");
color_list.push(color);
}
else {
console.log("The color has already been added to your favourite list");
}
}
else {
console.log("The maximum number of favourite colors is 16");
}
}