How-to place JavaScript generated div element inside main body div element - javascript

I have tried several different approaches to place a JavaScript generated bar graph that generates its own div element into the body of the main div element without success. Does anyone know how this can be accomplished?
EDITED
Here is the CodePen to see what I am talking about. As you can see, I have a wrapper with a border around the body. However, no matter where I place the script, I cannot get it into the wrapper. It is always generated outside.
Any help will be much appreciated.
Here is the code.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</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="Stephen Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
</head>
<body>
<div id="wrapper">
<h2>Test</h2>
<div class="topnav">
Home
Login
</div>
<div>
<h2>Sales Subscription Dashboard</h2>
<script src="js/subscriptions_graph.js">
</div>
</div>
<div class="copyright">
Copyright © 2018
</div>
</body>
</script>
</html>
CSS
#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 {
text-align: center;
font-size: 10px;
padding: 5px;
}
JavaScript
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 = 25;
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.body.appendChild(chart);
};

Your problem is that you are appending it to the body - therefore getting the bar graph out of the box.
It will be placed into the #wrapper if you swap that this line:
document.body.appendChild(chart);
for this:
document.querySelector('#wrapper').appendChild(chart);
Note that this is best seen in the full screen mode of the snippet - you will need to address the overflow when the graph is bigger than the containing wrapper on smaller screens. I popped an overflow-x: auto style rule there to show it is within the wrapper.
Also you were not closing the script tag correctly - so i fixed that as well.
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 = 25;
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); // I altered this line
};
#wrapper {
margin-left: auto;
margin-right: auto;
width: 100%;
border: groove;
border-color: white;
padding: 2px;
overflow-x: auto;
}
#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 {
text-align: center;
font-size: 10px;
padding: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</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="Stephen Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
</head>
<body>
<div id="wrapper">
<h2>Test</h2>
<div class="topnav">
Home
Login
</div>
<div>
<h2>Sales Subscription Dashboard</h2>
</div>
</div>
<div class="copyright">
Copyright © 2018
</div>
<script src="js/subscriptions_graph.js"></script>
</body>
</html>

Related

How to add a Vertical line at the end of a percentage bar HTML/Javascript

I am using the following HTML/Javascipt code to make the classic percentage bar.
function update() {
var element = document.getElementById("myprogressBar");
var width = 1;
var identity = setInterval(scene, 10);
function scene() {
if (width >= 70) {
clearInterval(identity);
} else {
width++;
element.style.width = width + '%';
element.innerHTML = width * 1 + '%';
}
}
}
#Progress_Status {
width: 50%;
background-color: #ddd;
}
#myprogressBar {
width: 1%;
height: 35px;
background-color: #4CAF50;
text-align: center;
line-height: 32px;
color: black;
}
<!DOCTYPE html>
<html>
<body>
<h3>Example of Progress Bar Using JavaScript</h3>
<p>Download Status of a File:</p>
<div id="Progress_Status">
<div id="myprogressBar">1%</div>
</div>
<br>
<button onclick="update()">Start Download</button>
</body>
</html>
What I would like to obtain and I am trying to achieve with .innerHTML is the following situation
The vertical line has to appear at the same level of the specified percentage.
For the vertical bar I used an added div nested inside the #Progress_Status container. It's styled to be absolute positioned and to change its offset in % in sync with the progress bar width.
For it to work, its container was set to position:relative as the reference frame.
function update() {
//fetches the vertical bar elements
var vbar = document.querySelector("#Progress_Status .percverticalbar");
var element = document.getElementById("myprogressBar");
var width = 1;
var identity = setInterval(scene, 10);
function scene() {
if (width >= 70) {
clearInterval(identity);
} else {
width++;
//updates the left offset of the vertical bar
vbar.style.left = `${width}%`;
element.style.width = width + '%';
element.innerHTML = width * 1 + '%';
}
}
}
#Progress_Status {
width: 50%;
background-color: #ddd;
position: relative;
}
.percverticalbar{
position: absolute;
height: 100px;
width: 5px;
background: gray;
top: -25px;
left: 0;
}
#myprogressBar {
width: 1%;
height: 35px;
background-color: #4CAF50;
text-align: center;
line-height: 32px;
color: black;
margin: 50px 0;
}
<h3>Example of Progress Bar Using JavaScript</h3>
<p>Download Status of a File:</p>
<div id="Progress_Status">
<div id="myprogressBar">1%</div>
<div class="percverticalbar"></div>
</div>
<br>
<button onclick="update()">Start Download</button>
You could just add an :after pseudo element and add the following styles to it. Keep in mind that the parent, in the case #myprogressBar should be relatively positioned.
#myprogressBar {
width: 1%;
height: 35px;
background-color: #4CAF50;
text-align: center;
line-height: 32px;
color: black;
position: relative;
}
#myprogressBar:after {
width: 5px;
height: 80px;
background: #333;
content: '';
position: absolute;
right: -5px;
top: 50%;
transform: translateY(-50%);
border-radius: 5px;
}

javascript on a webpage displaying text wrongly

I have JS code on a webpage that loads questions in from mysql db and displays the text . What happens is that it cuts off words at the end of the line and continues the word on the next line at the start. So all text across the screen starts/ends at the same point.
This seems to be the code where it displays the text.
For example the text will look like at the end of a line 'cont' and then on next line at the start 'inue'.
How do i fix this?
var questions = <?=$questions;?>;
// Initialize variables
//------------------------------------------------------------------
var tags;
var tagsClass = '';
var liTagsid = [];
var correctAns = 0;
var isscorrect = 0;
var quizPage = 1;
var currentIndex = 0;
var currentQuestion = questions[currentIndex];
var prevousQuestion;
var previousIndex = 0;
var ulTag = document.getElementsByClassName('ulclass')[0];
var button = document.getElementById('submit');
var questionTitle = document.getElementById('question');
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'selected';
// Display Answers and hightlight selected item
//------------------------------------------------------------------
function showQuestions (){
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
if (currentIndex != 0) {
// create again submit button only for next pages
ulTag.innerHTML ='';
button.innerHTML = 'Submit';
button.className = 'submit';
button.id = 'submit';
if(quizPage<=questions.length){
//update the number of questions displayed
document.getElementById('quizNumber').innerHTML = quizPage;
}
}
//Display Results in the final page
if (currentIndex == (questions.length)) {
ulTag.innerHTML = '';
document.getElementById('question').innerHTML = '';
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
showResults();
return
}
questionTitle.innerHTML = "Question No:" + quizPage + " "+currentQuestion.question.category_name +"<br/>"+ currentQuestion.question.text;
if(currentQuestion.question.filename !== ''){
var br = document.createElement('br');
questionTitle .appendChild(br);
var img = document.createElement('img');
img.src = currentQuestion.question.filename;
img.className = 'imagecenter';
img.width = 750;
img.height = 350;
questionTitle .appendChild(img);
}
// create a for loop to generate the options and display them in the page
for (var i = 0; i < currentQuestion.options.length; i++) {
// creating options
var newAns = document.createElement('li');
newAns.id = 'ans'+ (i+1);
newAns.className = "notSelected listyle";
var textAns = document.createTextNode(currentQuestion.options[i].optiontext);
newAns.appendChild(textAns);
if(currentQuestion.options[i].file !== ''){
var br = document.createElement('br');
newAns .appendChild(br);
var img1 = document.createElement('img');
img1.src = currentQuestion.options[i].file;
img1.className = 'optionimg';
img1.width = 250;
img1.height = 250;
newAns .appendChild(img1);
newAns .appendChild(br);
}
var addNewAnsHere = document.getElementById('options');
addNewAnsHere.appendChild(newAns);
}
//.click() will return the result of $('.notSelected')
var $liTags = $('.notSelected').click(function(list) {
list.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.notSelected')
//instead of the saved $litTags
$liTags.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
//get id name of clicked answer
for (var i = 0; i < currentQuestion.options.length ; i++) {
// console.log(liTagsid[i]);
if($liTags[i].className == "notSelected listyle selected"){
//store information to check answer
tags = $liTags[i].id;
// tagsClass = $LiTags.className;
tagsClassName = $liTags[i];
}
}
});
//check answer once it has been submitted
button.onclick = function (){
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
setTimeout(function() { checkAnswer(); }, 100);
};
}
//self calling function
showQuestions();
The website is on my local now but i can upload a screenimage if need be and the whole code of the webpage. Or is the issue in html?
edit: here is html/css code
<style>
/*========================================================
Quiz Section
========================================================*/
/*styling quiz area*/
.main {
background-color: white;
margin: 0 auto;
margin-top: 30px;
padding: 30px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
/*white-space: nowrap;*/
}
/*Editing the number of questions*/
.spanclass {
font-size: x-large;
}
#pages{
border: 3px solid;
display: inline-flex;
border-radius: 0.5em;
float: right;
}
#question{
word-break: break-all;
}
/*format text*/
p {
text-align: left;
font-size: x-large;
padding: 10px 10px 0;
}
.optionimg{
border: 2px solid black;
border-radius: 1.5em;
}
/*Form area width*/
/*formatting answers*/
.listyle {
list-style-type: none;
text-align: left;
background-color: transparent;
margin: 10px 5px;
padding: 5px 10px;
border: 1px solid lightgray;
border-radius: 0.5em;
font-weight: normal;
font-size: x-large;
display: inline-grid;
width: 48%;
height: 300px;
overflow: auto;
}
.listyle:hover {
background: #ECEEF0;
cursor: pointer;
}
/*Change effect of question when the questions is selected*/
.selected, .selected:hover {
background: #FFDEAD;
}
/*change correct answer background*/
.correct, .correct:hover {
background: #9ACD32;
color: white;
}
/*change wrong answer background*/
.wrong, .wrong:hover {
background: #db3c3c;
color: white;
}
/*========================================================
Submit Button
========================================================*/
.main button {
text-transform: uppercase;
width: 20%;
border: none;
padding: 15px;
color: #FFFFFF;
}
.submit:hover, .submit:active, .submit:focus {
background: #43A047;
}
.submit {
background: #4CAF50;
min-width: 120px;
}
/*next question button*/
.next {
background: #fa994a;
min-width: 120px;
}
.next:hover, .next:active, .next:focus {
background: #e38a42;
}
.restart {
background-color:
}
/*========================================================
Results
========================================================*/
.circle{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: #bdc3c7;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
overflow: hidden;
}
.fill{
position: absolute;
bottom: 0;
width: 100%;
height: 80%;
background: #31a2ac;
}
.score {
position: absolute;
width: 100%;
top: 1.7em;
text-align: center;
font-family: Arial, sans-serif;
color: #fff;
font-size: 40pt;
line-height: 0;
font-weight: normal;
}
.circle p {
margin: 400px;
}
/*========================================================
Confeeti Effect
========================================================*/
canvas{
position:absolute;
left:0;
top:11em;
z-index:0;
border:0px solid #000;
}
.imagecenter{
display: block;
margin: 0 auto;
}
.buttonload {
background-color: #04AA6D; /* Green background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
#media only screen and (max-width: 900px){
.listyle {
width: 100% !important;
height: auto !important;
}
.imagecenter {
width: 100% !important;
}
.listyle img{
width: inherit !important;
height: unset !important;
}
.ulclass
{
padding:0px !important;
}
}
</style>
<!-- Main page -->
<div class="main">
<!-- Number of Question -->
<div class="wrapper" id="pages">
<span class="spanclass" id="quizNumber">1</span><span class="spanclass">/<?=$count?></span>
</div>
<!-- Quiz Question -->
<div class="quiz-questions" id="display-area">
<p id="question"></p>
<ul class="ulclass" id="options">
</ul>
<div id="quiz-results" class="text-center">
<button type="button" name="button" class="submit" id="submit">Submit</button>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
I'm guessing that #question{ word-break: break-all; } is probably the culprit then? –
CB..yes that fixed it:)

Change modal backgroundColor on button click using Javascript

I created a linear-gradient and animated it in javascript and set it as the background to my website. Then I added a button in HTML that when clicked the colors of the gradient switch out.
Now I am trying to make the button also change the backgroundColor of a modal on my page, but I can't seem to figure it out. Could anyone help me see where I went wrong?
I think I am just having a problem targeting the class of .modal that is on the modal div.
I will firstly put the broken javascript of when I attempt to add the function to change the modal background. Then I will put the html, css, and javascript that is not broke (without the code to change the modal background.
Broken Javascript
var angle = -20, color = "#2b2b2b", colors = "#000", font = "rgba(102, 102, 102, .3)", shadow = "4px 4px 40px #000", modalz = "rgba(0, 0, 0, 0.6)";
var changeBackground = function() {
angle = angle + .3
document.body.style.backgroundImage = "linear-gradient(" + angle + "deg, " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color;
requestAnimationFrame(changeBackground)
}
var changeFont = function() {
document.querySelectorAll('li').forEach(li => li.style.color = font);
}
var changeShadow = function() {
document.querySelectorAll('li').forEach(li => li.style.textShadow = shadow);
}
var changeModal = function() {
document.body.style.modal.backgroundColor = "rgba(0, 0, 0, 0.6)";
}
changeBackground()
changeFont()
changeShadow();
document.querySelector('#myBtn').addEventListener('click', function () {
color = (color != "#2b2b2b") ? "#2b2b2b" : "#f1f9d4";
colors = (colors != "#000") ? "#000" : "#759ef3";
font = (font != "rgba(102, 102, 102, .3)") ? "rgba(102, 102, 102, .3)" : "rgba(178, 117, 164, .3)";
shadow = (shadow != "4px 4px 40px #000") ? "4px 4px 40px #000" : "4px 4px 40px #fff";
modalz = (modalz != "rgba(0, 0, 0, 0.6)") ? "rgba(0, 0, 0, 0.6)" : "rgba(240, 240, 240, 1)";
changeFont()
changeModal()
changeShadow();
})
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jacob Truax Portfolio</title>
<script src="main.js"></script>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="fonts.css">
<script src="jquery.js"></script>
</head>
<body>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p> This is a test </p>
</div>
</div>
<!-- Button triggering color change -->
<div id="myBtn" class="Btn">
<button></button>
</div>
<!-- main content -->
<div class="main">
<ul>
<li id="hover1-1" class="fnup">fn-up</li>
<li id="hover1-2" class="about">about</li>
<li id="hover1-3" class="issue">issue 0</li>
<li id="hover1-4" class="contact">contact</li>
</ul>
</div>
Css
/* The Modal (background) */
.modal {
color: #fff;
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 5; /* Sit on top */
padding-top: 20px; /* Location of the box */
padding-bottom: 20px;
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.6); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
margin: auto;
text-align: center;
padding: 20px;
width: 80%;
font-size: 3vw;
line-height: 6.4vh;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
display: none;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* End modal ============ */
body {
background-color: #d22c1f;
font-family:"Brrr", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 700;
font-size: 12vw;
overflow: hidden;
perspective: 1500px;
height: 100vh;
width: 100vw;
}
#media only screen and (min-width: 1600px) {
body {
font-size: 210px
}
}
/* a {
opacity: 0;
color: rgba(102, 102, 102, 0);
text-decoration: none;
display: inline-block;
} */
/* the main contet is in 3d space and rotates slightly with the cursor */
.main {
position: relative;
height: 100vh;
width: 100vw;
transform-style: preserve-3d;
backface-visibility: hidden;
transform: rotateX(0deg) rotateY(0deg);
}
li {
text-shadow: 4px 4px 40px #000;
color: rgba(102, 102, 102, .3);
padding-left: 60px;
top: -10px;
display: inline-block;
}
div.Btn {
position: fixed;
line-height:0;
font-size: 0px;
right: 3vw;
bottom: 3vh;
width: 36px;
height: 36px;
background-image: url(lib/frown.svg);
opacity: 0.3;
mix-blend-mode: overlay;
z-index: 2;
}
div.Btn:hover {
background-image: url(lib/smile.svg);
opacity: 0.3;
mix-blend-mode: overlay;
}
button {
width: 36px;
height: 36px;
border: none;
outline:none;
background: transparent;
border: none !important;
cursor: pointer;
font-size:0;
}
Javascript (not broken)
var angle = -20, color = "#2b2b2b", colors = "#000", font = "rgba(102, 102, 102, .3)", shadow = "4px 4px 40px #000";
var changeBackground = function() {
angle = angle + .3
document.body.style.backgroundImage = "linear-gradient(" + angle + "deg, " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color + ", " + colors + ", " + color;
requestAnimationFrame(changeBackground)
}
var changeFont = function() {
document.querySelectorAll('li').forEach(li => li.style.color = font);
}
var changeShadow = function() {
document.querySelectorAll('li').forEach(li => li.style.textShadow = shadow);
}
changeBackground()
changeFont()
changeShadow();
document.querySelector('#myBtn').addEventListener('click', function () {
color = (color != "#2b2b2b") ? "#2b2b2b" : "#f1f9d4";
colors = (colors != "#000") ? "#000" : "#759ef3";
font = (font != "rgba(102, 102, 102, .3)") ? "rgba(102, 102, 102, .3)" : "rgba(178, 117, 164, .3)";
shadow = (shadow != "4px 4px 40px #000") ? "4px 4px 40px #000" : "4px 4px 40px #fff";
changeFont()
changeShadow();
})
You can try this instead. Give your modal an id. Let's say you give it elem.
var elem = document.getElementById("elem");
elem.style.backgroundColor = "rgba(0, 0, 0, 0.6)";
the problem must be with this syntax
document.body.style.modal.backgroundColor= "blue";
I may be missing something obvious, but to my knowledge, document.body.style.modal doesn't return anything. You should access the element with the class of modal and then assign the color. document.querySelector('.modal').style.backgroundColor = "blue";

Why doesn't CSS transition get applied?

I've built a small stacked bar visual just using floated divs that underneath is bound to some data using knockout. What I want to be able to do is to animate changes in the size of these stacks when the data changes.
I've managed to do this in the general case, so of the 4 bars that I've got, 3 of them transition correctly. The problem is my final bar seems to ignore the transition and instantly re-sizes and I can't understand why. Here's a picture of the before/during/after states:
The way that I've defined this transition is simply via css
-webkit-transition: width 1s;
transition: width 1s;
The width of the bars is a computed value, calculating the percentage of items, so each bar should have it's width defined as a percentage. Although the red bar is calculated differently to the other 3 bars, I don't see why that should affect the transition.
What I find quite strange, is that if I modify the width through the developer console for example, then the bar does correctly animate. I'm wondering if anyone can suggest why this might be the case?
var vm = (function generateModel() {
var data = {
name: "Sign-off",
id: "XX",
values: [{ text: "Signed-off", count: 150, color: "#5fb5cc" },
{ text: "Submitted", count: 90, color: "#75d181" },
{ text: "Not Submitted", count: 75, color: "#f8a25b" }
],
aggregates: {
count: 650
}
};
// Create a view model directly from the data which we will update
var vm = ko.mapping.fromJS(data);
// Add a computed value to calculate percentage
vm.values().forEach(function (d) {
d.percentage = ko.computed(function () {
return d.count() / vm.aggregates.count() * 100;
});
});
// Create a
vm.allValues = ko.computed(function() {
var values = [];
var count = 0;
var total = vm.aggregates.count();
debugger;
// Add each of these results into those that will be returned
vm.values().forEach(function(d) {
values.push(d);
count += d.count();
});
// Create an other category for everything else
values.push({
text: ko.observable("Other"),
count: ko.observable(total - count),
percentage: ko.observable((total - count) / total * 100),
color: ko.observable("#ff0000")
});
return values;
});
return vm;
})();
ko.applyBindings(vm);
setTimeout(function() {
vm.values()[0].count(90);
vm.values()[1].count(40);
vm.values()[2].count(35);
vm.aggregates.count(3550);
}, 3000);
body {
background: rgb(40, 40, 40);
}
.spacer {
height: 230px;
}
.cards {
float: right;
}
/* Small Card */
.card {
margin-bottom: 3px;
background: white;
border-radius: 3px;
width:398px;
float: right;
clear: both;
min-height: 100px;
padding: 10px 5px 15px 5px;
font-family:'Open Sans', Arial, sans-serif;
}
.title {
color: rgb(105, 161, 36);
font-size: 16px;
}
.states {
padding-top: 10px;
}
.state {
font-size: 12px;
color: rgb(67, 88, 98);
padding: 0px 5px 2px 5px;
clear: both;
}
.circle {
width: 10px;
height: 10px;
border-radius: 50%;
float: left;
margin: 1px 5px 5px 0px;
}
.value {
float: right;
}
.graph {
padding: 10px 5px 0px 5px;
}
.bar {
float: left;
height: 10px;
-webkit-transition: width 10s;
transition: width 10s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<div class="card">
<div class="content">
<div class="graph" data-bind="foreach: allValues">
<div class="bar" data-bind="style: { background: color, width: percentage() + '%' }"/>
</div>
</div>
</div>
As the first 3 are based on object references that don't change, knockout is preserving the actual <div> that's been rendered.
For the final bar, each time allValues is evaluated, it's pushing a brand new object into the returned array. I would assume that since knockout sees that as a new object, it re-renders the div from scratch, rather than updating existing bindings.
You'll need to rework your model slightly to hold an actual object for that final value so that you can then update the observables on it in the same way.
Here's a fixed version using a static object for the "other" value:
var vm = (function generateModel() {
var data = {
name: "Sign-off",
id: "XX",
values: [{ text: "Signed-off", count: 150, color: "#5fb5cc" },
{ text: "Submitted", count: 90, color: "#75d181" },
{ text: "Not Submitted", count: 75, color: "#f8a25b" }
],
aggregates: {
count: 650
}
};
// Create a view model directly from the data which we will update
var vm = ko.mapping.fromJS(data);
// Add a computed value to calculate percentage
vm.values().forEach(function (d) {
d.percentage = ko.computed(function () {
return d.count() / vm.aggregates.count() * 100;
});
});
//Create a static "others" object
vm.other = {
text: ko.observable("Other"),
count: ko.computed(function() {
var total = vm.aggregates.count();
var count = 0;
vm.values().forEach(function(d) { count += d.count(); });
return total - count;
}),
percentage: ko.computed(function(d, b) {
var total = vm.aggregates.count();
var count = 0;
vm.values().forEach(function(d) { count += d.count(); });
return (total - count) / total * 100;
}),
color: ko.observable("#ff0000")
};
// Create a
vm.allValues = ko.computed(function() {
var values = [];
var count = 0;
var total = vm.aggregates.count();
debugger;
// Add each of these results into those that will be returned
vm.values().forEach(function(d) {
values.push(d);
count += d.count();
});
// and push static object in instead of creating a new one
values.push(vm.other);
return values;
});
return vm;
})();
ko.applyBindings(vm);
setTimeout(function() {
vm.values()[0].count(90);
vm.values()[1].count(40);
vm.values()[2].count(35);
vm.aggregates.count(3550);
}, 3000);
body {
background: rgb(40, 40, 40);
}
.spacer {
height: 230px;
}
.cards {
float: right;
}
/* Small Card */
.card {
margin-bottom: 3px;
background: white;
border-radius: 3px;
width:398px;
float: right;
clear: both;
min-height: 100px;
padding: 10px 5px 15px 5px;
font-family:'Open Sans', Arial, sans-serif;
}
.title {
color: rgb(105, 161, 36);
font-size: 16px;
}
.states {
padding-top: 10px;
}
.state {
font-size: 12px;
color: rgb(67, 88, 98);
padding: 0px 5px 2px 5px;
clear: both;
}
.circle {
width: 10px;
height: 10px;
border-radius: 50%;
float: left;
margin: 1px 5px 5px 0px;
}
.value {
float: right;
}
.graph {
padding: 10px 5px 0px 5px;
}
.bar {
float: left;
height: 10px;
-webkit-transition: width 10s;
transition: width 10s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<div class="card">
<div class="content">
<div class="graph" data-bind="foreach: allValues">
<div class="bar" data-bind="style: { background: color, width: percentage() + '%' }"/>
</div>
</div>
</div>

Limit a DIV to appear within another DIV of specific size

I'm currently working on this small project that randomly displays a div (#box) of 100px width and height. I want this div to appear ONLY in another div (#boxBorder) so it appears to be limited to a specific area on the page.
Here is the content of my HTML:
<h1>Test your reactions!</h1>
<p id="directions">Click the shape as fast as you can!</p>
<p id="scoreC">Click score: <span id="cScore">0</span>s</p>
<p id="scoreT">Total score: <span id="tScore">0</span>s</p>
<div id="boxBorder"></div>
<div id="box"></div>
Here is the CSS:
#boxBorder {
height: 500px;
width: 500px;
margin: 20px auto;
left: 0;
right: 0;
background-color: white;
border: 1px black solid;
position: absolute;
z-index: 0;
}
#box {
margin: 0 auto;
height: 100px;
width: 100px;
background-color: red;
display: none;
border-radius: 50px;
position: relative;
z-index: 1;
}
h1 {
margin: 15px 0 0 0;
}
#directions {
margin: 0;
padding: 5px;
font-size: 0.8em;
}
#scoreT, #scoreC {
font-weight: bold;
margin: 10px 50px 0 0;
}
#tScore, #cScore {
font-weight: normal;
}
h1, #directions, #scoreT, #scoreC {
width: 100%;
text-align: center;
}
And lastly, the javascript function for random position:
//Get random position
function getRandomPos() {
var pos = Math.floor((Math.random() * 500) + 1);
console.log("POS: " + pos + "px");
return pos + "px";
}
Which I call within a timeout method:
setTimeout(function() {
createdTime = Date.now();
console.log("make box: " + createdTime);
document.getElementById("box").style.top=getRandomPos();
document.getElementById("box").style.left=getRandomPos();
document.getElementById("box").style.backgroundColor=getRandomColor();
document.getElementById("box").style.borderRadius=getRandomShape();
document.getElementById("box").style.display="block";
}, rTime);
I'm not very skilled in positioning and I can't seem to get these two divs to align so that the #box div can recognize the size of the #boxBorder div and stay within those limits. Any help would be appreciated!
Couple things wrong here:
You need the box div nested inside the borderBox div if you want to use the relative positioning.
<div id="boxBorder">
<div id="box"></div>
</div>
The randomPos function needs to take into account the size of the box, so only multiply by 400 instead of 500.
function getRandomPos() {
var pos = Math.floor((Math.random() * 400));
return pos + "px";
}
Set the style to inline-block, not block for the box.
Use setInterval instead of setTimeout to have it repeat.
var rTime = 1000;
function getRandomPos() {
var pos = Math.floor((Math.random() * 400));
console.log("POS: " + pos + "px");
return pos + "px";
}
function getRandomColor() {
return ['#bf616a', '#d08770', '#ebcb8b', '#a3be8c', '#96b5b4', '#8fa1b3', '#b48ead'][(Math.floor(Math.random() * 7))];
}
function randomizeBox() {
createdTime = Date.now();
console.log("make box: " + createdTime);
document.getElementById("box").style.top = getRandomPos();
document.getElementById("box").style.left = getRandomPos();
document.getElementById("box").style.backgroundColor = getRandomColor();
}
setInterval(randomizeBox, rTime);
#boxBorder {
height: 500px;
width: 500px;
margin: 20px auto;
left: 0;
right: 0;
background-color: white;
border: 1px black solid;
position: absolute;
z-index: 0;
}
#box {
margin: 0 auto;
height: 100px;
width: 100px;
border-radius: 50px;
position: relative;
z-index: 1;
display: inline-block;
}
h1 {
margin: 15px 0 0 0;
}
#directions {
margin: 0;
padding: 5px;
font-size: 0.8em;
}
#scoreT,
#scoreC {
font-weight: bold;
margin: 10px 50px 0 0;
}
#tScore,
#cScore {
font-weight: normal;
}
h1,
#directions,
#scoreT,
#scoreC {
width: 100%;
text-align: center;
}
<h1>Test your reactions!</h1>
<p id="directions">Click the shape as fast as you can!</p>
<p id="scoreC">Click score: <span id="cScore">0</span>s</p>
<p id="scoreT">Total score: <span id="tScore">0</span>s</p>
<div id="boxBorder">
<div id="box"></div>
</div>

Categories