Appending Text to Div Extends Div Beyond Initial CSS Grid - html

I've created a basic CSS Grid and had everything positioned where I wanted it. When I run my JS (appends info from an API call to a div), the div's dimension push beyond the borders of the viewport. Is there a way to prevent the overall body element from changing and just have the div dynamically increase height?
pics: https://imgur.com/a/wJAcW
I've tried so many different things and can't seem to figure this out. My fallback will be to just overwrite the div rather than append to it. Code is below.
//Set initial latitute and longitude variables, to be used later
var lat = 0;
var long = 0;
//Google Geocode API to find the latitude and longitude of the txtAddress
$("#submit").on("click", function() {
var userInput = $("#txtAddress").val();
//trim the user input to the form needed for the api
var userSearchTerm = userInput.split(' ').join('+');
//call the google geocode api
var queryURLGeocode = "https://maps.googleapis.com/maps/api/geocode/json?address=" + userSearchTerm + "&key=AIzaSyCSAYHZn9fz13c3bsl_RcS13HJu8wDJXCU"
$.ajax({
url: queryURLGeocode,
method: "GET"
})
.done(function(response) {
//Set latitude and longitude from the returned object
lat = response.results[0].geometry.location.lat;
//limit decimal points to 4 (xx.xxxx) - form needed for hiking api
lat = lat.toFixed(4);
long = response.results[0].geometry.location.lng;
long = long.toFixed(4);
//Call the hiking project api
var queryURL = "https://www.hikingproject.com/data/get-trails?lat=" + lat + "&lon=" + long + "&maxDistance=10&key=200206461-4fa8ac1aa85295888ce833cca1b5929f"
$.ajax({
url: queryURL,
method: "GET"
})
.done(function(response) {
// loop through the response trails and add info to the site
for (i = 0; i < response.trails.length; i++) {
var contentDivTitle = $("<div> class='newTrailTitle'");
var contentDivMain = $("<div> class='newTrailDescription'");
contentDivTitle.text("Name: " + response.trails[i].name + " Location: " + response.trails[i].location);
contentDivMain.text("Summary: " + response.trails[i].summary);
$("#search-results").append(contentDivTitle);
$("#search-results").append(contentDivMain);
}
});
});
});
html,
body {
background-color: black;
margin: 10px;
}
h1,
h3 {
color: white;
text-align: center;
padding: 5px;
line-height: 1px;
}
h1 {
/* automatically changes lowercase to uppercase text; */
text-transform: uppercase;
}
sub {
color: white;
text-align: center;
line-height: 1px;
font-size: 15px;
font-weight: lighter;
}
.container {
display: grid;
grid-template-columns: auto;
grid-template-rows: 800px 500px 200px 50px 100px;
grid-gap: 3px;
}
.container>div {
display: flex;
justify-content: center;
align-items: center;
font-size: 1em;
}
.container>div:nth-child(1n) {
background-color: black;
}
.container>div:nth-child(2n) {
background-color: blue;
}
.container>div:nth-child(3n) {
background-color: red;
}
.container>div:nth-child(4n) {
background-color: yellow;
}
.container>div:nth-child(5n) {
background-color: green;
}
label {
color: white;
}
#main {
background-image: url("assets/images/etienne-bosiger-367964.jpg");
background-size: cover;
background-repeat: no-repeat;
}
#au,
#cr {
display: block;
margin: auto;
}
#groupPic {
padding: 10px;
}
<html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="container">
<div id="main">
<div id="title">
<h1>kairns<sub>®</sub></h1>
<h3>"find your trail"</h3>
<div class="search-div">
<label for="txtAddress">Enter Address: </label>
<input type="text" name="txtAddress" id="txtAddress">
<button type="button" id="submit">Search</button>
</div>
</div>
</div>
<div class="search-results" id="search-results">2</div>
<div>
<p id="au">About Us</p>
<img id="groupPic" src="http://via.placeholder.com/150x150" alt="placeholder image">
<p id="cr">Copyright 2018.</p>
</div>
<div>4</div>
<div>
<p>Powered by
Google Maps,
Open Weather Map, and Hiking Project
</p>
</div>
</div>
<!-- JAVASCRIPT -->
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- custom javaScript -->
<script type='text/javascript' src='assets/javascript/logic.js'></script>
</body>
</html>

All in-flow children of the #search-results element will align vertically if you apply:
#search-results {
display: flex;
flex-direction: column;
}

Related

Memory Game Cards Not Rotating Properly

I have been learning how to create a memory game and thought I was following the instructions carefully but I have run into a snag. In my html, I have a div for the card and two child divs to style the front and back of the card.
<div class="container">
<div id="memory_board">
<div class="card">
<div id="back0" class="cardFace cardFaceBack"></div>
<div id="front0" class="cardFace cardFaceFront" class="card"></div>
</div>
</div>
</div>
The number of cards for the memory game will vary.
When I run the code, they are stacked on top of each other meaning when you click on one card, the back flips over as expected but the front flips over underneath its original position. Here is my codepen. How can I adjust me code so that it looks like the card flips over properly?
=============== Edit ===================
Quick question, when I include a link to codepen, do I still have include all of the code?
The css for this game is:
* {
margin:0;
padding:0;
box-sizing:border-box;
}
div.container {
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
}
div#memory_board{
background:#CCC;
border:#999 1px solid;
display: inline-block;
padding: 10px;
perspective: 1000px;
}
.card {
width:100px;
height:133px;
display: inline-block;
margin:0px;
padding:10px;
transition: transform 1s;
transform-style: preserve-3d;
transform-origin: center right;
cursor: pointer;
position: relative;
}
.card.is-flipped {
transform: translateX(-100%) rotateY(-180deg);
}
.cardFace {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.cardFaceFront {
position: inherit;
background: whitesmoke;
color: black;
font-weight: bold;
font-size: 40px;
border:#000 1px solid;
text-align:center;
vertical-align: middle;
transform: rotateY(180deg);
}
.cardFaceBack {
background: url("https://images.cdn2.stockunlimited.net/preview1300/playing-cards-
background_1608080.jpg"); no-repeat;
background-size: cover;
position: relative;
border:#000 1px solid;
}
In addition, the javascript for this program is:
var memory_array = ['A','A','B','B'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
const memory_board = document.getElementById('memory_board');
let getRndInteger = (min, max) => Math.floor(Math.random() * (max - min) ) + min
// the following function randomly shuffles elements in an array using the Fisher-Yates (aka Knuth) shuffle
let shuffle = array => {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
function initiateCard () {
let card = document.querySelectorAll('.card');
card.forEach( card => card.addEventListener ( 'click', () => {
card.classList.toggle('is-flipped');
}));
}
function newBoard() {
let memoryArray = shuffle (memory_array);
for (let i = 0; i <= memoryArray.length - 1; i++) {
document.getElementById("front" + i).innerText = memory_array[i];
}
}
$( document ).ready(function() {
newBoard ();
initiateCard ();
});
When the game starts, the memory_array shuffles propery and each element is distributed to the cards. However, when you turn a card,
I thought I had followed the instructions but I do not understand why, when turned, the front face is below where the back was. What adjustments do I have to make, after turning the card, so the front of the card in the same place as the back of the card, not below it.
an animation or a gif will be of help to as what you want to achieve, from your comment in your code I could see you are trying to replicate this, but the way you structure your code doesn't seem to be as this
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Okay, so a couple of things. I couldn't get your js to work. Getting this error "Uncaught TypeError: Cannot set properties of null (setting 'innerText')".
And with your CSS you need to position the front and back with position: absolute; otherwise, they affect each other. The back was pushing the front down the page.
And if you set transform-origin: center center; you don't need to do the additional transform: translateY(-100%);
var memory_array = ['A', 'A', 'B', 'B'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
const memory_board = document.getElementById('memory_board');
let getRndInteger = (min, max) => Math.floor(Math.random() * (max - min)) + min
// the following function randomly shuffles elements in an array using the Fisher-Yates (aka Knuth) shuffle
let shuffle = array => {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
function initiateCard() {
let card = document.querySelectorAll('.card');
card.forEach(card => card.addEventListener('click', () => {
card.classList.toggle('is-flipped');
}));
}
function newBoard() {
let memoryArray = shuffle(memory_array);
for (let i = 0; i <= memoryArray.length - 1; i++) {
document.getElementById("front" + i).innerText = memory_array[i];
}
}
$(document).ready(function () {
newBoard();
initiateCard();
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
div.container {
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
}
div#memory_board {
background: #CCC;
border: #999 1px solid;
display: inline-block;
padding: 10px;
perspective: 1000px;
}
.card {
width: 100px;
height: 133px;
display: inline-block;
margin: 0px;
/* padding: 10px; */
transition: transform 1s;
transform-style: preserve-3d;
cursor: pointer;
position: relative;
transform-origin: center center;
}
.card.is-flipped {
transform: rotateY(180deg);
}
.cardFace {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.cardFaceFront {
position: absolute;
background: whitesmoke;
color: black;
font-weight: bold;
font-size: 40px;
border: #000 1px solid;
text-align: center;
vertical-align: middle;
transform: rotateY(180deg);
}
.cardFaceBack {
background: url("https://images.cdn2.stockunlimited.net/preview1300/playing-cards-background_1608080.jpg") no-repeat;
background-size: cover;
position: absolute;
border: #000 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container">
<div id="memory_board">
<div class="card is-flipped">
<div id="back0" class="cardFace cardFaceBack"></div>
<div id="front0" class="cardFace cardFaceFront" class="card"></div>
</div>
<div class="card">
<div id="back0" class="cardFace cardFaceBack"></div>
<div id="front0" class="cardFace cardFaceFront" class="card"></div>
</div>
<div class="card">
<div id="back0" class="cardFace cardFaceBack"></div>
<div id="front0" class="cardFace cardFaceFront" class="card"></div>
</div>
<div class="card">
<div id="back0" class="cardFace cardFaceBack"></div>
<div id="front0" class="cardFace cardFaceFront" class="card"></div>
</div>
</div>
</div>

How to create a box around around controls in webprgramming

I have a few controls that I am attempting to encapsulate on my webpage. I have tried a few different methods on encapsulating my controls and they have not succeeded. I tried using a div and this did not work too well and I have also tried this post:
Create a group box around certain controls on a web form using CSS
What is happening is that a box is being created but it is at the top of my webpage instead of around the controls.
I would like to create a grey box similar to the ones found on this webpage:
https://img.labnol.org/di/trigger1.png
Below, I am attaching a copy of the CSS and HTML code that I am using in order to create my form. The form is a simple file upload form that I tweaked from an example. I am using this on my own, personal website.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
//_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
document.getElementById('p1').innerHTML = "Drag your file here or click in this area.";
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
function changeText()
{
document.getElementById('p1').innerHTML = "1 file selected";
}
</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h2>Upload</h2>
<fieldset>
<legend>Group 1</legend>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<p id="p1">Drag your file here or click in this area.</p>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:508px; margin-left: -4px; margin-top: 10px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</fieldset>
<script>
// self executing function here
(function() {
document.getElementById('upload_form')[0].onchange = changeText;
})();
</script>
</body>
</html>
Here is the CSS (which is referred to in the html as test.css):
body{
background: rgba(0,0,0,0.0);
}
form{
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -250px;
width: 500px;
height: 200px;
border: 4px dashed #0D0D0D;
}
form p{
width: 100%;
height: 100%;
text-align: center;
line-height: 140px;
color: #0D0D0D;
font-family: Arial;
}
h2{
text-align: center;
}
form input[type="file"]{
position: absolute;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
outline: none;
opacity: 0;
}
form input[type="button"]{
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 508px;
height: 35px;
margin-top: -20px;
margin-left: -4px;
border-radius: 4px;
border-bottom: 4px solid #117A60;
transition: all .2s ease;
outline: none;
}
form input[type="button"]:hover{
background: #149174;
color: #0C5645;
}
form input[type="button"]:active{
border:0;
}
form progressBar{
text-align: center;
}
Coming back to the HTML, the fieldset tags are placed around the controls that I am attempting to encapsulate. I left them there so that anyone can see the main issue that I am running into.
I apologize but I am very new to web programming. Any help will be greatly appreciated, thank you.
Note: how the box is created doesn't really matter to me. I would expect that the box is created in HTML and then I can style it using CSS.
The structure of your HTML is fine, but the position: absolute properties in your CSS are clashing with the fieldset.
Since <fieldset> is wrapping all your controls, I would suggeset giving it a fixed width and height and position your child elements based on that, i.e. use width: 100% for your children and give all of them the same margin so they align nicely. Also make sure you either edit your #progressBar style in the markup.
Here's a snippet with the changes I just mentioned:
body {
background: rgba(0, 0, 0, 0.0);
}
fieldset {
width: 508px;
height: 270px;
/* fixed width and height*/
margin: 13vh auto;
}
#p1 {
border: 4px dashed #0D0D0D;
/* modified the actual text box instead of the entire form */
width: 508px;
height: 140px;
line-height: 140px;
margin-top: 0px;
}
form p {
text-align: center;
color: #0D0D0D;
font-family: Arial;
}
h2 {
text-align: center;
}
form input[type="file"] {
position: absolute;
margin: 0;
outline: none;
width: 508px;
height: 140px;
margin: 22px 4px;
opacity: 1;
background-color: orange;
/* Last two properties are a visual representation. Delete background-color and set opacity to 0 */
}
form input[type="button"] {
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 100%;
/* width relative to parent fieldset */
height: 35px;
margin-top: -20px;
border-radius: 4px;
border-bottom: 4px solid #117A60;
transition: all .2s ease;
outline: none;
}
form input[type="button"]:hover {
background: #149174;
color: #0C5645;
}
form input[type="button"]:active {
border: 0;
}
form progressBar {
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
//_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
document.getElementById('p1').innerHTML = "Drag your file here or click in this area.";
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
function changeText() {
document.getElementById('p1').innerHTML = "1 file selected";
}
</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h2>Upload</h2>
<fieldset>
<legend>Group 1</legend>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<p id="p1">Drag your file here or click in this area.</p>
<input type="button" value="Upload File" onclick="uploadFile()">
<!-- changed progressBar style -->
<progress id="progressBar" value="0" max="100" style="width:100%; margin-top: 10px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</fieldset>
<script>
// self executing function here
(function() {
document.getElementById('upload_form')[0].onchange = changeText;
})();
</script>
</body>
</html>
Hope it helps!

How can I control the placement of my Chart.JS pie chart's legend, as well as its appearance?

I am able to create a pie chart using Chart.JS with this code:
HTML
<div>
<canvas id="top10ItemsChart" style="padding-left:20px" width="320" height="320"></canvas>
<div id="top10Legend" class="chart-legend"></div>
</div>
jQuery
var data = [{
value: 2755,
color: "#FFE135",
label: "Bananas"
}, {
value: 2256,
color: "#3B5323",
label: "Lettuce, Romaine"
}, {
value: 1637,
color: "#fc6c85",
label: "Melons, Watermelon"
}, {
value: 1608,
color: "#ffec89",
label: "Pineapple"
}, {
value: 1603,
color: "#021c3d",
label: "Berries"
}, {
value: 1433,
color: "#3B5323",
label: "Lettuce, Spring Mix"
}, {
value: 1207,
color: "#046b00",
label: "Broccoli"
}, {
value: 1076,
color: "#cef45a",
label: "Melons, Honeydew"
}, {
value: 1056,
color: "#421C52",
label: "Grapes"
}, {
value: 1048,
color: "#FEA620",
label: "Melons, Cantaloupe"
}];
var optionsPie = {
legend: {
display: true,
position: 'right',
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var top10PieChart = new Chart(ctx).Pie(data, optionsPie);
document.getElementById('top10Legend').innerHTML = top10PieChart.generateLegend();
The problem is that it positions the legend to the bottom of the pie, and even spilling and bleeding outside of the boundaries of the div to which I want the pie to restrict itself:
It also presents the legend as a simple unordered list. What I want to do is to control the color of the various elements in the legend ("Banana" should be the same color (#FFE135) as the piece of banana pie (so to speak), etc.)
How can I make the individual elements match the color of its respective data point?
UPDATE
The "Legend Label Configuration" topic in the official docs here indicate you can set the fontColor of the legends, but this is for the whole shebang; what I want to know is, how is it possible to control the color of each item?
UPDATE 2
In an attempt to at least get the legend displaying in the desired spot, I added this to the jQuery:
var optionsPie = {
legend: {
display: true,
position: 'right',
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
. . .
var myPieChart = new Chart(ctx).Pie(data, optionsPie);
document.getElementById("legendDiv").innerHTML = myPieChart.generateLegend();
...but it makes no difference - the legend is still hung from the bottom of the pie chart, and its font is still the default black.
UPDATE 3
I utilized some suggested code, but the legend is still gravity-fed instead of hanging off to the right:
So the legend impinges on the chart below it, rather than restricting itself to its own neighborhood.
Also, I don't want the bullet points to infest the legend - the colored squares (and the verbiage - but also the values) are all I need. How can I shove the legend from south of the pie to east of the pie?
UPDATE 4
I have refactored the code based on this and it's looking better (I added more data to the "label" value of the data array, too):
Still, though, as you can see the legend is infringing on the quadrant below it. There is a "ton" of empty/wasted space around the pie, though - I want to move the pie to the left, and the legend to the right of the pie. That would also allow more vertical space for the pie to grow in stature.
How can I do that? Here is the code I'm using now:
HTML
<div>
<canvas id="top10ItemsChart" class="pie" style="padding-left:20px"></canvas>
<div id="top10Legend"></div>
</div>
CSS
.pie-legend {
list-style: none;
margin: 0;
padding: 0;
}
.pie-legend span {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 100%;
margin-right: 16px;
margin-bottom: -2px;
}
.pie-legend li {
margin-bottom: 10px;
display: inline-block;
margin-right: 10px;
}
JQUERY
var data = [{
value: 2755,
color: "#FFE135",
label: "Bananas: 2,755 (18%)"
}, {
. . .
}, {
value: 1048,
color: "#FEA620",
label: "Melons, Cantaloupe: 1,048 (7%)"
}];
var optionsPie = {
responsive: true,
scaleBeginAtZero: true,
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
}
var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var top10PieChart = new Chart(ctx).Pie(data, optionsPie);
$("#top10Legend").html(top10PieChart.generateLegend());
NOTE: Adding this to optionsPie:
legend: {
display: true,
position: 'right'
},
...does nothing - the legend remains weighted down to the floor like a frog filled to the chin with quail shot.
UPDATE 5
I've played around with Teo's example, trying to get it to work just right but, although it's better, the pie is very puny, and the legend should be wider, but I can't figure out how to stretch the legend horizontally and the pie in all directions. Here's how it looks now:
This is the code now (JQUERY is the same):
HTML
<div class="col-md-6">
<div class="topleft">
<h2 class="sectiontext">Top 10 Items</h2>
<br />
<div class="legendTable">
<div class="legendCell">
<canvas id="top10ItemsChart" class="pie" style="padding-left:20px"></canvas>
</div>
<div class="legendCell" id="top10Legend">
</div>
</div>
</div>
</div>
CSS
.topleft {
margin-top: -4px;
margin-left: 16px;
margin-bottom: 16px;
padding: 16px;
border: 1px solid black;
}
canvas {
width: 100% !important;
height: auto !important;
}
.legendTable {
border: 1px solid forestgreen;
display: table;
width: 100%;
table-layout: fixed;
}
.legendCell {
display: table-cell;
vertical-align: middle;
}
.pie-legend ul {
list-style: none;
margin: 0;
padding: 0;
width: 300px;
}
.pie-legend span {
display: inline-block;
width: 14px;
height: 12px;
border-radius: 100%;
margin-right: 4px;
margin-bottom: -2px;
}
.pie-legend li {
margin-bottom: 4px;
display: inline-block;
margin-right: 4px;
}
Something is squashing the pie and pushing the outer edges of the legend together.
UPDATE 6
Ochi, et al: Here's what I see after the Ochification of my code:
This is my code - I even ordered the jQuery in the way you have it, although I doubt that is really necessary:
HTML
<div class="row" id="top10Items">
<div class="col-md-6">
<div class="topleft">
<h2 class="sectiontext">Top 10 Items</h2>
<br />
#*<div class="legendTable">
<div class="legendCell">
<canvas id="top10ItemsChart" class="pie" style="padding-left:20px"></canvas>
</div>
<div class="legendCell" id="top10Legend">
</div>
</div>*#
<div class="chart">
<canvas id="top10ItemsChart" class="pie"></canvas>
<div id="pie_legend"></div>
</div>
</div>
</div>
. . .
</div>
CSS
.pie-legend {
list-style: none;
margin: 0;
padding: 0;
}
.pie-legend span {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 100%;
margin-right: 16px;
margin-bottom: -2px;
}
.pie-legend li {
margin-bottom: 10px;
display: block;
margin-right: 10px;
}
.chart,
#priceComplianceBarChart,
#pie_legend {
display: inline-flex;
padding: 0;
margin: 0;
}
JQUERY
var optionsPie = {
responsive: true,
scaleBeginAtZero: true,
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
}
var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var data = [{
value: 2755,
color: "#FFE135",
label: "Bananas: 2,755 (18%)"
. . .
}, {
value: 1048,
color: "#FEA620",
label: "Melons, Cantaloupe: 1,048 (7%)"
}];
var top10PieChart = new Chart(ctx).Pie(data, optionsPie);
$("#pie_legend").html(top10PieChart.generateLegend());
...and yet the pie is stretchier than stretch pants on an elephant.
UPDATE 7
Maybe there's a configuration problem or something. I decided to "upgrade" to version 2.1.3 of Chart.JS (started out w. version 1.0.2):
#*<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.js"></script>
...and copied almost exactly Teo Dragovic's CodePen here.
The only things I changed were the names of two CSS class ("table" became "legendTable" and "cell" became "legendCell") and the color of the table border from red to forestgreen, and I get this now:
Do I need to also a reference a Chart.JS CSS file or something?
I think this what you want: DEMO
First, you need to make canvas responsive by overriding fixed width and height and wrap it in additional div that can be used for positioning. I used display: table for centering elements but setting inner divs to inline-block also works if you wish for chart and legend to take different amount of space than 50:50.
HTML:
<div class="table">
<div class="cell">
<canvas id="top10ItemsChart" class="pie"></canvas>
</div>
<div class="cell" id="top10Legend"></div>
</div>
CSS:
canvas {
width: 100% !important;
height: auto !important;
}
.table {
border: 1px solid red;
display: table;
width: 100%;
table-layout: fixed;
}
.cell {
display: table-cell;
vertical-align: middle;
}
UPDATE: Did some adjustment based on additional information by OP NEW DEMO
HTML:
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="topleft">
<h2 class="sectiontext">Top 10 Items</h2>
<br />
<div class="chart">
<div class="pie">
<canvas id="top10ItemsChart" class="pie"></canvas>
</div>
<div class="legend" id="top10Legend">
</div>
</div>
</div>
</div>
</div>
</div>
CSS:
.topleft {
margin-top: -4px;
margin-left: 16px;
margin-bottom: 16px;
padding: 16px;
border: 1px solid black;
}
canvas {
width: 100% !important;
height: auto !important;
margin-left: -25%;
}
.chart {
border: 1px solid forestgreen;
width: 100%;
overflow: hidden;
position: relative;
}
.pie {
position: relative;
padding: 10px 0;
// adjust as necessary
padding-left: 10px;
padding-right: 0;
}
.legend {
position: absolute;
right: 10px;
top: 10px;
height: 100%;
// adjust as necessary:
width: 48%;
}
#media (max-width: 480px) {
.legend {
position: relative;
width: 100%;
}
.pie {
margin: 0;
}
}
.pie-legend ul {
list-style: none;
margin: 0;
padding: 0;
width: 300px;
}
.pie-legend span {
display: inline-block;
width: 14px;
height: 12px;
border-radius: 100%;
margin-right: 4px;
margin-bottom: -2px;
}
.pie-legend li {
margin-bottom: 4px;
display: inline-block;
margin-right: 4px;
}
As #B.ClayShannon mentioned, version 2 is quite a bit different than verison 1. Here is an example of how to customize the legend template using version 2.
options: {
legendCallback: function (chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend" style="list-style:none">');
for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
text.push('<li><div style="width:10px;height:10px;display:inline-block;background:' + chart.data.datasets[0].backgroundColor[i] + '" /> ');
if (chart.data.labels[i]) {
text.push(chart.data.labels[i]);
}
text.push('</li>');
}
text.push('</ul>');
return text.join('');
},
legend: {display: false},
}
It's not shown directly in the accepted solution above, but to render your legend elsewhere you'll want to call:
$("#myChartLegend").html(myChart.generateLegend());
Finally, some HTML to pull it together (note clearfix is a Bootstrap class that :
<div class="chart">
<div style="float:left">
<canvas id="myChart" class="pie" style="max-width:300px;"></canvas>
</div>
<div class="legend" id="myChartLegend" style="float:left;"></div>
<div style="clear: both;"/>
</div>
This is what works (more or less) using version 2 of Chart.JS:
HTML
<h2 class="sectiontext">Top 10 Items</h2>
<br />
<div class="chart">
<canvas id="top10ItemsChart" class="pie"></canvas>
<div id="pie_legend"></div>
</div>
JQUERY
var data = {
labels: [
"Bananas: 2,755 (18%)",
"Lettuce, Romaine: 2,256 (14%)",
"Melons, Watermelon: 1,637 (10%)",
"Pineapple: 1,608 (10%)",
"Berries: 1,603 (10%)",
"Lettuce, Spring Mix: 1,433 (9%)",
"Broccoli: 1,207 (8%)",
"Melons, Honeydew: 1,076 (7%)",
"Grapes: 1,056 (7%)",
"Melons, Cantaloupe: 1,048 (7%)"
],
datasets: [
{
data: [2755, 2256, 1637, 1608, 1603, 1433, 1207, 1076, 1056, 1048],
backgroundColor: [
"#FFE135",
"#3B5323",
"#fc6c85",
"#ffec89",
"#021c3d",
"#3B5323",
"#046b00",
"#cef45a",
"#421C52",
"#FEA620"
],
}]
};
var optionsPie = {
responsive: true,
scaleBeginAtZero: true
}
var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var top10PieChart = new Chart(ctx,
{
type: 'pie',
data: data,
options: optionsPie
});
$("#top10Legend").html(top10PieChart.generateLegend());
I say, "more or less" because the pie pieces are still pitifully puny:

WinJS.BackButton sizes

I have this html tag which reffers to the backButton provided by the WinJS library:
<button data-win-control="WinJS.UI.BackButton"></button>
I want to change its size. How can I do that? I tried using CSS by adding the ID "backButton" and font-size OR width/height properties, like this:
#backButton {
font-size: small;
}
#backButton {
height: 30px;
width: 30px;
}
EDIT: Code added and a picture of what happens when changing the values of width/height of the button.
// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/anime/anime.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
this.renderAnimeInfo(Identifier.file);
},
unload: function () {
// TODO: Respond to navigations away from this page.
},
updateLayout: function (element) {
/// <param name="element" domElement="true" />
// TODO: Respond to changes in layout.
},
renderAnimeInfo: function (id) {
// Path for the anime data.
var path = "data/animes.json";
// Retrieve the .json.
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
for (var i = 0; i < json.length; i++) {
if (json[i].file == id) {
var animeData = json[i];
break;
}
}
},
function (error) {},
function (progress) {}
);
},
});
})();
.right {
float: right;
}
.left {
float: left;
}
.active {
background-color: blue;
}
#animeDetails {
background: red;
height: 100%;
width: 300px;
float: left;
}
#animeInfo {
display: -ms-grid;
height: 100%;
width: calc(100% - 300px);
float: right;
}
#navbar {
-ms-grid-row: 1;
padding: 20px 25px;
}
#navbar .right button {
margin-right: 4px;
}
#navbar input {
width: 150px;
}
#details {
-ms-grid-row: 2;
padding: 0 25px;
text-align: justify;
white-space: pre-line;
}
#details h3 {
width: 100%;
padding: 5px 0;
border-bottom: 1px solid #bebebe;
margin-bottom: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>anime</title>
<link href="anime.css" rel="stylesheet" />
<script src="anime.js"></script>
</head>
<body>
<div id="animeDetails"></div>
<div id="animeInfo">
<div id="navbar">
<div class="left">
<button class="left" data-win-control="WinJS.UI.BackButton"></button>
<h3>Back</h3>
</div>
<div class="right">
<button type="button" class="active">Details</button>
<button type="button">Episodes</button>
<button type="button">Characters</button>
<button type="button">Staff</button>
<input type="search" placeholder="Search" />
</div>
</div>
<div id="details">
<div id="synopsis">
<h3>Synopsis</h3>
<span>
</span>
</div>
</div>
</div>
</body>
When using the width/height properties, what happens is that the button does resize to the specified value, but the icon inside (which is not a background) doesn't. http://i.imgur.com/lMqmL0G.png
Possibly you have to set display: inline-block to button because the width of an element with display: inline (the default for buttons) is exactly the same as its content because it only takes up the space needed to display its contents so try with:
With id selector
#backButton {
height: 30px;
width: 30px;
display: inline-block;
}
<button id="backButton" data-win-control="WinJS.UI.BackButton"></button>
With style inline
<button data-win-control="WinJS.UI.BackButton" style="width: 30px; height: 30px; display: inline-block"></button>
Try to set the styles to child element .win-back
#backButton .win-back{
/*---styles---*/
}
You haven't given your button an ID. The CSS does not know what tag to link to.
<button id="backButton" data-win-control="WinJS.UI.BackButton"></button>
edit: you may find the following reference useful CSS Selectors

How best to make a smileys box in html

I'd like to add a box containing smileys icons above the comment area which opens using jQuery on click. What I come up with is this:
<div class="emo">
<i href="#" id="showhide_emobox"> </i>
<div id="emobox">
<input class="emoticon" id="icon-smile" type="button" value=":)" />
<input class="emoticon" id="icon-sad" type="button" value=":(" />
<input class="emoticon" id="icon-widesmile" type="button" value=":D" /> <br>
</div>
</div>
css:
.emoticon-smile{
background: url('../smileys/smile.png');
}
#icon-smile {
border: none;
background: url('../images/smile.gif') no-repeat;
}
jQuery:
// =======show hide emoticon div============
$('#showhide_emobox').click(function(){
$('#emobox').toggle();
$(this).toggleClass('active');
});
// ============add emoticons============
$('.emoticon').click(function() {
var textarea_val = jQuery.trim($('.user-comment').val());
var emotion_val = $(this).attr('value');
if (textarea_val =='') {
var sp = '';
} else {
var sp = ' ';
}
$('.user-comment').focus().val(textarea_val + sp + emotion_val + sp);
});
However I have difficulty placing buttons in a nice array and make background image for them (the button values appear before image and the array is not perfectly rectangular. So I'm wondering maybe this is not the best way to render this box.
Any ideas to do this properly?
First show images, on hover hide image and show text. No need for input elements to get text of Dom Node
Something like this:
$(document).ready(function() {
$(".wrapper").click(function() {
var value = $(this).find(".smily-text").text();
console.log(value);
alert("Smily text is '" + value + "'");
});
});
.smily {
background: url(http://www.smiley-lol.com/smiley/manger/grignoter/vil-chewingum.gif) no-repeat center center;
width: 45px;
height: 45px;
}
.smily-text {
display: none;
font-size: 20px;
text-align: center;
line-height: 45px;
height: 45px;
width: 45px;
}
.wrapper {
border: 1px solid red;
float: left;
cursor: pointer;
}
.wrapper:hover .smily {
display: none;
}
.wrapper:hover .smily-text {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:)</div>
</div>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:(</div>
</div>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:]</div>
</div>
<div class="wrapper">
<div class="smily"></div>
<div class="smily-text">:[</div>
</div>