I'm very new to html/css/js. I wanted to create a color gradient bar and then draw a dot on it based on a variable. I have looked around and from different sources I came up with this, but it's not fully working and I would like to know why.
var A = 38,
B = 100,
C = 0,
D = 300,
score = 67; // {{crFlag['value']}} will be variable
function init() {
$('.circle').attr('style', 'left: ' + ((score - A) / (B - A) * (D - C)) + 'px');
};
.container {
position: relative;
display: flex;
width: 300px;
height: 16px;
border: 1px solid #7c7676;
background-image: linear-gradient(to right, #4cd964, #d0ff00, #e0740f, #ff2d55);
}
.circle {
background: rgba(88, 83, 83);
width: 10px;
height: 16px;
border-radius: 30%;
position: absolute;
left: 40px;
}
<div class="container">
<div class="circle"></div>
</div>
Why is the dot not changing position when I give a different score?
Two things:
1) f you were calling your init function at all, you may have been calling it too early (before the DOM had loaded, so before the div with class circle exists). I added a new script block at the end to call it.
2) You didn't say if you were actually using jQuery or not, but you're using jQuery syntax. The example below will work without jQuery, but you can uncomment the line I commented out if and only iff you've loaded jQuery.
<html>
<head>
<style>
.container {
position: relative;
display: flex;
width: 300px;
height: 16px;
border: 1px solid #7c7676;
background-image: linear-gradient(to right, #4cd964, #d0ff00, #e0740f, #ff2d55);
}
.circle {
background: rgba(88, 83, 83);
width: 10px;
height: 16px;
border-radius: 30%;
position: absolute;
left: 40px;
}
</style>
<script>
var A = 38,
B = 100,
C = 0,
D = 300,
score = 67; // {{crFlag['value']}} will be variable
function init(){
document.querySelector(".circle").setAttribute("style", 'left: ' + ((score-A)/(B-A)*(D-C)) + 'px' )
// $('.circle').attr('style', 'left: ' + ((score-A)/(B-A)*(D-C)) + 'px' );
};
</script>
</head>
<body>
<div class="container">
<div class="circle"></div>
</div>
</body>
<script>
init();
</script>
</html>
Related
I’m trying to code a mobile game in which you must drive a car, so I have made a separate file as a library of sorts. The problem is how to I calculate how to move forward using the orient variable to find out which way is forward. I would have tried to add this, but I had no clue where to start :/ any help is appreciated! Here is the code:
<!doctype html>
<html>
<head>
<title>Title Here</title>
<!-- CSS --!>
<style>
#character {
position: relative;
transform: rotate(0deg);
width: 50px;
height: 75px;
background-color: red;
top: 50px;
left: 50px;
}
#left {
position: fixed;
bottom: 3px;
left: 3px;
width: 125px;
height: 125px;
background-color: red;
text-align: center;
}
#right {
position: fixed;
bottom: 3px;
right: 3px;
width: 125px;
height: 125px;
background-color: red;
text-align: center;
}
#drive
</style>
</head>
<body>
<div id="character">
<div style="width: 44px; height: 22px; background-color: blue; margin: 3px;"></div>
</div>
<div id="left" onclick="left()"></div>
<div id="right" onclick="right()"></div>
<!-- JS --!>
<script>
// variables go here
var pos;
var orient = 0;
// initialiser function
function init() {
Update();
}
//start the game
init();
// Updating function (this occurs when an action is completed)
function Update() {
}
// Character controller goes here
function left() {
orient -= 10;
document.getElementById("character").style.transform = "rotate(" + orient + "deg)";
Update();
}
function right() {
orient += 10;
document.getElementById("character").style.transform = "rotate(" + orient + "deg)";
Update();
}
function fwd() {
pos +=
document.getElementById("character").style.top = "1000px";
Update();
}
//functions go here
// oninput tags go here
</script>
</body>
</html>
If you also know how to make the code able to run, please tell me how to do so in the comments!
You can use transform: translate(X,Y).
Here, you have to calculate X and, Y based on rotation of CAR and, initial position. Also, you can have you own velocity and acceleration for it.
I am new to Javascript and CSS. I have a div that will contain an image. The below code, I pieced it together after watching some YouTube videos and going over some documentation, however I am sure that this is not the right code.
https://jsfiddle.net/0hp97a6k/
* {
margin: 0;
padding: 0;
}
body {
background-color: powderblue;
height: 2000px;
padding: 0 0;
}
div {
margin: 0;
}
.headerspace {
width: 100%;
height: 20px;
background-color: white;
}
.header {
width: 100%;
height: 300px;
background-color: maroon;
display: flex;
}
.logo {
width: 200px;
height: 200px;
background-color: red;
margin-top: 50px;
margin-left: 50px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="headerspace"></div>
<div class="header">
<div class="logo" id="logoid">
</div>
</div>
<script type="text/javascript">
let logo = document.getElementById("logoid");
window.addEventListener('scroll', function() {
var value = window.scrollY;
logo.style.marginleft = value * 0.5 + 'px';
})
</script>
</body>
</html>
How do I set the left margin based on scroll?
Also can scroll based properties be applied to two margins, say top and right at the same time?
marginleft should be marginLeft in your javascript
<script type="text/javascript">
let logo = document.getElementById("logoid");
window.addEventListener('scroll', function(){
var value = window.scrollY;
logo.style.marginLeft = value * 0.5 + 'px';
})
</script>
And then if you want to edit the left and top you can do the following
<script type="text/javascript">
let logo = document.getElementById("logoid");
window.addEventListener('scroll', function(){
var value = window.scrollY;
logo.style.marginLeft = value * 0.5 + 'px';
logo.style.marginTop = value * 0.5 + 'px';
})
</script>
To make sure the logo element goes back where it started you should edit the css like this
* {
margin: 0;
padding: 0;
}
body {
background-color: powderblue;
height: 2000px;
padding: 0 0;
}
div{
margin: 0;
}
.headerspace{
width: 100%;
height: 20px;
background-color: white;
}
.header{
width: 100%;
height: 300px;
background-color: maroon;
display: flex;
padding-top: 50px;
padding-left: 50px;
}
.logo{
width: 200px;
height: 200px;
background-color: red;
}
I have removed the margin from .logo because that will be overwritten and added those values as padding to the parent (.header)
I searched a lot and finding nothing on it. I want to make a progress bar with round corners.progress bar need to have shadow. All I did as of now is here :
$(".progress-bar").each(function(){
var bar = $(this).find(".bar");
var val = $(this).find("span");
var per = parseInt( val.text(), 10);
$({p:0}).animate({p:per}, {
duration: 3000,
easing: "swing",
step: function(p) {
bar.css({
transform: "rotate("+ (45+(p*1.8)) +"deg)"
});
val.text(p|0);
}
});
});
body{
background-color:#3F63D3;
}
.progress-bar{
position: relative;
margin: 4px;
float:left;
text-align: center;
}
.barOverflow{
position: relative;
overflow: hidden;
width: 150px; height: 70px;
margin-bottom: -14px;
}
.bar{
position: absolute;
top: 0; left: 0;
width: 150px; height: 150px;
border-radius: 50%;
box-sizing: border-box;
border: 15px solid gray;
border-bottom-color: white;
border-right-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress-bar">
<div class="barOverflow">
<div class="bar"></div>
</div>
<span>100</span>%
</div>
I want to make corners round and having shadow. below given image represent what actually i want. Shadow is missing because i don't know to draw. :
I have tried Progressbar.js also, but I don't have much knowledge about SVG. Any answer would be appreciated.
#jaromanda for suggestion of learning SVG.
Yes is looks very hard to achieve from border-radius. So i looked into SVG and find it pretty handy. Here is my snippet:
// progressbar.js#1.0.0 version is used
// Docs: http://progressbarjs.readthedocs.org/en/1.0.0/
var bar = new ProgressBar.SemiCircle(container, {
strokeWidth: 10,
color: 'red',
trailColor: '#eee',
trailWidth: 10,
easing: 'easeInOut',
duration: 1400,
svgStyle: null,
text: {
value: '',
alignToBottom: false
},
// Set default step function for all animate calls
step: (state, bar) => {
bar.path.setAttribute('stroke', state.color);
var value = Math.round(bar.value() * 100);
if (value === 0) {
bar.setText('');
} else {
bar.setText(value+"%");
}
bar.text.style.color = state.color;
}
});
bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';
bar.animate(0.45); // Number from 0.0 to 1.0
#container {
width: 200px;
height: 100px;
}
svg {
height: 120px;
width: 200px;
fill: none;
stroke: red;
stroke-width: 10;
stroke-linecap: round;
-webkit-filter: drop-shadow( -3px -2px 5px gray );
filter: drop-shadow( -3px -2px 5px gray );
}
<script src="https://rawgit.com/kimmobrunfeldt/progressbar.js/1.0.0/dist/progressbar.js"></script>
<link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600,800,900" rel="stylesheet" type="text/css">
<div id="container"></div>
I want to suggest some stupid but quick solution since you're already using position: absolute. You can add background color to the circles when your animation starts.
html:
<div class="progress-bar">
<div class="left"></div>
<div class="right"><div class="back"></div></div>
<div class="barOverflow">
<div class="bar"></div>
</div>
<span>0</span>%
</div>
css:
/** all your css here **/
body{
background-color:#3F63D3;
}
.progress-bar{
position: relative;
margin: 4px;
float: left;
text-align: center;
}
.barOverflow{
position: relative;
overflow: hidden;
width: 150px; height: 70px;
margin-bottom: -14px;
}
.bar{
position: absolute;
top: 0; left: 0;
width: 150px; height: 150px;
border-radius: 50%;
box-sizing: border-box;
border: 15px solid gray;
border-bottom-color: white;
border-right-color: white;
transform: rotate(45deg);
}
.progress-bar > .left {
position: absolute;
background: white;
width: 15px;
height: 15px;
border-radius: 50%;
left: 0;
bottom: -4px;
overflow: hidden;
}
.progress-bar > .right {
position: absolute;
background: white;
width: 15px;
height: 15px;
border-radius: 50%;
right: 0;
bottom: -4px;
overflow: hidden;
}
.back {
width: 15px;
height: 15px;
background: gray;
position: absolute;
}
jquery:
$(".progress-bar").each(function(){
var bar = $(this).find(".bar");
var val = $(this).find("span");
var per = parseInt( val.text(), 10);
var $right = $('.right');
var $back = $('.back');
$({p:0}).animate({p:per}, {
duration: 3000,
step: function(p) {
bar.css({
transform: "rotate("+ (45+(p*1.8)) +"deg)"
});
val.text(p|0);
}
}).delay( 200 );
if (per == 100) {
$back.delay( 2600 ).animate({'top': '18px'}, 200 );
}
if (per == 0) {
$('.left').css('background', 'gray');
}
});
https://jsfiddle.net/y86qs0a9/7/
Same as the answers above, I found it much easier to implement using SVG instead of pure CSS.
However I couldn't find a single simplistic implementation using only HTML and CSS, or at least with no libraries, no external scripts or no dependencies. I found that given the math that needs to be calculated to make the SVG transformations to represent the percentage, JS needs to be included (if someone knows how to achieve this with only HTML and CSS I'd love to learn how). But what the JS script does is not long or complex enough to justify the overhead of adding yet another dependency to my codebase.
The JS calculations are pretty easy once you read through. You need to calculate the coordinate for the end point of the gauge in the coordinate system of the SVG. so basic trig.
Most of the CSS is not even needed and I added just to style it and to make it pretty. You can add shadow or gradients same as you could with any HTML pure shape.
Here is the codePen https://codepen.io/naticaceres/pen/QWQeyGX
You can easily tinker with this code to achieve any kind of shape of circular gauge (full circle, lower half of the semi-circle, or any variation including ellipsis).
Hope this is helpful.
// # Thanks to mxle for the first rounded corner CSS only solution https://stackoverflow.com/a/42478006/4709712
// # Thanks to Aniket Naik for the styling and the basic idea and implementation https://codepen.io/naikus/pen/BzZoLL
// - Aniket Naik has a library, linked to that codepen you should check out if you don't want to copy-paste or implement yourself
// the arc radius in the meter-value needs to stay the same, and must always be x=y, not lower than the possible circle that can connect the two points (otherwise the ratio is not preserved and the curvature doesn't match the background path).
// to style the gauge, make it bigger or smaller, play with its parent element and transform scale. don't edit width and height of SVG directly
function percentageInRadians(percentage) {
return percentage * (Math.PI / 100);
}
function setGaugeValue(gaugeElement, percentage, color) {
const gaugeRadius = 65;
const startingY = 70;
const startingX = 10;
const zeroBasedY = gaugeRadius * Math.sin(percentageInRadians(percentage));
const y = -zeroBasedY + startingY;
const zeroBasedX = gaugeRadius * Math.cos(percentageInRadians(percentage));
const x = -zeroBasedX + gaugeRadius + startingX;
// # uncomment this to log the calculations of the coordinates for the final point of the gauge value path.
//console.log(
// `percentage: ${percentage}, zeroBasedY: ${zeroBasedY}, y: ${y}, zeroBasedX: ${zeroBasedX}, x: ${x}`
//);
gaugeElement.innerHTML = `<path d="M ${startingX} ${startingY}
A ${gaugeRadius} ${gaugeRadius} 0 0 1 ${x} ${y}
" stroke="${color}" stroke-width="10" stroke-linecap="round" />`;
}
percentageChangedEvent = (gauge, newPercentage, color) => {
const percentage =
newPercentage > 100 ? 100 : newPercentage < 0 ? 0 : newPercentage;
setGaugeValue(gauge, percentage, color);
};
function initialGaugeSetup(gaugeElementId, inputId, meterColor, initialValue) {
const gaugeElement = document.getElementById(gaugeElementId);
setGaugeValue(gaugeElement, 0, meterColor);
const inputElement = document.getElementById(inputId);
inputElement.value = initialValue;
setGaugeValue(gaugeElement, initialValue, meterColor);
inputElement.addEventListener("change", (event) =>
percentageChangedEvent(gaugeElement, event.target.value, meterColor)
);
}
// Gauge Initial Config
initialGaugeSetup(
"svg-graph-meter-value",
"svg-gauge-percentage-2",
"rgb(227 127 215)",
40
);
body {
background-color: rgba(0, 0, 0, 0.8);
color: #999;
font-family: Hevletica, sans-serif;
}
/* SVG Path implementation */
.svg-container {
margin: 20px auto 10px;
height: 80px;
width: 150px;
}
svg {
fill: transparent;
}
.input-percent-container {
text-align: center;
}
.input-percent-container>* {
display: inline;
}
input {
text-align: right;
width: 40px;
margin: auto;
background-color: #5d5d5d;
color: white;
border-radius: 6px;
border: black;
}
<div class="svg-container">
<svg width="150" height="80" xmlns="http://www.w3.org/2000/svg">
<path d="M 10 70
A 65 65 0 1 1 140 70
" stroke="grey" stroke-width="3" stroke-linecap="round" />
<g id="svg-graph-meter-value">
</g>
</svg>
</div>
<div class="input-percent-container"><input id="svg-gauge-percentage-2" /><span>%<span/></div>
Trying to move a position:fixed div on scroll by changing the top: css value in javascript. The div won't move though, not sure why.
html:
<div id="red">
<div id="blue"></div>
</div>
css:
#red {
position: relative;
float: left;
width: 100%;
height: 1000px;
background: rgba(255, 0, 0, 0.2);
border: solid 2px #f0f;
}
#blue {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 50vh;
background: rgba(0, 0, 255, 0.2);
border: solid 2px #0ff;
}
js:
window.addEventListener('scroll', function() {
var yPos = -(Math.floor(document.body.scrollTop / 10));
//console.log("yPos = " + yPos); //output is correct
document.getElementById('blue').style.top = yPos + 'px';
//document.getElementById('blue').setAttribute('top',yPos); //also tried this
});
https://jsfiddle.net/akzx43yL/
Why isn't the top css value changing and how can I get it to do so? No jquery please.
Two things:
Instead of document.documentElement.scrollTop, you should use window.pageYOffset (scrollTop doesn't play nicely in Chrome).
You need to add a unit of measurement after you update top; values other than 0 should have px appened to them.
This can be seen in the following:
window.addEventListener('scroll', function() {
var yPos = -(Math.floor(window.pageYOffset / 10));
document.getElementById('blue').style.top = yPos + "px";
// Optionally log the `top` value
//console.log(document.getElementById('blue').style.top);
});
#red {
position: relative;
float: left;
width: 100%;
height: 1000px;
background: rgba(255, 0, 0, 0.2);
border: solid 2px #f0f;
}
#blue {
position: absolute;
top: -10px;
left: 0;
width: 100vw;
height: 50vh;
background: rgba(0, 0, 255, 0.2);
border: solid 2px #0ff;
}
<div id="red">
<div id="blue"></div>
</div>
Hope this helps! :)
If you check your console, you will be see your console.log("yPos = " + yPos) is always 0 you most update your code as follow:
window.addEventListener('scroll', function() {
var yPos = -(Math.floor(document.documentElement.scrollTop / 10));
console.log("yPos = " + yPos);
document.getElementById('blue').style.top = yPos + "px";
});
Tip:
Ways to get srollTop (pure js):
var top = window.pageYOffset || document.documentElement.scrollTop;
This is what worked for me:
document.getElementById('blue').style.top = yPos + "px";
my name is Daniel and i'm making a drinking game for school, I want to let a div to become visible when the bar is full (so you know when the bar is full and you win the game), but i have no idea how to do this...
Could you help me out?
HTML:
<div class="col-xs-12" style="display: none;" id="hiddenText">
<div id="bar" class="animated bounceInUp">
</div>
</div>
CCS:
#bar {
background-color: #F8F8F8 ;
width: 340px;
height: 24px;
margin-right: auto;
margin-left: auto;
}
#bar > div {
margin-top: 30px;
max-width: 334px;
width: 100%;
height: 16px;
background: #9d3349;
position: relative;
top: 4px;
left: 3px;
transition: width 500ms;
}
JS:
var jumpsize = 2.77, // %
body = $("body");
(container = $("#bar")), (bar = container.children("div")), (topcnt = function(
px
) {
return 100 * px / container.width();
}), (set = function(pcnt) {
bar.css({ width: pcnt + "%" });
});
body
.on("click", ".card1, .card2, .card3, .card4", function() {
set(topcnt(bar.width()) + jumpsize);
});
set(0);
The reason its not working is because u forgot to put the if statement in the function u run on click. So the if statement only runs once. and on first load it will result in false. To fix your code move the if statement in your Body.onclick.
Next time it would be smart to include the full javascript that is relative to the function.
By looking at the online code i was able to find the issue.
Hope this resolves your issues.
~Yannick
When you hit your target you need to remove the CSS styling of Display = none.
W3 schools page here for some helpful info to help you learn some more.
https://www.w3schools.com/jsref/prop_style_display.asp
The line below inserted when you reach your goal to display should make the bar appear.
document.getElementById("hiddenText").style.display = "block";
I'm not sure you want this, but try this:
var jumpsize = 2.77, // %
width = 0,
body = $("body");
(container = $("#bar")), (bar = container.children("div")), (topcnt = function(
px
) {
return 100 * px / container.width();
}), (set = function(pcnt) {
bar.css({ width: pcnt + "%" });
if(pcnt >= 100) {$('#hiddenText').show();}
});
body
.on("click", ".card1, .card2, .card3, .card4", function() {
width += jumpsize;
set(topcnt(width));
});
set(0);
#bar {
background-color: #F8F8F8 ;
width: 340px;
height: 24px;
margin-right: auto;
margin-left: auto;
}
#bar > div {
margin-top: 30px;
max-width: 334px;
width: 100%;
height: 16px;
background: #9d3349;
position: relative;
top: 4px;
left: 3px;
transition: width 500ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-xs-12" style="display: none;" id="hiddenText">
<div id="bar" class="animated bounceInUp">
<div></div>
</div>
</div>
<button class="card1">click me</button>
You are using jQuery so quicker will be:
$('#hiddenText').show();
Edit:
sooo
if($('#bar').children('div').width() >= 334){
$('#hiddenText').show();
}
As You can see the div with progress bar can have max od 334 px. Check if it has it and if yes then show the text. Put this in that click event
Seems to me like you're overcomplicating things a little bit with the percentage calculations. I would just add a variable for the width of the bar that starts at 0 and increase this with the jumpsize on every click. Once this new variable goes over or equals 100 you show the hidden div.
HTML
<div class="col-xs-12" id="hiddenText">
<div id="bar" class="animated bounceInUp">
<div></div>
</div>
</div>
<button id="button">Click me</button>
<div id="showOnComplete">Show me when the bar is full!</div>
CSS
#bar {
width: 340px;
height: 24px;
padding: 4px 3px;
margin: 30px auto 0;
background-color: #f8f8f8;
}
#bar > div {
position: relative;
float: left;
height: 100%;
width: 0;
max-width: 100%;
background: #9d3349;
transition: width 500ms;
}
#button {
margin: 20px auto;
display: block;
}
#showOnComplete {
width: 400px;
padding: 20px;
margin: 20px auto;
background: blue;
color: #fff;
text-align: center;
display: none;
}
JS
(function($) {
var jumpSize = 20, //increased this for the fiddle, so we don't have to click as often
barWidth = 0,
$bar,
$showOnComplete;
$(function() {
$bar = $("#bar").children("div");
$showOnComplete = $("#showOnComplete");
$(document).on("click", "#button", function() {
barWidth += jumpSize;
$bar.width(barWidth + "%");
if (barWidth >= 100) $showOnComplete.show(); //optionally add a setTimeout of 500 here to account for the final transition of the bar
});
});
})(jQuery);
I've made a fiddle for it here.