I am using Chart.js to construct pie chart, is there any way to concatenate the Count to the label (Displaying numbers and percentages in a pie chart legend)?
createChart : function() {
debugger;
var chartData = [60, 90, 120, 150];
var chartLabels = ['apples','bananas','oranges','pears'];
var chartCanvas = component.find("chart").getElement();
var chart = new Chart(chartCanvas, {
type: 'pie',
data: {
labels: chartLabels,
datasets: [
{
label: "test",
data: chartData,
borderWidth: 0,
backgroundColor: [
"#f43004",
"#decf3f",
"#FFA500"
]
}
]
},
options: {
cutoutPercentage: 1,
maintainAspectRatio: false,
legend: {
display: true,
position:'right',
fullWidth:false,
reverse:true,
labels: {
fontColor: '#000',
fontSize:10,
fontFamily:"Arial, sans-serif SANS_SERIF"
},
layout: {
padding: 70,
}
}
}
});
}
I am trying to construct chart like this:
Please provide any suggestions or pointers to achieve this.
Thank you in advance.
You can use html-legends feature so you can customize the Chart.js legend:
legendCallback : function (chart) {
var text = [];
text.push('<ul class="0-legend">');
var ds = chart.data.datasets[0];
var sum = ds.data.reduce(function add(a, b) {
return a + b;
}, 0);
for (var i = 0; i < ds.data.length; i++) {
text.push('<li>');
var perc = Math.round(100 * ds.data[i] / sum, 0);
text.push('<span style="background-color:' + ds.backgroundColor[i] + '">' + '</span>' + chart.data.labels[i] + ' (' + ds.data[i] + ') (' + perc + '%)');
text.push('</li>');
}
text.push('</ul>');
return text.join("");
}
Here is a fiddle: https://jsfiddle.net/beaver71/b5hdn9gw/
var ctx = document.getElementById("myChart").getContext('2d');
var chartData = [60, 90, 120, 150];
var chartLabels = ['apples','bananas','oranges','pears'];
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: chartLabels,
datasets: [{
backgroundColor: [
"#f43004",
"#decf3f",
"#FFA500",
"#9b59b6",
],
data: chartData
}]
},
options: {
legend: {
display: false
},
legendCallback: function(chart) {
var text = [];
text.push('<ul class="0-legend">');
var ds = chart.data.datasets[0];
var sum = ds.data.reduce(function add(a, b) { return a + b; }, 0);
for (var i=0; i<ds.data.length; i++) {
text.push('<li>');
var perc = Math.round(100*ds.data[i]/sum,0);
text.push('<span style="background-color:' + ds.backgroundColor[i] + '">' + '</span>' + chart.data.labels[i] + ' ('+ds.data[i]+') ('+perc+'%)');
text.push('</li>');
}
text.push('</ul>');
return text.join("");
}
}
});
var myLegendContainer = document.getElementById("legend");
// generate HTML legend
myLegendContainer.innerHTML = chart.generateLegend();
// bind onClick event to all LI-tags of the legend
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i += 1) {
legendItems[i].addEventListener("click", legendClickCallback, false);
}
function legendClickCallback(event) {
event = event || window.event;
var target = event.target || event.srcElement;
while (target.nodeName !== 'LI') {
target = target.parentElement;
}
var parent = target.parentElement;
var chartId = parseInt(parent.classList[0].split("-")[0], 10);
var chart = Chart.instances[chartId];
var index = Array.prototype.slice.call(parent.children).indexOf(target);
var meta = chart.getDatasetMeta(0);
console.log(index);
var item = meta.data[index];
if (item.hidden === null || item.hidden === false) {
item.hidden = true;
target.classList.add('hidden');
} else {
target.classList.remove('hidden');
item.hidden = null;
}
chart.update();
}
body {
font-family: 'Arial';
}
.container {
margin: 15px auto;
}
#chart {
float: left;
width: 70%;
}
#legend {
float: right;
}
[class$="-legend"] {
list-style: none;
cursor: pointer;
padding-left: 0;
}
[class$="-legend"] li {
display: block;
padding: 0 5px;
}
[class$="-legend"] li.hidden {
text-decoration: line-through;
}
[class$="-legend"] li span {
border-radius: 5px;
display: inline-block;
height: 10px;
margin-right: 10px;
width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<div class="container">
<h2>Chart.js — Pie Chart Demo Percent</h2>
<div>
<div id="chart"><canvas id="myChart"></canvas></div>
<div id="legend"></div>
</div>
</div>
var ctx = document.getElementById("myChart").getContext('2d');
var chartData = [60, 90, 120, 150];
var chartLabels = ['apples','bananas','oranges','pears'];
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: chartLabels,
datasets: [{
backgroundColor: [
"#f43004",
"#decf3f",
"#FFA500",
"#9b59b6",
],
data: chartData
}]
},
options: {
legend: {
display: false
},
legendCallback: function(chart) {
var text = [];
text.push('<ul class="0-legend">');
var ds = chart.data.datasets[0];
var sum = ds.data.reduce(function add(a, b) { return a + b; }, 0);
for (var i=0; i<ds.data.length; i++) {
text.push('<li>');
var perc = Math.round(100*ds.data[i]/sum,0);
text.push('<span style="background-color:' + ds.backgroundColor[i] + '">' + '</span>' + chart.data.labels[i] + ' ('+ds.data[i]+') ('+perc+'%)');
text.push('</li>');
}
text.push('</ul>');
return text.join("");
}
}
});
var myLegendContainer = document.getElementById("legend");
// generate HTML legend
myLegendContainer.innerHTML = chart.generateLegend();
// bind onClick event to all LI-tags of the legend
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i += 1) {
legendItems[i].addEventListener("click", legendClickCallback, false);
}
function legendClickCallback(event) {
event = event || window.event;
var target = event.target || event.srcElement;
while (target.nodeName !== 'LI') {
target = target.parentElement;
}
var parent = target.parentElement;
var chartId = parseInt(parent.classList[0].split("-")[0], 10);
var chart = Chart.instances[chartId];
var index = Array.prototype.slice.call(parent.children).indexOf(target);
var meta = chart.getDatasetMeta(0);
console.log(index);
var item = meta.data[index];
if (item.hidden === null || item.hidden === false) {
item.hidden = true;
target.classList.add('hidden');
} else {
target.classList.remove('hidden');
item.hidden = null;
}
chart.update();
}
body {
font-family: 'Arial';
}
.container {
margin: 15px auto;
}
#chart {
float: left;
width: 70%;
}
#legend {
float: right;
}
[class$="-legend"] {
list-style: none;
cursor: pointer;
padding-left: 0;
}
[class$="-legend"] li {
display: block;
padding: 0 5px;
}
[class$="-legend"] li.hidden {
text-decoration: line-through;
}
[class$="-legend"] li span {
border-radius: 5px;
display: inline-block;
height: 10px;
margin-right: 10px;
width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<div class="container">
<h2>Chart.js — Pie Chart Demo Percent</h2>
<div>
<div id="chart"><canvas id="myChart"></canvas></div>
<div id="legend"></div>
</div>
</div>
Related
How to change div border-color by input value?
My Code
<div id=divx"> </div>
<button onClick=""> </button>
<script>
function myFunction() {
var color = document.getElemntByID("inpx").value;
document.getElementById("divx").style.borderColor = color;
}
</script>
Don't use on* inline JS handlers/attributes. Use Element.addEventListener(). JS should in in one place only, and that's either your JavaScript tag or file.
getElemntByID should be getElementById
Use input type="color"
Create a reusable setBorderColor(Element, color) function:
const EL = (sel, EL) => (EL||document).querySelector(sel);
const setBorderColor = (el, color) => el.style.borderColor = color;
const EL_inpx = EL("#inpx");
const EL_divx = EL("#divx");
EL_inpx.addEventListener("input", () => {
setBorderColor(EL_divx, EL_inpx.value);
});
setBorderColor(EL_divx, EL_inpx.value);
#divx {border: 10px solid transparent;}
<input id="inpx" type="color" value="#ff0088">
<div id="divx">test</div>
try this: run
function myFunction() {
const color = document.getElementById("inpx").value;
document
.getElementById("divx")
.setAttribute("style", "background-color:" + color);
}
// colors source: https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json
const colors = {
"aliceblue": "#f0f8ff",
"antiquewhite": "#faebd7",
"aqua": "#00ffff",
"aquamarine": "#7fffd4",
"azure": "#f0ffff",
"beige": "#f5f5dc",
"bisque": "#ffe4c4",
"black": "#000000",
"blanchedalmond": "#ffebcd",
"blue": "#0000ff",
"blueviolet": "#8a2be2",
"brown": "#a52a2a",
"burlywood": "#deb887",
"cadetblue": "#5f9ea0",
"chartreuse": "#7fff00",
"chocolate": "#d2691e",
"coral": "#ff7f50",
"cornflowerblue": "#6495ed",
"cornsilk": "#fff8dc",
"crimson": "#dc143c",
"cyan": "#00ffff",
"darkblue": "#00008b",
"darkcyan": "#008b8b",
"darkgoldenrod": "#b8860b",
"darkgray": "#a9a9a9",
"darkgreen": "#006400",
"darkgrey": "#a9a9a9",
"darkkhaki": "#bdb76b",
"darkmagenta": "#8b008b",
"darkolivegreen": "#556b2f",
"darkorange": "#ff8c00",
"darkorchid": "#9932cc",
"darkred": "#8b0000",
"darksalmon": "#e9967a",
"darkseagreen": "#8fbc8f",
"darkslateblue": "#483d8b",
"darkslategray": "#2f4f4f",
"darkslategrey": "#2f4f4f",
"darkturquoise": "#00ced1",
"darkviolet": "#9400d3",
"deeppink": "#ff1493",
"deepskyblue": "#00bfff",
"dimgray": "#696969",
"dimgrey": "#696969",
"dodgerblue": "#1e90ff",
"firebrick": "#b22222",
"floralwhite": "#fffaf0",
"forestgreen": "#228b22",
"fuchsia": "#ff00ff",
"gainsboro": "#dcdcdc",
"ghostwhite": "#f8f8ff",
"goldenrod": "#daa520",
"gold": "#ffd700",
"gray": "#808080",
"green": "#008000",
"greenyellow": "#adff2f",
"grey": "#808080",
"honeydew": "#f0fff0",
"hotpink": "#ff69b4",
"indianred": "#cd5c5c",
"indigo": "#4b0082",
"ivory": "#fffff0",
"khaki": "#f0e68c",
"lavenderblush": "#fff0f5",
"lavender": "#e6e6fa",
"lawngreen": "#7cfc00",
"lemonchiffon": "#fffacd",
"lightblue": "#add8e6",
"lightcoral": "#f08080",
"lightcyan": "#e0ffff",
"lightgoldenrodyellow": "#fafad2",
"lightgray": "#d3d3d3",
"lightgreen": "#90ee90",
"lightgrey": "#d3d3d3",
"lightpink": "#ffb6c1",
"lightsalmon": "#ffa07a",
"lightseagreen": "#20b2aa",
"lightskyblue": "#87cefa",
"lightslategray": "#778899",
"lightslategrey": "#778899",
"lightsteelblue": "#b0c4de",
"lightyellow": "#ffffe0",
"lime": "#00ff00",
"limegreen": "#32cd32",
"linen": "#faf0e6",
"magenta": "#ff00ff",
"maroon": "#800000",
"mediumaquamarine": "#66cdaa",
"mediumblue": "#0000cd",
"mediumorchid": "#ba55d3",
"mediumpurple": "#9370db",
"mediumseagreen": "#3cb371",
"mediumslateblue": "#7b68ee",
"mediumspringgreen": "#00fa9a",
"mediumturquoise": "#48d1cc",
"mediumvioletred": "#c71585",
"midnightblue": "#191970",
"mintcream": "#f5fffa",
"mistyrose": "#ffe4e1",
"moccasin": "#ffe4b5",
"navajowhite": "#ffdead",
"navy": "#000080",
"oldlace": "#fdf5e6",
"olive": "#808000",
"olivedrab": "#6b8e23",
"orange": "#ffa500",
"orangered": "#ff4500",
"orchid": "#da70d6",
"palegoldenrod": "#eee8aa",
"palegreen": "#98fb98",
"paleturquoise": "#afeeee",
"palevioletred": "#db7093",
"papayawhip": "#ffefd5",
"peachpuff": "#ffdab9",
"peru": "#cd853f",
"pink": "#ffc0cb",
"plum": "#dda0dd",
"powderblue": "#b0e0e6",
"purple": "#800080",
"rebeccapurple": "#663399",
"red": "#ff0000",
"rosybrown": "#bc8f8f",
"royalblue": "#4169e1",
"saddlebrown": "#8b4513",
"salmon": "#fa8072",
"sandybrown": "#f4a460",
"seagreen": "#2e8b57",
"seashell": "#fff5ee",
"sienna": "#a0522d",
"silver": "#c0c0c0",
"skyblue": "#87ceeb",
"slateblue": "#6a5acd",
"slategray": "#708090",
"slategrey": "#708090",
"snow": "#fffafa",
"springgreen": "#00ff7f",
"steelblue": "#4682b4",
"tan": "#d2b48c",
"teal": "#008080",
"thistle": "#d8bfd8",
"tomato": "#ff6347",
"turquoise": "#40e0d0",
"violet": "#ee82ee",
"wheat": "#f5deb3",
"white": "#ffffff",
"whitesmoke": "#f5f5f5",
"yellow": "#ffff00",
"yellowgreen": "#9acd32"
};
const colorTextInput = document.querySelector("#colorTextInput");
const colorSelector = document.querySelector("#colorSelector");
const updateColorBtn = document.querySelector("#updateColorBtn");
// hexToRgb function source: https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb#answer-5624139
const rgbToHex = (r, g, b) => {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
const getHexColor = (color) => {
if (color.length === 0) {
return null;
}
// regex source: https://www.geeksforgeeks.org/how-to-validate-hexadecimal-color-code-using-regular-expression/
const isHexColor = new RegExp("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$").test(color);
if (isHexColor) {
// Three digit hex to six digit converter
// Source: https://gomakethings.com/converting-a-color-from-a-three-digit-hexcolor-to-a-six-digit-hexcolor-with-vanilla-js/
if (color.length === 4) {
hexColor = color.substr("#".length).split('').map(function (hex) {
return hex + hex;
}).join('');
return "#" + hexColor;
}
return color;
}
else {
if (color.startsWith("rgba(")) {
color = "rgb" + color.substr("rgba".length);
}
if (color.startsWith("rgb(")) {
const csv = color.substr("rgb(".length, color.length - ("rgb(".length + ")".length));
const rgb = csv.split(",").map(function(item) {
return Number(item);
});
if (rgb.length === 3 || rgb.length === 4) {
return rgbToHex(rgb[0], rgb[1], rgb[2]);
}
else {
return null;
}
}
else {
let hexColor = colors[color.toLowerCase()];
if (typeof hexColor === "string") {
return hexColor;
}
return null;
}
}
}
colorTextInput.addEventListener("input", () => {
let hexColor = getHexColor(colorTextInput.value);
if (hexColor !== null) {
colorTextInput.classList.remove("invalid");
colorSelector.value = hexColor;
}
else {
colorTextInput.classList.add("invalid");
}
});
colorSelector.addEventListener("input", () => {
colorTextInput.classList.remove("invalid");
colorTextInput.value = colorSelector.value;
})
updateColorBtn.addEventListener("click", () => {
document.getElementById("colorOutput").style.borderColor = colorSelector.value;
});
#colorOutput
{
width: 50px;
height: 50px;
border-width: 3px;
border-style: solid;
margin-bottom: 1rem;
}
#colorTextInput {
outline: none;
}
#colorTextInput.invalid {
border-color: #d93025;
}
#colorControls {
display: flex;
gap: .25rem;
}
#colorControls > * {
border-radius: 0.25rem;
border: 1px solid black;
}
#colorSelector {
width: 2rem;
outline: none;
-webkit-appearance: none;
}
#colorSelector::-webkit-color-swatch-wrapper {
padding: 0;
}
#colorSelector::-webkit-color-swatch {
border: none;
margin: 1px 0px;
border-radius: .25rem;
}
<div id="colorOutput" style="border-color: #4169e1;"></div>
<div id="colorControls">
<input id="colorTextInput" type="text" value="royalblue">
<input id="colorSelector" type="color" value="#4169e1">
<button id="updateColorBtn">Set border color</button>
</div>
This Javascript function allows for multiple file uploads and includes a file size limit, however it is missing a maximum number of files allowed to be uploaded.
The function handleFile(e) has the file type and size arguments passed through it but do not know where to introduce a limit on the allowable number of files to be uploaded.
const fInputs = document.querySelectorAll('.btcd-f-input>div>input')
function getFileSize(size) {
let _size = size
let unt = ['Bytes', 'KB', 'MB', 'GB'],
i = 0; while (_size > 900) { _size /= 1024; i++; }
return (Math.round(_size * 100) / 100) + ' ' + unt[i];
}
function delItem(el) {
fileList = { files: [] }
let fInp = el.parentNode.parentNode.parentNode.querySelector('input[type="file"]')
for (let i = 0; i < fInp.files.length; i++) {
fileList.files.push(fInp.files[i])
}
fileList.files.splice(el.getAttribute('data-index'), 1)
fInp.files = createFileList(...fileList.files)
if (fInp.files.length > 0) {
el.parentNode.parentNode.parentNode.querySelector('.btcd-f-title').innerHTML = `${fInp.files.length} File Selected`
} else {
el.parentNode.parentNode.parentNode.querySelector('.btcd-f-title').innerHTML = 'No File Chosen'
}
el.parentNode.remove()
}
function fade(element) {
let op = 1; // initial opacity
let 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;
}, 50);
}
function unfade(element) {
let op = 0.01; // initial opacity
element.style.opacity = op;
element.style.display = 'flex';
let timer = setInterval(function () {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 13);
}
function get_browser() {
let ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return { name: 'IE', version: (tem[1] || '') };
}
if (M[1] === 'Chrome') {
tem = ua.match(/\bOPR|Edge\/(\d+)/)
if (tem != null) { return { name: 'Opera', version: tem[1] }; }
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
return {
name: M[0],
version: M[1]
};
}
for (let inp of fInputs) {
inp.parentNode.querySelector('.btcd-inpBtn>img').src = ''
inp.addEventListener('mousedown', function (e) { setPrevData(e) })
inp.addEventListener('change', function (e) { handleFile(e) })
}
let fileList = { files: [] }
let fName = null
let mxSiz = null
function setPrevData(e) {
if (e.target.hasAttribute('multiple') && fName !== e.target.name) {
console.log('multiple')
fName = e.target.name
fileList = fileList = { files: [] }
if (e.target.files.length > 0) {
for (let i = 0; i < e.target.files.length; i += 1) {
console.log(e.target.files[i])
fileList.files.push(e.target.files[i])
}
}
}
}
function handleFile(e) {
let err = []
const fLen = e.target.files.length;
mxSiz = e.target.parentNode.querySelector('.f-max')
mxSiz = mxSiz != null && (Number(mxSiz.innerHTML.replace(/\D/g, '')) * Math.pow(1024, 2))
if (e.target.hasAttribute('multiple')) {
for (let i = 0; i < fLen; i += 1) {
fileList.files.push(e.target.files[i])
}
} else {
fileList.files.push(e.target.files[0])
}
//type validate
if (e.target.hasAttribute('accept')) {
let tmpf = []
let type = new RegExp(e.target.getAttribute('accept').split(",").join("$|") + '$', 'gi')
for (let i = 0; i < fileList.files.length; i += 1) {
if (fileList.files[i].name.match(type)) {
tmpf.push(fileList.files[i])
} else {
err.push('Wrong File Type Selected')
}
}
fileList.files = tmpf
}
// size validate
if (mxSiz > 0) {
let tmpf = []
for (let i = 0; i < fileList.files.length; i += 1) {
if (fileList.files[i].size < mxSiz) {
tmpf.push(fileList.files[i])
mxSiz -= fileList.files[i].size
} else {
console.log('rejected', i, fileList.files[i].size)
err.push('Max Upload Size Exceeded')
}
}
fileList.files = tmpf
}
if (e.target.hasAttribute('multiple')) {
e.target.files = createFileList(...fileList.files)
} else {
e.target.files = createFileList(fileList.files[fileList.files.length - 1])
fileList = { files: [] }
}
// set File list view
if (e.target.files.length > 0) {
e.target.parentNode.querySelector('.btcd-f-title').innerHTML = e.target.files.length + ' File Selected'
e.target.parentNode.parentNode.querySelector('.btcd-files').innerHTML = ''
for (let i = 0; i < e.target.files.length; i += 1) {
let img = null
if (e.target.files[i].type.match(/image-*/)) {
img = window.URL.createObjectURL(e.target.files[i])
}
else {
img = ''
}
e.target.parentNode.parentNode.querySelector('.btcd-files').insertAdjacentHTML('beforeend', `<div>
<img src="${img}" alt="img" title="${e.target.files[i].name}">
<div>
<span title="${e.target.files[i].name}">${e.target.files[i].name}</span>
<br/>
<small>${getFileSize(e.target.files[i].size)}</small>
</div>
<button type="button" onclick="delItem(this)" data-index="${i}" title="Remove This File"><span>×</span></button>
</div>`)
}
}
// set eror
if (err.length > 0) {
for (let i = 0; i < err.length; i += 1) {
e.target.parentNode.parentNode.querySelector('.btcd-files').insertAdjacentHTML('afterbegin', `
<div style="background: #fff2f2;color: darkred;display:none" class="btcd-f-err">
<img src="" alt="img">
<span>${err[i]}</span>
</div>`)
}
const errNods = e.target.parentNode.parentNode.querySelectorAll('.btcd-files>.btcd-f-err')
for (let i = 0; i < errNods.length; i += 1) {
unfade(errNods[i])
setTimeout(() => { fade(errNods[i]) }, 3000);
setTimeout(() => { errNods[i].remove() }, 4000);
}
err = []
}
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, Helvetica, sans-serif;
}
.btcd-f-input {
display: inline-block;
width: 340px;
position: relative;
overflow: hidden;
}
.btcd-f-input>div>input::-webkit-file-upload-button {
cursor: pointer;
}
.btcd-f-wrp {
cursor: pointer;
}
.btcd-f-wrp>small {
color: gray;
}
.btcd-f-wrp>button {
cursor: pointer;
background: #f3f3f3;
padding: 5px;
display: inline-block;
border-radius: 9px;
border: none;
margin-right: 8px;
height: 35px;
}
.btcd-f-wrp>button>img {
width: 24px;
}
.btcd-f-wrp>button>span,
.btcd-f-wrp>span,
.btcd-f-wrp>small {
vertical-align: super;
}
.btcd-f-input>.btcd-f-wrp>input {
z-index: 100;
width: 100%;
position: absolute;
opacity: 0;
left: 0;
height: 37px;
cursor: pointer;
}
.btcd-f-wrp:hover {
background: #fafafa;
border-radius: 10px;
}
.btcd-files>div {
display: flex;
align-items: center;
background: #f8f8f8;
border-radius: 10px;
margin-left: 30px;
width: 91%;
margin-top: 10px;
height: 40px;
}
.btcd-files>div>div {
display: inline-block;
width: 73%;
}
.btcd-files>div>div>small {
color: gray;
}
.btcd-files>div>img {
width: 40px;
height: 40px;
margin-right: 10px;
border-radius: 10px;
}
.btcd-files>div>div>span {
display: inline-block;
width: 100%;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.btcd-files>div>button {
background: #e8e8e8;
border: none;
border-radius: 50px;
width: 25px;
height: 25px;
font-size: 20px;
margin-right: 6px;
padding: 0;
}
.btcd-files>div>button:hover {
background: #bbbbbb;
}
<div class="btcd-f-input">
<small>Multiple Upload</small>
<div class="btcd-f-wrp">
<button class="btcd-inpBtn" type="button"> <img src="" alt=""> <span> Attach File</span></button>
<span class="btcd-f-title">No File Chosen</span>
<small class="f-max">(Max 1 MB)</small>
<input multiple type="file" name="snd_multiple" id="">
</div>
<div class="btcd-files">
</div>
</div>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<script src="https://unpkg.com/create-file-list#1.0.1/dist/create-file-list.min.js"></script>
In the function handleFile before type validate:
let maxFileNum = 10; // Maximum number of files
if (fileList.files.length > maxFileNum){
err.push("Too many files selected");
}
There is a jsfiddle code that I'd like to use on my page.
I copied css and put it into <style> tag on my page. Then I separate part that starts with
$(function(){
$('.anyClass').liEqualizer({
and put it into custom.js. And the first part that starts with (function ($) { I put into audio_frequency.js. I added its imports to head tag. The page looks like this
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<style>
.sampleWrap {
margin-left: 6%;
margin-top: 5%;
}
.eqCol {
width: 80px;
margin: 0 0 0 2px;
float: left;
}
.eqItem {
height: 20px;
width: 100%;
background: transparent;
margin: 1px 0 0 0;
opacity: 0;
box-shadow: 15px 20px 0px rgba(0,0,0,0.1);
}
.eqCol .eqItem:last-child {
opacity:1 !important
}
</style>
<script src="jquery-3.2.1.slim.min.js"></script>
<script src="audio_frequency.js"></script>
<script src="custom.js"></script>
</head>
<body>
<div class="sampleWrap d-flex">
<div class="anyClass"></div>
<div style="clear:both; padding:15px 0">
<button class="start">start</button>
<button class="stop">stop</button>
</div>
</div>
</div>
</body>
</html>
custom.js looks like this
$(document).ready(function() {
$('.anyClass').liEqualizer({
row:7,
col:20,
speed:20,
freq:400,
on:true
});
$('.start').click(function(){
$('.anyClass').liEqualizer('start');
return false;
})
$('.stop').click(function(){
$('.anyClass').liEqualizer('stop');
return false;
})
});
and audio_frequency looks like this
(function ($) {
var methods = {
init: function (options) {
var p = {
row: 7,
col: 6,
speed: 20,
freq: 400,
on: true
};
if (options) {
$.extend(p, options);
}
var eqWrap = $(this).addClass('eqWrap');
for (c = 0; c < p.col; c++) {
var eqColEl = $('<div>').addClass('eqCol').appendTo(eqWrap);
for(r = 0; r < p.row; r++){
$('<div>').addClass('eqItem').appendTo(eqColEl);
}
}
var
eqCol = $('.eqCol', eqWrap),
eqItem = $('.eqItem', eqWrap),
randomNumber = function (m, n){
m = parseInt(m);
n = parseInt(n);
return Math.floor(Math.random() * (n - m + 1)) + m;
},
eqUp = function(colEl, val) {
var
speed = p.speed,
v = p.row - val,
i = p.row,
j = 0,
flag2 = true,
eachItemUp = function(){
$('.eqItem', colEl).eq(i - 1).nextAll().stop().css({ opacity:'1' });
if ($('.eqItem', colEl).eq(i - 1).css('opacity') == 1) { flag2 = false }
else { flag2 = true }
$('.eqItem', colEl).eq(i - 1).stop(true).animate({ opacity:'1' }, p.speed, function() {
if ($('.eqItem', colEl).index(this) == v) {
if(flag2) {
eqDown(colEl,val);
}
} else {
i--;
j++;
if(i>v){
eachItemUp()
}
}
})
}
eachItemUp()
},
eqDown = function(colEl,val){
var
v = p.row - val,
i = (p.row-val),
j = 0,
speed = p.speed * 2,
eachItemDown = function(){
if (i == (p.row - val)) {
$('.eqItem', colEl).eq(i).animate({ opacity:'0' }, speed * 10)
setTimeout(function() {
i++;
j++;
if(i < p.row){
eachItemDown();
}
}, speed)
} else {
$('.eqItem', colEl).eq(i).animate({ opacity:'0' }, speed, function(){
i++;
j++;
if(i < p.row){
eachItemDown();
}
})
}
}
eachItemDown();
},
eqInterval = function(){
eqCol.each(function(){
eqUp($(this), randomNumber(0, p.row))
})
}
eqInterval()
if (p.on) {
var eqIntervalId = setInterval(eqInterval, p.freq)
$(this).data({
'eqIntId': eqIntervalId,
'eqInt': eqInterval,
'freq': p.freq,
'on': p.on
})
} else {
$(this).data({
'eqIntId':eqIntervalId,
'eqInt':eqInterval,
'freq':p.freq,
'on':p.on
})
}
}, start: function () {
if (!$(this).data('on')) {
$(this).data('eqInt')();
var eqIntervalId = setInterval($(this).data('eqInt'), $(this).data('freq'));
$(this).data ({
'eqIntId':eqIntervalId,
'on':true
})
}
},
stop: function () {
if($(this).data('on')) {
clearInterval($(this).data('eqIntId'));
$('.eqItem', $(this)).animate({opacity:0})
$(this).data({
'on':false
})
}
}
};
$.fn.liEqualizer = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' in jQuery.liEqualizer does not exist');
}
};
})(jQuery);
But when I load page I get
TypeError: $(...).eq(...).nextAll(...).stop is not a function[Learn More]
What is the problem? Is it trying to evaluate something before all the components are ready on the page?
This $(...).eq(...).nextAll(...).stop error is because of jquery-3.2.1.slim.min.js this ist not complete.
Note:
In the jquery.slim.js, the following functions of code are removed:
jQuery.fn.extend
jquery.fn.load
jquery.each // Attach a bunch of functions for handling common AJAX events
jQuery.expr.filters.animated
ajax settings like jQuery.ajaxSettings.xhr, jQuery.ajaxPrefilter, jQuery.ajaxSetup, jQuery.ajaxPrefilter, jQuery.ajaxTransport,
jQuery.ajaxSetup
xml parsing like jQuery.parseXML,
animation effects like jQuery.easing, jQuery.Animation, jQuery.speedIn the jquery.slim.js, the following function of code are removed:
Here is the complete code, you need jquery lib <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script>
<style>
/*Layout css*/
body {
margin: 0;
padding: 20px 10px;
text-align: center
}
.sampleWrap {
height: 290px
}
/*plugin css*/
.eqWrap {
margin: -1px 0 0 -2px;
overflow: hidden;
display: inline-block; //display:inline; //zoom:1;}
.eqCol {
width: 37px;
margin: 0 0 0 2px;
float: left;
}
.eqItem {
height: 10px;
width: 100%;
background: #e7aa3b;
margin: 1px 0 0 0;
opacity: 0
}
.eqCol .eqItem:last-child {
opacity: 1 !important
}
</style>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script>
<div class="sampleWrap">
<div class="anyClass"></div>
<div style="clear:both; padding:15px 0">
<button class="start">start</button>
<button class="stop">stop</button>
</div>
<div class="anyClass2"></div>
<div style="clear:both; padding:15px 0">
<button class="start2">start</button>
<button class="stop2">stop</button>
</div>
</div>
<script>
/*код плагина*/
(function($) {
var methods = {
init: function(options) {
var p = {
row: 7, //кол-во столбцов
col: 6, //кол-во колонок
speed: 20, //скорость подсветки кубиков
freq: 400, //частота сигнала
on: true //включено по умолчанию (true,false)
};
if (options) {
$.extend(p, options);
}
var eqWrap = $(this).addClass('eqWrap');
for (c = 0; c < p.col; c++) {
var eqColEl = $('<div>').addClass('eqCol').appendTo(eqWrap);
for (r = 0; r < p.row; r++) {
$('<div>').addClass('eqItem').appendTo(eqColEl);
}
}
var
eqCol = $('.eqCol', eqWrap),
eqItem = $('.eqItem', eqWrap),
randomNumber = function(m, n) {
m = parseInt(m);
n = parseInt(n);
return Math.floor(Math.random() * (n - m + 1)) + m;
},
eqUp = function(colEl, val) {
var
speed = p.speed,
v = p.row - val,
i = p.row,
j = 0,
flag2 = true,
eachItemUp = function() {
$('.eqItem', colEl).eq(i - 1).nextAll().stop().css({
opacity: '1'
});
if ($('.eqItem', colEl).eq(i - 1).css('opacity') == 1) {
flag2 = false
} else {
flag2 = true
}
$('.eqItem', colEl).eq(i - 1).stop(true).animate({
opacity: '1'
}, p.speed, function() {
if ($('.eqItem', colEl).index(this) == v) {
if (flag2) {
eqDown(colEl, val);
}
} else {
i--;
j++;
if (i > v) {
eachItemUp()
}
}
})
}
eachItemUp()
},
eqDown = function(colEl, val) {
var
v = p.row - val,
i = (p.row - val),
j = 0,
speed = p.speed * 2,
eachItemDown = function() {
if (i == (p.row - val)) {
$('.eqItem', colEl).eq(i).animate({
opacity: '0'
}, speed * 10)
setTimeout(function() {
i++;
j++;
if (i < p.row) {
eachItemDown();
}
}, speed)
} else {
$('.eqItem', colEl).eq(i).animate({
opacity: '0'
}, speed, function() {
i++;
j++;
if (i < p.row) {
eachItemDown();
}
})
}
}
eachItemDown();
},
eqInterval = function() {
eqCol.each(function() {
eqUp($(this), randomNumber(0, p.row))
})
}
eqInterval()
if (p.on) {
var eqIntervalId = setInterval(eqInterval, p.freq)
$(this).data({
'eqIntId': eqIntervalId,
'eqInt': eqInterval,
'freq': p.freq,
'on': p.on
})
} else {
$(this).data({
'eqIntId': eqIntervalId,
'eqInt': eqInterval,
'freq': p.freq,
'on': p.on
})
}
},
start: function() {
if (!$(this).data('on')) {
$(this).data('eqInt')();
var eqIntervalId = setInterval($(this).data('eqInt'), $(this).data('freq'));
$(this).data({
'eqIntId': eqIntervalId,
'on': true
})
}
},
stop: function() {
if ($(this).data('on')) {
clearInterval($(this).data('eqIntId'));
$('.eqItem', $(this)).animate({
opacity: 0
})
$(this).data({
'on': false
})
}
}
};
$.fn.liEqualizer = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Метод ' + method + ' в jQuery.liEqualizer не существует');
}
};
})(jQuery);
/*инициализация плагина*/
$(function() {
$('.anyClass').liEqualizer({
row: 7, //кол-во столбцов
col: 6, //кол-во колонок
speed: 20, //скорость подсветки кубиков
freq: 400, //частота сигнала
on: true //включено по умолчанию (true,false)
});
$('.start').click(function() {
$('.anyClass').liEqualizer('start');
return false;
})
$('.stop').click(function() {
$('.anyClass').liEqualizer('stop');
return false;
})
$('.anyClass2').liEqualizer({
row: 7, //кол-во столбцов
col: 6, //кол-во колонок
speed: 20, //скорость подсветки кубиков
freq: 400, //частота сигнала
on: false //включено по умолчанию (true,false)
});
$('.start2').click(function() {
$('.anyClass2').liEqualizer('start');
return false;
})
$('.stop2').click(function() {
$('.anyClass2').liEqualizer('stop');
return false;
})
});
</script>
I have this code im using to display events from a calendar but its displaying ALL of the events for that month and I only want to display the events for the day when a user clicks on a certain day. For example, click on February 10, you get all of the events for that day.
var eventList = $('<div/>').addClass('c-event-list');
for (var i = 0; i < settings.events.length; i++) {
var d = settings.events[i].datetime;
if ((d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
var date = lpad(d.getMonth(), 2) + '/' +
lpad(d.getDate(), 2) + ' ' +
lpad(d.getHours() %12, 2) + ':' +
lpad(d.getMinutes(), 2);
var item = $('<div/>').addClass('c-event-item');
var title = $('<div/>')
.addClass('title')
.html(date + ' ' + settings.events[i].title + '<br />');
var description = $('<div/>')
.addClass('description')
.html(settings.events[i].description + '<br />');
item.attr('data-event-day', d.getDate());
item.on('mouseover', mouseOverItem).on('mouseleave', mouseLeaveItem);
item.append(title).append(description);
eventList.append(item);
}
}
$(instance).addClass('calendar');
cEventsBody.append(eventList);
$(instance).html(cBody).append(cEvents);
}
return print();
}
Thanks in advance for any assistance.
What I can see from your code is that this condition determines the month and year that events should be held on:
((d.getMonth() - 1) == dMonth && d.getFullYear() == dYear)
So when you want to display events only on a certain day you have to extend this condition like:
(d.getDate() == dDay && (d.getMonth() - 1) == dMonth && d.getFullYear() == dYear)
dDay is a new varibale that holds the day that events should be held on.
Following your request within last answer to show "no events" when a month is selected and there are none available.
I have modified this plugin so that it shows a "text"(for instance "no events") when the list on the right side is empty. I have tested it and it works.
This modification is ok because it is MIT licensed.
(function($) {
var eCalendar = function(options, object) {
// Initializing global variables
var adDay = new Date().getDate();
var adMonth = new Date().getMonth();
var adYear = new Date().getFullYear();
var dDay = adDay;
var dMonth = adMonth;
var dYear = adYear;
var instance = object;
var settings = $.extend({}, $.fn.eCalendar.defaults, options);
function lpad(value, length, pad) {
if (typeof pad == 'undefined') {
pad = '0';
}
var p;
for (var i = 0; i < length; i++) {
p += pad;
}
return (p + value).slice(-length);
}
var mouseOver = function() {
$(this).addClass('c-nav-btn-over');
};
var mouseLeave = function() {
$(this).removeClass('c-nav-btn-over');
};
var mouseOverEvent = function() {
$(this).addClass('c-event-over');
var d = $(this).attr('data-event-day');
$('div.c-event-item[data-event-day="' + d + '"]').addClass('c-event-over');
};
var mouseLeaveEvent = function() {
$(this).removeClass('c-event-over')
var d = $(this).attr('data-event-day');
$('div.c-event-item[data-event-day="' + d + '"]').removeClass('c-event-over');
};
var mouseOverItem = function() {
$(this).addClass('c-event-over');
var d = $(this).attr('data-event-day');
$('div.c-event[data-event-day="' + d + '"]').addClass('c-event-over');
};
var mouseLeaveItem = function() {
$(this).removeClass('c-event-over')
var d = $(this).attr('data-event-day');
$('div.c-event[data-event-day="' + d + '"]').removeClass('c-event-over');
};
var nextMonth = function() {
if (dMonth < 11) {
dMonth++;
} else {
dMonth = 0;
dYear++;
}
print();
};
var previousMonth = function() {
if (dMonth > 0) {
dMonth--;
} else {
dMonth = 11;
dYear--;
}
print();
};
var checkEventsOnCurrentMonth = function() {
var eventNum = $('.c-event-list').find('.c-event-item') ? $('.c-event-list').find('.c-event-item').length : 0;
if (!eventNum) {
$('.c-event-list').html($.fn.eCalendar.defaults.noEventText);
}
};
function loadEvents() {
if (typeof settings.url != 'undefined' && settings.url != '') {
$.ajax({
url: settings.url,
async: false,
success: function(result) {
settings.events = result;
}
});
}
}
function print() {
loadEvents();
var dWeekDayOfMonthStart = new Date(dYear, dMonth, 1).getDay();
var dLastDayOfMonth = new Date(dYear, dMonth + 1, 0).getDate();
var dLastDayOfPreviousMonth = new Date(dYear, dMonth + 1, 0).getDate() - dWeekDayOfMonthStart + 1;
var cBody = $('<div/>').addClass('c-grid');
var cEvents = $('<div/>').addClass('c-event-grid');
var cEventsBody = $('<div/>').addClass('c-event-body');
cEvents.append($('<div/>').addClass('c-event-title c-pad-top').html(settings.eventTitle));
cEvents.append(cEventsBody);
var cNext = $('<div/>').addClass('c-next c-grid-title c-pad-top');
var cMonth = $('<div/>').addClass('c-month c-grid-title c-pad-top');
var cPrevious = $('<div/>').addClass('c-previous c-grid-title c-pad-top');
cPrevious.html(settings.textArrows.previous);
cMonth.html(settings.months[dMonth] + ' ' + dYear);
cNext.html(settings.textArrows.next);
cPrevious.on('mouseover', mouseOver).on('mouseleave', mouseLeave).on('click', previousMonth);
cNext.on('mouseover', mouseOver).on('mouseleave', mouseLeave).on('click', nextMonth);
cBody.append(cPrevious);
cBody.append(cMonth);
cBody.append(cNext);
for (var i = 0; i < settings.weekDays.length; i++) {
var cWeekDay = $('<div/>').addClass('c-week-day c-pad-top');
cWeekDay.html(settings.weekDays[i]);
cBody.append(cWeekDay);
}
var day = 1;
var dayOfNextMonth = 1;
for (var i = 0; i < 42; i++) {
var cDay = $('<div/>');
if (i < dWeekDayOfMonthStart) {
cDay.addClass('c-day-previous-month c-pad-top');
cDay.html(dLastDayOfPreviousMonth++);
} else if (day <= dLastDayOfMonth) {
cDay.addClass('c-day c-pad-top');
if (day == dDay && adMonth == dMonth && adYear == dYear) {
cDay.addClass('c-today');
}
for (var j = 0; j < settings.events.length; j++) {
var d = settings.events[j].datetime;
if (d.getDate() == day && (d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
cDay.addClass('c-event').attr('data-event-day', d.getDate());
cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
}
}
cDay.html(day++);
} else {
cDay.addClass('c-day-next-month c-pad-top');
cDay.html(dayOfNextMonth++);
}
cBody.append(cDay);
}
var eventList = $('<div/>').addClass('c-event-list');
for (var i = 0; i < settings.events.length; i++) {
var d = settings.events[i].datetime;
if ((d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
var date = lpad(d.getDate(), 2) + '/' + lpad(d.getMonth(), 2) + ' ' + lpad(d.getHours(), 2) + ':' + lpad(d.getMinutes(), 2);
var item = $('<div/>').addClass('c-event-item');
var title = $('<div/>').addClass('title').html(date + ' ' + settings.events[i].title + '<br/>');
var description = $('<div/>').addClass('description').html(settings.events[i].description + '<br/>');
item.attr('data-event-day', d.getDate());
item.on('mouseover', mouseOverItem).on('mouseleave', mouseLeaveItem);
item.append(title).append(description);
eventList.append(item);
}
}
$(instance).addClass('calendar');
cEventsBody.append(eventList);
$(instance).html(cBody).append(cEvents);
checkEventsOnCurrentMonth();
}
return print();
}
$.fn.eCalendar = function(oInit) {
return this.each(function() {
return eCalendar(oInit, $(this));
});
};
// plugin defaults
$.fn.eCalendar.defaults = {
weekDays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
months: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
textArrows: {
previous: '<',
next: '>'
},
eventTitle: 'Eventos',
noEventText: 'no events',
url: '',
events: [{
title: 'Brasil x Croácia',
description: 'Abertura da copa do mundo 2014',
datetime: new Date(2014, 6, 12, 17)
}, {
title: 'Brasil x México',
description: 'Segundo jogo da seleção brasileira',
datetime: new Date(2014, 6, 17, 16)
}, {
title: 'Brasil x Camarões',
description: 'Terceiro jogo da seleção brasileira',
datetime: new Date(2014, 6, 23, 16)
}]
};
}(jQuery));
.calendar * {
box-sizing: border-box;
font-family: Tahoma;
font-size: 14px;
}
.calendar-sm {
cursor: default;
width: 800px;
height: 370px;
}
.calendar {
cursor: default;
width: 600px;
height: 270px;
}
.calendar-sm .c-pad-top {
padding-top: 2%;
}
.calendar .c-pad-top {
padding-top: 3%;
}
.c-grid {
box-shadow: 2px 2px 5px #888888;
height: inherit;
}
.c-day {
width: 14.28%;
height: 13%;
background-color: #EFF4F9;
float: left;
text-align: center;
}
.c-day-previous-month {
width: 14.28%;
height: 13%;
background-color: #F9FBFD;
float: left;
text-align: center;
color: gray;
}
.c-day-next-month {
width: 14.28%;
height: 13%;
background-color: #F9FBFD;
float: left;
text-align: center;
color: gray;
}
.c-week-day {
width: 14.28%;
height: 10.38%;
background-color: rgb(145, 172, 203);
color: white;
float: left;
text-align: center;
font-weight: bold;
padding-top: 1%;
}
.c-next {
width: 12.5%;
height: 12%;
padding: 2% 2% 0 2%;
text-align: right;
cursor: pointer;
}
.c-previous {
width: 12.5%;
height: 12%;
padding: 2% 2% 0 2%;
text-align: left;
cursor: pointer;
}
.c-month {
width: 75%;
height: 12%;
text-align: center;
}
.c-nav-btn-over {
background-color: rgb(137, 163, 192) !important;
font-weight: bold;
}
.c-today {
background-color: #D8EAF1;
}
.c-event {
background-color: rgb(166, 166, 166);
color: white;
font-weight: bold;
cursor: pointer;
}
.c-grid {
float: left;
width: 50%;
}
.c-event-grid {
margin-left: 1px;
height: inherit;
width: 49%;
float: left;
box-shadow: 2px 2px 5px #888888;
}
.c-grid-title {
font-weight: bold;
float: left;
background-color: rgb(112, 145, 183);
color: white;
}
.c-event-title {
width: 100%;
height: 12%;
text-align: center;
font-weight: bold;
background-color: rgb(135, 155, 188);
color: white;
}
.c-event-body {
background-color: #EFF4F9;
height: 88.1%;
}
.c-event-list {
padding: 7 0 0 0;
overflow: auto;
height: 95%;
}
.c-event-item > .title {
font-weight: bold;
}
.c-event-item > div {
text-overflow: ellipsis;
width: inherit;
overflow: hidden;
white-space: nowrap;
}
.c-event-item {
padding-left: 10px;
margin-bottom: 10px;
}
.c-event-over {
background-color: lightgray;
font-weight: bold;
color: black;
}
.c-event-over > .description {
font-weight: normal;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>jQuery e-calendar Plugin Demo</title>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/jquery.e-calendar.js"></script>
<script type="text/javascript" src="index.js"></script>
<link rel="stylesheet" href="../css/jquery.e-calendar.css" />
</head>
<body>
<div id="jquery-script-menu">
<div class="jquery-script-center">
<ul>
<li>Download This Plugin
</li>
<li>Back To jQueryScript.Net
</li>
</ul>
<div class="jquery-script-ads">
<script type="text/javascript">
<!--
google_ad_client = "ca-pub-2783044520727903";
/* jQuery_demo */
google_ad_slot = "2780937993";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<div class="jquery-script-clear"></div>
</div>
</div>
<h1 style="margin-top:150px;">jQuery e-calendar Plugin Demo</h1>
<div id="calendar"></div>
</body>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36251023-1']);
_gaq.push(['_setDomainName', 'jqueryscript.net']);
_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>
$(document).ready(function() {
$.fn.eCalendar.defaults.noEventText = '<br/>there are no events available';
$('#calendar').eCalendar({
weekDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
textArrows: {
previous: '<',
next: '>'
},
eventTitle: 'Events',
url: '',
events: [{
title: 'Event 1',
description: 'Description 1',
datetime: new Date(2014, 7, 15, 17)
}, {
title: 'Event 2',
description: 'Description 2',
datetime: new Date(2014, 7, 14, 16)
}, {
title: 'Event 3',
description: 'jQueryScript.Net',
datetime: new Date(2014, 7, 10, 16)
}]
});
});
</script>
</html>
This is the function that check whether the event-list is empty and show a text if it's true. Put this function after previousMonth-function or somewhere within the library:
var checkEventsOnCurrentMonth = function(){
var eventNum = $('.c-event-list').find('.c-event-item') ? $('.c-event-list').find('.c-event-item').length : 0;
if(!eventNum){
$('.c-event-list').html('no events');
}
};
This function you have to call at the end of print:
function print() {
...
...
...
$(instance).addClass('calendar');
cEventsBody.append(eventList);
$(instance).html(cBody).append(cEvents);
// this is the function you have to call at the end of print:
checkEventsOnCurrentMonth();
}
Furthermore you can define the text in another fashion.
There are default values or settings at the bottom of the library.
$.fn.eCalendar.defaults = {
weekDays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
...
...
noEventText: 'no events',
...
...
};
I've defined a new property "noEventText" to be used as text when no events are available.
The function checkEventsOnCurrentMonth has to be altered for this new default-value(noEventText) to be taken into consideration:
var checkEventsOnCurrentMonth = function(){
var eventNum = $('.c-event-list').find('.c-event-item') ? $('.c-event-list').find('.c-event-item').length : 0;
if(!eventNum){
$('.c-event-list').html($.fn.eCalendar.defaults.noEventText);
}
};
At the end you can define the text before the plugin has been started:
$(document).ready(function () {
// here you can define the text and put some html into it.
$.fn.eCalendar.defaults.noEventText = 'there are no events available';
$('#calendar').eCalendar({
...
...
});
});
As mentioned I've tested it but only with the download-version you can find here: http://www.jqueryscript.net/time-clock/Create-A-Simple-Event-Calendar-with-jQuery-e-calendar.html
Image:
I have a simple memory game that is won by matching two letter. How can I add a button to start a timer that displays some where by the game, and when you win the timer stops but shows best times, furthermore, you can keep count to beat your best time. Also, how do I change my letter to substitute for images?
<title>Memory</title>
</head>
<body>
<div id="container">
<div id="header">
Memory!
</div>
<div id="content">
<table id="gameBoard">
<tbody>
</tbody>
</table>
<button id="playAgain">Play Again</button>
</div>
</div>
body {
font-family:copperplate;
font-size: 0.9em;
background-color:#ccc;
}
html, body {
margin:0;
padding:0;
height:100%;
}
#container {
width:950px;
min-width:950px;
background-color:#fff;
margin:0 auto;
min-height:100%;
}
#header {
font-size:4em;
line-height:95px;
text-align:center;
border-bottom:1px solid #000;
}
#content {
clear:both;
border-top:1px solid #000;
padding-top:5px;
padding:10px;
text-align:center;
}
h1 {
text-transform: capitalize;
}
#gameBoard {
margin-left:auto;
margin-right:auto;
margin-bottom:25px;
}
.card {
width:100px;
height:100px;
border:1px solid #000;
cursor: pointer;
}
.down {
background-color: #E8DD5B;
}
.up {
background-color: #ccc;
line-height: 100px;
text-align:center;
font-size:5em;
}
button {
font-size:2em;
padding:5px;
background-color:#E97A54;
}
$(function() {
var cards = [
{ id: 1, matchesId: 2, content: "A" },
{ id: 2, matchesId: 1, content: "A" },
{ id: 3, matchesId: 4, content: "B" },
{ id: 4, matchesId: 3, content: "B" },
{ id: 5, matchesId: 6, content: "C" },
{ id: 6, matchesId: 5, content: "C" },
{ id: 7, matchesId: 8, content: "D" },
{ id: 8, matchesId: 7, content: "D" },
{ id: 9, matchesId: 10, content: "E" },
{ id: 10, matchesId: 9, content: "E" },
{ id: 11, matchesId: 12, content: "F" },
{ id: 12, matchesId: 11, content: "F" }
];
var shuffledCards = [];
var cardToMatchElement;
setupGame();
$("#playAgain").click(function() {
setupGame();
});
function setupGame() {
cardToMatchElement = null;
shuffleCards();
dealCards();
}
function shuffleCards() {
shuffledCards = [];
for(var i = 0; i < cards.length; i++) {
var randomCardIndex = getRandomCardIndex();
while($.inArray(randomCardIndex,shuffledCards) != -1) {
randomCardIndex = getRandomCardIndex();
}
shuffledCards.push(randomCardIndex);
}
}
function getRandomCardIndex() {
return Math.floor((Math.random() * cards.length));
}
function dealCards() {
setupGameBoard();
attachCardEvents();
}
function attachCardEvents() {
$(".card").click(function() {
var selectedCardElement = $(this);
var selectedCard = getCardFromElement(selectedCardElement);
flipCard(selectedCardElement, selectedCard);
if(cardToMatchElement) {
var cardToMatch = getCardFromElement(cardToMatchElement);
if(cardToMatch.matchesId == selectedCard.id) {
selectedCardElement.off();
cardToMatchElement.off();
cardToMatchElement = null;
}
else {
$.blockUI({ message: "", overlayCSS : { backgroundColor: '#fff', cursor:'normal', opacity:0.5 } });
setTimeout(function() {
flipCard(selectedCardElement, selectedCard);
flipCard(cardToMatchElement, cardToMatch);
cardToMatchElement = null;
$.unblockUI();
},1000);
}
}
else {
cardToMatchElement = selectedCardElement;
}
});
}
function getCardFromElement(cardElement) {
return cards[cardElement.attr("data-cardindex")];
}
function flipCard(cardElement, card) {
if(cardElement.hasClass("down")) {
cardElement.removeClass("down").addClass("up");
cardElement.html(card.content);
}
else {
cardElement.removeClass("up").addClass("down");
cardElement.html("");
}
}
function setupGameBoard() {
var numberColumns = 4;
var tableBody = "";
var tableRow = "<tr>";
$.each(shuffledCards, function(index, card) {
tableRow += "<td><div class='card down' data-cardindex='" + shuffledCards[index] + "'> </div></td>";
if(index > 0 && (index + 1) % numberColumns == 0) {
tableRow += "</tr>";
if(index < cards.length - 1) {
tableRow += "<tr>";
}
}
if(index == cards.length - 1 && (index + 1) % numberColumns != 0) {
tableRow += "</tr>";
}
tableBody += tableRow;
tableRow = "";
});
$("#gameBoard tbody").html(tableBody);
}
});
http://jsfiddle.net/Brannan2/VkKRa/1/
To create a timer call below function on your button click (id is some global js variable)
function createTimer() {
id = setInterval(function(){
var secondEl = document.getElementById('second');
if (secondEl.value == null || secondEl.value == "") {
secondEl.value = 0;
}
var seconds = parseInt(secondEl.value) + 1;
if (seconds == 60) {
seconds = 0;
var minuteEl = document.getElementById('minute');
if (minuteEl.value == null || minuteEl.value == "") {
minuteEl.value = 0;
}
var minutes = parseInt(minuteEl.value) + 1;
if (minutes == 60) {
minutes = 0;
var hourEl = document.getElementById('hour');
if (hourEl.value == null || hourEl.value == "") {
hourEl.value = 0;
}
hourEl.value = parseInt(hourEl.value) + 1;
}
minuteEl.value = minutes;
}
secondEl.value = seconds;
},1000);
}
For my sample I have created three input types in html with ids 'hour','minute' and 'second'. You can create any other based on UI need and update function accordingly.
To stop timer just remove the setInterval function as shown below
window.clearInterval(id);
Once you have stop the watch you can calculate total times easily by using below formula
var totalTime = (hours * 3600) + (minutes * 60) + seconds;
This will return the total time in seconds. Now to get best times, I think you have to use localStorage so that you can store best times in client browser and refer to it later whenever user returns again to play your game.
To substitute letter with images, there can be many ways. For e.g. you can add a css class to the element which will set the background image for you or you can directly use a img tag in your div with image location. Its totally up to you. I am not sure though why you want to show image with your current requirement.