Unable to reset JavaScript bar graph - javascript

I have a bar graph created in JavaScript to display values using colors. I am having trouble resetting the bar graph. Basically what needs to happen is when the "reset" button is clicked, all bars clear values and reset to "0". Then the button needs to give the option to "Generate" and the previous values are shown again. Also, this is my first time using constant velocity to ease the bars up and down as the button is clicked to give it a little flair. Not sure what I am missing to have the data clear and be set to zero on the bottom line of the graph while using constant velocity to make it ease down and when button is clicked to restore the values to previous state. Any help is appreciated. Here is the code so far:
HTML
/*
* Some base values.
*/
var millisecondsPerFrame = 30;
/*
* Helper function for managing button event handlers.
*/
var setupButton = function(button, label, onclickHandler) {
button.value = label;
button.onclick = onclickHandler;
button.disabled = false;
};
var startConstantVelocityAnimation = function() {
// Grab the desired velocity.
var velocity = parseFloat(document.getElementById("chart").value);
// Grab the object to animate, and initialize if necessary.
var colors = document.getElementById("colors");
chart.style.bottom = chart.style.bottom || "0px";
// Start animating.
var intervalID = setInterval(function() {
var newBottom = parseInt(box.style.bottom) + velocity;
if ((newBottom < 0) || (newBottom > maxBottom)) {
velocity = -velocity;
} else {
chart.style.bottom = newBottom + "px";
}
}, millisecondsPerFrame);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"), "Reset", function() {
clearInterval(intervalID);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"),
"Generate", startConstantVelocityAnimation);
});
};
window.onload = function() {
// Set up the initial event handlers.
document.getElementById("Reset").onclick = startConstantVelocityAnimation;
};
**
* Graph JS Code ** *
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 = 48.30;
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); // keeps chart inside wrapper div
};
#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 {
margin-right: auto;
margin-left: auto;
width: 85%;
text-align: center;
font-size: 10px;
padding: 5px;
}
/*Chart Color Legend*/
.legend .legend-scale ul {
margin: 0;
padding: 0;
float: left;
list-style: none;
}
.legend .legend-scale ul li {
display: block;
float: left;
width: 50px;
margin-bottom: 6px;
text-align: center;
font-size: 80%;
list-style: none;
}
.legend ul.legend-labels li span {
display: block;
float: left;
height: 15px;
width: 50px;
}
.legend a {
color: #777;
}
.subs {
font-size: 10px;
font-style: italic;
padding: 5px;
text-align: center;
}
.reset-button {
text-align: right;
padding-top: 2px;
padding-right: 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tissue: Titan Issue Tracking</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="S Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
<script src="js/animation.js"></script>
</head>
<body>
<div id="wrapper">
<h2>TISSUE: Sales Subscription Dashboard</h2>
<div class="topnav">
Home
Tracker Login
</div>
<div>
<div class="legend">
<div class="legend-scale">
<div class="reset-button">
<input type="button" value="Reset Graph" id="Reset">
</div>
<ul class="legend-labels">
<li><span></span>40</li>
<li><span></span>10</li>
<li><span></span>100</li>
<li><span></span>65</li>
<li><span></span>75</li>
<li><span></span>120</li>
<li><span></span>121</li>
<li><span></span>175</li>
<li><span></span>220</li>
<li><span></span>275</li>
<li><span></span>300</li>
<li><span></span>15</li>
</ul>
</div>
</div>
<div class="legend">
<div class="legend-scale">
<ul class="legend-labels">
<li><span style='background:red;'></span>Jan</li>
<li><span style='background:blue;'></span>Feb</li>
<li><span style='background:green;'></span>March</li>
<li><span style='background:black;'></span>Apr</li>
<li><span style='background:yellow;'></span>May</li>
<li><span style='background:purple;'></span>June</li>
<li><span style='background:grey;'></span>July</li>
<li><span style='background:orange;'></span>Aug</li>
<li><span style='background:olive;'></span>Sept</li>
<li><span style='background:maroon;'></span>Oct</li>
<li><span style='background:brown;'></span>Nov</li>
<li><span style='background:teal;'></span>Dec</li>
</ul>
</div>
</div>
<br><br><br><br>
<hr>
<div class="subs">***Subscribers in Thousands***</div>
<script src="js/subscriptions_graph.js"></script>
</div>
</div>
<div class="copyright">
Copyright © 2018 Titan Issue Tracker
</div>
</body>
</html>

Related

Accessible input elements without label [duplicate]

Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?
I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying #Wildhoney's code a bit and really like it.
function getVals(){
// Get slider values
var parent = this.parentNode;
var slides = parent.getElementsByTagName("input");
var slide1 = parseFloat( slides[0].value );
var slide2 = parseFloat( slides[1].value );
// Neither slider will clip the other, so make sure we determine which is larger
if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }
var displayElement = parent.getElementsByClassName("rangeValues")[0];
displayElement.innerHTML = slide1 + " - " + slide2;
}
window.onload = function(){
// Initialize Sliders
var sliderSections = document.getElementsByClassName("range-slider");
for( var x = 0; x < sliderSections.length; x++ ){
var sliders = sliderSections[x].getElementsByTagName("input");
for( var y = 0; y < sliders.length; y++ ){
if( sliders[y].type ==="range" ){
sliders[y].oninput = getVals;
// Manually trigger event first time to display values
sliders[y].oninput();
}
}
}
}
section.range-slider {
position: relative;
width: 200px;
height: 35px;
text-align: center;
}
section.range-slider input {
pointer-events: none;
position: absolute;
overflow: hidden;
left: 0;
top: 15px;
width: 200px;
outline: none;
height: 18px;
margin: 0;
padding: 0;
}
section.range-slider input::-webkit-slider-thumb {
pointer-events: all;
position: relative;
z-index: 1;
outline: 0;
}
section.range-slider input::-moz-range-thumb {
pointer-events: all;
position: relative;
z-index: 10;
-moz-appearance: none;
width: 9px;
}
section.range-slider input::-moz-range-track {
position: relative;
z-index: -1;
background-color: rgba(0, 0, 0, 1);
border: 0;
}
section.range-slider input:last-of-type::-moz-range-track {
-moz-appearance: none;
background: none transparent;
border: 0;
}
section.range-slider input[type=range]::-moz-focus-outer {
border: 0;
}
<!-- This block can be reused as many times as needed -->
<section class="range-slider">
<span class="rangeValues"></span>
<input value="5" min="0" max="15" step="0.5" type="range">
<input value="10" min="0" max="15" step="0.5" type="range">
</section>
No, the HTML5 range input only accepts one input. I would recommend you to use something like the jQuery UI range slider for that task.
Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.
It's also free, open source and can be used in commercial projects without restrictions.
Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:
<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">
<!-- In <body> -->
<script src="nouislider.min.js"></script>
Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.
HTML:
<div id="slider">
</div>
JS:
var slider = document.getElementById('slider');
noUiSlider.create(slider, {
start: [20, 80],
connect: true,
range: {
'min': 0,
'max': 100
}
});
Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in #Garys) solution.
Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.
It uses JQuery but a vanillajs version is no magic though.
#Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.
(function() {
function addSeparator(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
function rangeInputChangeEventHandler(e){
var rangeGroup = $(this).attr('name'),
minBtn = $(this).parent().children('.min'),
maxBtn = $(this).parent().children('.max'),
range_min = $(this).parent().children('.range_min'),
range_max = $(this).parent().children('.range_max'),
minVal = parseInt($(minBtn).val()),
maxVal = parseInt($(maxBtn).val()),
origin = $(this).context.className;
if(origin === 'min' && minVal > maxVal-5){
$(minBtn).val(maxVal-5);
}
var minVal = parseInt($(minBtn).val());
$(range_min).html(addSeparator(minVal*1000) + ' €');
if(origin === 'max' && maxVal-5 < minVal){
$(maxBtn).val(5+ minVal);
}
var maxVal = parseInt($(maxBtn).val());
$(range_max).html(addSeparator(maxVal*1000) + ' €');
}
$('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
width: 210px;
height: 30px;
overflow: hidden;
cursor: pointer;
outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
background: none;
}
input[type='range']::-webkit-slider-runnable-track {
width: 200px;
height: 1px;
background: #003D7C;
}
input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
background: none;
}
input[type='range']::-webkit-slider-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
input[type='range']:nth-child(1)::-webkit-slider-thumb{
z-index: 2;
}
.rangeslider{
position: relative;
height: 60px;
width: 210px;
display: inline-block;
margin-top: -5px;
margin-left: 20px;
}
.rangeslider input{
position: absolute;
}
.rangeslider{
position: absolute;
}
.rangeslider span{
position: absolute;
margin-top: 30px;
left: 0;
}
.rangeslider .right{
position: relative;
float: right;
margin-right: -5px;
}
/* Proof of concept for Firefox */
#-moz-document url-prefix() {
.rangeslider::before{
content:'';
width:100%;
height:2px;
background: #003D7C;
display:block;
position: relative;
top:16px;
}
input[type='range']:nth-child(1){
position:absolute;
top:35px !important;
overflow:visible !important;
height:0;
}
input[type='range']:nth-child(2){
position:absolute;
top:35px !important;
overflow:visible !important;
height:0;
}
input[type='range']::-moz-range-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
input[type='range']:nth-child(1)::-moz-range-thumb {
transform: translateY(-20px);
}
input[type='range']:nth-child(2)::-moz-range-thumb {
transform: translateY(-20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
<input class="min" name="range_1" type="range" min="1" max="100" value="10" />
<input class="max" name="range_1" type="range" min="1" max="100" value="90" />
<span class="range_min light left">10.000 €</span>
<span class="range_max light right">90.000 €</span>
</div>
Actually I used my script in html directly. But in javascript when you add oninput event listener for this event it gives the data automatically.You just need to assign the value as per your requirement.
[slider] {
width: 300px;
position: relative;
height: 5px;
margin: 45px 0 10px 0;
}
[slider] > div {
position: absolute;
left: 13px;
right: 15px;
height: 5px;
}
[slider] > div > [inverse-left] {
position: absolute;
left: 0;
height: 5px;
border-radius: 10px;
background-color: #CCC;
margin: 0 7px;
}
[slider] > div > [inverse-right] {
position: absolute;
right: 0;
height: 5px;
border-radius: 10px;
background-color: #CCC;
margin: 0 7px;
}
[slider] > div > [range] {
position: absolute;
left: 0;
height: 5px;
border-radius: 14px;
background-color: #d02128;
}
[slider] > div > [thumb] {
position: absolute;
top: -7px;
z-index: 2;
height: 20px;
width: 20px;
text-align: left;
margin-left: -11px;
cursor: pointer;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.4);
background-color: #FFF;
border-radius: 50%;
outline: none;
}
[slider] > input[type=range] {
position: absolute;
pointer-events: none;
-webkit-appearance: none;
z-index: 3;
height: 14px;
top: -2px;
width: 100%;
opacity: 0;
}
div[slider] > input[type=range]:focus::-webkit-slider-runnable-track {
background: transparent;
border: transparent;
}
div[slider] > input[type=range]:focus {
outline: none;
}
div[slider] > input[type=range]::-webkit-slider-thumb {
pointer-events: all;
width: 28px;
height: 28px;
border-radius: 0px;
border: 0 none;
background: red;
-webkit-appearance: none;
}
div[slider] > input[type=range]::-ms-fill-lower {
background: transparent;
border: 0 none;
}
div[slider] > input[type=range]::-ms-fill-upper {
background: transparent;
border: 0 none;
}
div[slider] > input[type=range]::-ms-tooltip {
display: none;
}
[slider] > div > [sign] {
opacity: 0;
position: absolute;
margin-left: -11px;
top: -39px;
z-index:3;
background-color: #d02128;
color: #fff;
width: 28px;
height: 28px;
border-radius: 28px;
-webkit-border-radius: 28px;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
text-align: center;
}
[slider] > div > [sign]:after {
position: absolute;
content: '';
left: 0;
border-radius: 16px;
top: 19px;
border-left: 14px solid transparent;
border-right: 14px solid transparent;
border-top-width: 16px;
border-top-style: solid;
border-top-color: #d02128;
}
[slider] > div > [sign] > span {
font-size: 12px;
font-weight: 700;
line-height: 28px;
}
[slider]:hover > div > [sign] {
opacity: 1;
}
<div slider id="slider-distance">
<div>
<div inverse-left style="width:70%;"></div>
<div inverse-right style="width:70%;"></div>
<div range style="left:0%;right:0%;"></div>
<span thumb style="left:0%;"></span>
<span thumb style="left:100%;"></span>
<div sign style="left:0%;">
<span id="value">0</span>
</div>
<div sign style="left:100%;">
<span id="value">100</span>
</div>
</div>
<input type="range" value="0" max="100" min="0" step="1" oninput="
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
let value = (this.value/parseInt(this.max))*100
var children = this.parentNode.childNodes[1].childNodes;
children[1].style.width=value+'%';
children[5].style.left=value+'%';
children[7].style.left=value+'%';children[11].style.left=value+'%';
children[11].childNodes[1].innerHTML=this.value;" />
<input type="range" value="100" max="100" min="0" step="1" oninput="
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
let value = (this.value/parseInt(this.max))*100
var children = this.parentNode.childNodes[1].childNodes;
children[3].style.width=(100-value)+'%';
children[5].style.right=(100-value)+'%';
children[9].style.left=value+'%';children[13].style.left=value+'%';
children[13].childNodes[1].innerHTML=this.value;" />
</div>
The question was: "Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?"
In 2020 it is possible to create a fully accessible, native, non-jquery HTML5 slider with two thumbs for price ranges. If found this posted after I already created this solution and I thought that it would be nice to share my implementation here.
This implementation has been tested on mobile Chrome and Firefox (Android) and Chrome and Firefox (Linux). I am not sure about other platforms, but it should be quite good. I would love to get your feedback and improve this solution.
This solution allows multiple instances on one page and it consists of just two inputs (each) with descriptive labels for screen readers. You can set the thumb size in the amount of grid labels. Also, you can use touch, keyboard and mouse to interact with the slider. The value is updated during adjustment, due to the 'on input' event listener.
My first approach was to overlay the sliders and clip them. However, that resulted in complex code with a lot of browser dependencies. Then I recreated the solution with two sliders that were 'inline'. This is the solution you will find below.
var thumbsize = 14;
function draw(slider,splitvalue) {
/* set function vars */
var min = slider.querySelector('.min');
var max = slider.querySelector('.max');
var lower = slider.querySelector('.lower');
var upper = slider.querySelector('.upper');
var legend = slider.querySelector('.legend');
var thumbsize = parseInt(slider.getAttribute('data-thumbsize'));
var rangewidth = parseInt(slider.getAttribute('data-rangewidth'));
var rangemin = parseInt(slider.getAttribute('data-rangemin'));
var rangemax = parseInt(slider.getAttribute('data-rangemax'));
/* set min and max attributes */
min.setAttribute('max',splitvalue);
max.setAttribute('min',splitvalue);
/* set css */
min.style.width = parseInt(thumbsize + ((splitvalue - rangemin)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
max.style.width = parseInt(thumbsize + ((rangemax - splitvalue)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
min.style.left = '0px';
max.style.left = parseInt(min.style.width)+'px';
min.style.top = lower.offsetHeight+'px';
max.style.top = lower.offsetHeight+'px';
legend.style.marginTop = min.offsetHeight+'px';
slider.style.height = (lower.offsetHeight + min.offsetHeight + legend.offsetHeight)+'px';
/* correct for 1 off at the end */
if(max.value>(rangemax - 1)) max.setAttribute('data-value',rangemax);
/* write value and labels */
max.value = max.getAttribute('data-value');
min.value = min.getAttribute('data-value');
lower.innerHTML = min.getAttribute('data-value');
upper.innerHTML = max.getAttribute('data-value');
}
function init(slider) {
/* set function vars */
var min = slider.querySelector('.min');
var max = slider.querySelector('.max');
var rangemin = parseInt(min.getAttribute('min'));
var rangemax = parseInt(max.getAttribute('max'));
var avgvalue = (rangemin + rangemax)/2;
var legendnum = slider.getAttribute('data-legendnum');
/* set data-values */
min.setAttribute('data-value',rangemin);
max.setAttribute('data-value',rangemax);
/* set data vars */
slider.setAttribute('data-rangemin',rangemin);
slider.setAttribute('data-rangemax',rangemax);
slider.setAttribute('data-thumbsize',thumbsize);
slider.setAttribute('data-rangewidth',slider.offsetWidth);
/* write labels */
var lower = document.createElement('span');
var upper = document.createElement('span');
lower.classList.add('lower','value');
upper.classList.add('upper','value');
lower.appendChild(document.createTextNode(rangemin));
upper.appendChild(document.createTextNode(rangemax));
slider.insertBefore(lower,min.previousElementSibling);
slider.insertBefore(upper,min.previousElementSibling);
/* write legend */
var legend = document.createElement('div');
legend.classList.add('legend');
var legendvalues = [];
for (var i = 0; i < legendnum; i++) {
legendvalues[i] = document.createElement('div');
var val = Math.round(rangemin+(i/(legendnum-1))*(rangemax - rangemin));
legendvalues[i].appendChild(document.createTextNode(val));
legend.appendChild(legendvalues[i]);
}
slider.appendChild(legend);
/* draw */
draw(slider,avgvalue);
/* events */
min.addEventListener("input", function() {update(min);});
max.addEventListener("input", function() {update(max);});
}
function update(el){
/* set function vars */
var slider = el.parentElement;
var min = slider.querySelector('#min');
var max = slider.querySelector('#max');
var minvalue = Math.floor(min.value);
var maxvalue = Math.floor(max.value);
/* set inactive values before draw */
min.setAttribute('data-value',minvalue);
max.setAttribute('data-value',maxvalue);
var avgvalue = (minvalue + maxvalue)/2;
/* draw */
draw(slider,avgvalue);
}
var sliders = document.querySelectorAll('.min-max-slider');
sliders.forEach( function(slider) {
init(slider);
});
* {padding: 0; margin: 0;}
body {padding: 40px;}
.min-max-slider {position: relative; width: 200px; text-align: center; margin-bottom: 50px;}
.min-max-slider > label {display: none;}
span.value {height: 1.7em; font-weight: bold; display: inline-block;}
span.value.lower::before {content: "€"; display: inline-block;}
span.value.upper::before {content: "- €"; display: inline-block; margin-left: 0.4em;}
.min-max-slider > .legend {display: flex; justify-content: space-between;}
.min-max-slider > .legend > * {font-size: small; opacity: 0.25;}
.min-max-slider > input {cursor: pointer; position: absolute;}
/* webkit specific styling */
.min-max-slider > input {
-webkit-appearance: none;
outline: none!important;
background: transparent;
background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}
.min-max-slider > input::-webkit-slider-thumb {
-webkit-appearance: none; /* Override default look */
appearance: none;
width: 14px; /* Set a specific slider handle width */
height: 14px; /* Slider handle height */
background: #eee; /* Green background */
cursor: pointer; /* Cursor on hover */
border: 1px solid gray;
border-radius: 100%;
}
.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
<div class="min-max-slider" data-legendnum="2">
<label for="min">Minimum price</label>
<input id="min" class="min" name="min" type="range" step="1" min="0" max="3000" />
<label for="max">Maximum price</label>
<input id="max" class="max" name="max" type="range" step="1" min="0" max="3000" />
</div>
Note that you should keep the step size to 1 to prevent the values to change due to redraws/redraw bugs.
View online at: https://codepen.io/joosts/pen/rNLdxvK
2022 - Accessible solution - 30 second solution to implement
This solution builds off of this answer by #JoostS. Accessibility is something none of the answers have focused on and that is a problem, so I built off of the above answer by making it more accessible & extensible since it had some flaws.
Usage is very simple:
Use the CDN or host the script locally: https://cdn.jsdelivr.net/gh/maxshuty/accessible-web-components/dist/simpleRange.min.js
Add this element to your template or HTML: <range-selector min-range="0" max-range="1000" />
Hook into it by listening for the range-changed event (or whatever event-name-to-emit-on-change you pass in)
That's it. View the full demo here. You can easily customize it by simply applying attributes like inputs-for-labels to use inputs instead of labels, slider-color to adjust the color, and so much more!
Here is a fiddle:
window.addEventListener('range-changed', (e) => {console.log(`Range changed for: ${e.detail.sliderId}. Min/Max range values are available in this object too`)})
<script src="https://cdn.jsdelivr.net/gh/maxshuty/accessible-web-components#latest/dist/simpleRange.min.js"></script>
<div>
<range-selector
id="rangeSelector1"
min-label="Minimum"
max-label="Maximum"
min-range="1000"
max-range="2022"
number-of-legend-items-to-show="6"
/>
</div>
<div>
<range-selector
id="rangeSelector1"
min-label="Minimum"
max-label="Maximum"
min-range="1"
max-range="500"
number-of-legend-items-to-show="3"
inputs-for-labels
/>
</div>
<div>
<range-selector
id="rangeSelector2"
min-label="Minimum"
max-label="Maximum"
min-range="1000"
max-range="2022"
number-of-legend-items-to-show="3"
slider-color="#6b5b95"
/>
</div>
<div>
<range-selector
id="rangeSelector3"
min-label="Minimum"
max-label="Maximum"
min-range="1000"
max-range="2022"
hide-label
hide-legend
/>
</div>
I decided to address the issues of the linked answer like the labels using display: none (bad for a11y), no visual focus on the slider, etc., and improve the code by cleaning up event listeners and making it much more dynamic and extensible.
I created this tiny library with many options to customize colors, event names, easily hook into it, make the accessible labels i18n capable and much more. Here it is in a fiddle if you want to play around.
You can easily customize the number of legend items it shows, hide or show the labels and legend, and customize the colors of everything, including the focus color like this.
Example using several of the props:
<range-selector
min-label="i18n Minimum Range"
max-label="i18n Maximum Range"
min-range="5"
max-range="555"
number-of-legend-items-to-show="6"
event-name-to-emit-on-change="my-custom-range-changed-event"
slider-color="orange"
circle-color="#f7cac9"
circle-border-color="#083535"
circle-focus-border-color="#3ec400"
/>
Then in your script:
window.addEventListener('my-custom-range-changed-event', (e) => { const data = e.detail; });
Finally if you see that this is missing something that you need I made it very easy to customize this library.
Simply copy this file and at the top you can see cssHelpers and constants objects that contain most of the variables you would likely want to further customize.
Since I built this with a Native Web Component I have taken advantage of disconnectedCallback and other hooks to clean up event listeners and set things up.
Here is a reusable double range slider implementation, base on tutorial Double Range Slider by Coding Artist
near native UI, Chrome/Firefox/Safari compatible
API EventTarget based, with change/input events, minGap/maxGap properties
let $ = (s, c = document) => c.querySelector(s);
let $$ = (s, c = document) => Array.prototype.slice.call(c.querySelectorAll(s));
class DoubleRangeSlider extends EventTarget {
#minGap = 0;
#maxGap = Number.MAX_SAFE_INTEGER;
#inputs;
style = {
trackColor: '#dadae5',
rangeColor: '#3264fe',
};
constructor(container){
super();
let inputs = $$('input[type="range"]', container);
if(inputs.length !== 2){
throw new RangeError('2 range inputs expected');
}
let [input1, input2] = inputs;
if(input1.min >= input1.max || input2.min >= input2.max){
throw new RangeError('range min should be less than max');
}
if(input1.max > input2.max || input1.min > input2.min){
throw new RangeError('input1\'s max/min should not be greater than input2\'s max/min');
}
this.#inputs = inputs;
let sliderTrack = $('.slider-track', container);
let lastValue1 = input1.value;
input1.addEventListener('input', (e) => {
let value1 = +input1.value;
let value2 = +input2.value;
let minGap = this.#minGap;
let maxGap = this.#maxGap;
let gap = value2 - value1;
let newValue1 = value1;
if(gap < minGap){
newValue1 = value2 - minGap;
}else if(gap > maxGap){
newValue1 = value2 - maxGap;
}
input1.value = newValue1;
if(input1.value !== lastValue1){
lastValue1 = input1.value;
passEvent(e);
fillColor();
}
});
let lastValue2 = input2.value;
input2.addEventListener('input', (e) => {
let value1 = +input1.value;
let value2 = +input2.value;
let minGap = this.#minGap;
let maxGap = this.#maxGap;
let gap = value2 - value1;
let newValue2 = value2;
if(gap < minGap){
newValue2 = value1 + minGap;
}else if(gap > maxGap){
newValue2 = value1 + maxGap;
}
input2.value = newValue2;
if(input2.value !== lastValue2){
lastValue2 = input2.value;
passEvent(e);
fillColor();
}
});
let passEvent = (e) => {
this.dispatchEvent(new e.constructor(e.type, e));
};
input1.addEventListener('change', passEvent);
input2.addEventListener('change', passEvent);
let fillColor = () => {
let overallMax = +input2.max;
let overallMin = +input1.min;
let overallRange = overallMax - overallMin;
let left1 = ((input1.value - overallMin) / overallRange * 100) + '%';
let left2 = ((input2.value - overallMin) / overallRange * 100) + '%';
let {trackColor, rangeColor} = this.style;
sliderTrack.style.background = `linear-gradient(to right, ${trackColor} ${left1}, ${rangeColor} ${left1}, ${rangeColor} ${left2}, ${trackColor} ${left2})`;
};
let init = () => {
let overallMax = +input2.max;
let overallMin = +input1.min;
let overallRange = overallMax - overallMin;
let range1 = input1.max - overallMin;
let range2 = overallMax - input2.min;
input1.style.left = '0px';
input1.style.width = (range1 / overallRange * 100) + '%';
input2.style.right = '0px';
input2.style.width = (range2 / overallRange * 100) + '%';
fillColor();
};
init();
}
get minGap(){
return this.#minGap;
}
set minGap(v){
this.#minGap = v;
}
get maxGap(){
return this.#maxGap;
}
set maxGap(v){
this.#maxGap = v;
}
get values(){
return this.#inputs.map((el) => el.value);
}
set values(values){
if(values.length !== 2 || !values.every(isFinite))
throw new RangeError();
let [input1, input2] = this.#inputs;
let [value1, value2] = values;
if(value1 > input1.max || value1 < input1.min)
throw new RangeError('invalid value for input1');
if(value2 > input2.max || value2 < input2.min)
throw new RangeError('invalid value for input2');
input1.value = value1;
input2.value = value2;
}
get inputs(){
return this.#inputs;
}
get overallMin(){
return this.#inputs[0].min;
}
get overallMax(){
return this.#inputs[1].max;
}
}
function main(){
let container = $('.slider-container');
let slider = new DoubleRangeSlider(container);
slider.minGap = 30;
slider.maxGap = 70;
let inputs = $$('input[name="a"]');
let outputs = $$('output[name="a"]');
outputs[0].value = inputs[0].value;
outputs[1].value = inputs[1].value;
slider.addEventListener('input', (e) => {
let values = slider.values;
outputs[0].value = values[0];
outputs[1].value = values[1];
});
slider.addEventListener('change', (e) => {
let values = slider.values;
console.log('change', values);
outputs[0].value = values[0];
outputs[1].value = values[1];
});
}
document.addEventListener('DOMContentLoaded', main);
.slider-container {
display: inline-block;
position: relative;
width: 360px;
height: 28px;
}
.slider-track {
width: 100%;
height: 5px;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
border-radius: 5px;
}
.slider-container>input[type="range"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
width: 100%;
outline: none;
background-color: transparent;
pointer-events: none;
}
.slider-container>input[type="range"]::-webkit-slider-runnable-track {
-webkit-appearance: none;
height: 5px;
}
.slider-container>input[type="range"]::-moz-range-track {
-moz-appearance: none;
height: 5px;
}
.slider-container>input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
margin-top: -9px;
height: 1.7em;
width: 1.7em;
background-color: #3264fe;
cursor: pointer;
pointer-events: auto;
border-radius: 50%;
}
.slider-container>input[type="range"]::-moz-range-thumb {
-moz-appearance: none;
height: 1.7em;
width: 1.7em;
cursor: pointer;
border: none;
border-radius: 50%;
background-color: #3264fe;
pointer-events: auto;
}
.slider-container>input[type="range"]:active::-webkit-slider-thumb {
background-color: #ffffff;
border: 3px solid #3264fe;
}
<h3>Double Range Slider, Reusable Edition</h3>
<div class="slider-container">
<div class="slider-track"></div>
<input type="range" name="a" min="-130" max="-30" step="1" value="-100" autocomplete="off" />
<input type="range" name="a" min="-60" max="0" step="2" value="-30" autocomplete="off" />
</div>
<div>
<output name="a"></output> ~ <output name="a"></output>
</div>
<pre>
Changes:
1. allow different min/max/step for two inputs
2. new property 'maxGap'
3. added events 'input'/'change'
4. dropped IE/OldEdge support
</pre>
For those working with Vue, there is now Veeno available, based on noUiSlider. But it does not seem to be maintained anymore. :-(
This code covers following points
Dual slider using HTML, CSS, JS
I have modified this slider using embedded ruby so we can save previously applied values using params in rails.
<% left_width = params[:min].nil? ? 0 : ((params[:min].to_f/100000) * 100).to_i %>
<% left_value = params[:min].nil? ? '0' : params[:min] %>
<% right_width = params[:max].nil? ? 100 : ((params[:max].to_f/100000) * 100).to_i %>
<% right_value = params[:max].nil? ? '100000' : params[:max] %>
<div class="range-slider-outer">
<div slider id="slider-distance">
<div class="slider-inner">
<div inverse-left style="width:<%= left_width %>%;"></div>
<div inverse-right style="width:<%= 100 - right_width %>%;"></div>
<div range style="left:<%= left_width %>%;right:<%= 100 - right_width %>%;"></div>
<span thumb style="left:<%= left_width %>%;"></span>
<span thumb style="left:<%= right_width %>%;"></span>
<div sign style="">
Rs.<span id="value"><%= left_value.to_i %></span> to
</div>
<div sign style="">
Rs.<span id="value"><%= right_value.to_i %></span>
</div>
</div>
<input type="range" name="min" value=<%= left_value %> max="100000" min="0" step="100" oninput="
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
let value = (this.value/parseInt(this.max))*100
var children = this.parentNode.childNodes[1].childNodes;
children[1].style.width=value+'%';
children[5].style.left=value+'%';
children[7].style.left=value+'%';children[11].style.left=value+'%';
children[11].childNodes[1].innerHTML=this.value;" />
<input type="range" name="max" value=<%= right_value %> max="100000" min="0" step="100" oninput="
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
let value = (this.value/parseInt(this.max))*100
var children = this.parentNode.childNodes[1].childNodes;
children[3].style.width=(100-value)+'%';
children[5].style.right=(100-value)+'%';
children[9].style.left=value+'%';children[13].style.left=value+'%';
children[13].childNodes[1].innerHTML=this.value;" />
</div>
<div class="range-label">
<div>0</div>
<div>100000</div>
</div>
</div>
[slider] {
/*width: 300px;*/
position: relative;
height: 5px;
/*margin: 20px auto;*/
/* height: 100%; */
}
[slider] > div {
position: absolute;
left: 13px;
right: 15px;
height: 14px;
top: 5px;
}
[slider] > div > [inverse-left] {
position: absolute;
left: 0;
height: 14px;
border-radius: 3px;
background-color: #CCC;
/*margin: 0 7px;*/
margin: 0 -7px;
}
[slider] > div > [inverse-right] {
position: absolute;
right: 0;
height: 14px;
border-radius: 3px;
background-color: #CCC;
/*margin: 0 7px;*/
margin: 0 -7px;
}
[slider] > div > [range] {
position: absolute;
left: 0;
height: 14px;
border-radius: 14px;
background-color:#8950fc;
}
[slider] > div > [thumb] {
position: absolute;
top: -3px;
z-index: 2;
height: 20px;
width: 20px;
text-align: left;
margin-left: -11px;
cursor: pointer;
/* box-shadow: 0 3px 8px rgba(0, 0, 0, 0.4); */
background-color: #FFF;
/*border-radius: 50%;*/
border-radius:2px;
outline: none;
}
[slider] > input[type=range] {
position: absolute;
pointer-events: none;
-webkit-appearance: none;
z-index: 3;
height: 14px;
top: -2px;
width: 100%;
opacity: 0;
}
div[slider] > input[type=range]:focus::-webkit-slider-runnable-track {
background: transparent;
border: transparent;
}
div[slider] > input[type=range]:focus {
outline: none;
}
div[slider] > input[type=range]::-webkit-slider-thumb {
pointer-events: all;
width: 28px;
height: 28px;
border-radius: 0px;
border: 0 none;
background: red;
-webkit-appearance: none;
}
div[slider] > input[type=range]::-ms-fill-lower {
background: transparent;
border: 0 none;
}
div[slider] > input[type=range]::-ms-fill-upper {
background: transparent;
border: 0 none;
}
div[slider] > input[type=range]::-ms-tooltip {
display: none;
}
[slider] > div > [sign] {
/* opacity: 0;
position: absolute;
margin-left: -11px;
top: -39px;
z-index:3;
background-color:#1a243a;
color: #fff;
width: 28px;
height: 28px;
border-radius: 28px;
-webkit-border-radius: 28px;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
text-align: center;*/
color: #A5B2CB;
border-radius: 28px;
justify-content: center;
text-align: center;
display: inline-block;
margin-top: 12px;
font-size: 14px;
font-weight: bold;
}
.slider-inner{
text-align:center;
}
/*[slider] > div > [sign]:after {
position: absolute;
content: '';
left: 0;
border-radius: 16px;
top: 19px;
border-left: 14px solid transparent;
border-right: 14px solid transparent;
border-top-width: 16px;
border-top-style: solid;
border-top-color:#1a243a;
}*/
[slider] > div > [sign] > span {
font-size: 12px;
font-weight: 700;
line-height: 28px;
}
[slider]:hover > div > [sign] {
opacity: 1;
}
.range-label{
display: flex;
justify-content: space-between;
margin-top: 28px;
padding: 0px 5px;
}
.range-slider-outer{
width:calc(100% - 20px);
margin:auto;
margin-bottom: 10px;
margin-top: 10px;
}

eventListener stops working after scrolling down/changing property in javascript

I have a navigation bar. In it, I have some anchors. One of the anchors has the text 'Guides'. I want a div to appear when I hover over the anchor, and I want it to remain on the screen as long as I am hovering over the anchor. I also want the the div to remain on the screen as long as I am hovering over the div itself. All of this is working fine. When I scroll down, I decrease the size of the navigation bar and change the top position of the div. After I do this, the eventListener that I have set up to keep the div on the screen as long as I am hovering over it stops working. Please note that the div still appears when I hover over the anchor, and it remains on the screen as long as I am hovering over it.
Here's the code. The div is the one with id="dropdown-guides":
// Show dropdown on hovering over 'guides' in navigation bar
let guidesAnchor = document.querySelector('#nav-anchor-guides')
let guidesDropdown = document.querySelector('#dropdown-guides')
function showGuidesDropdown() {
guidesDropdown.style.display = 'block'
}
function hideGuidesDropDown() {
guidesDropdown.style.display = 'none'
}
guidesAnchor.addEventListener('mouseenter', showGuidesDropdown)
guidesAnchor.addEventListener('mouseleave', hideGuidesDropDown)
guidesDropdown.addEventListener('mouseenter', showGuidesDropdown)
guidesDropdown.addEventListener('mouseleave', hideGuidesDropDown)
// Show search bar on clicking search icon
let searchIcon = document.querySelector('#search-icon_anchor')
let searchBar = document.querySelector('#search-bar')
searchIcon.addEventListener('click', function() {
if (searchBar.style.display === 'none') {
searchBar.style.display = 'block'
} else {
searchBar.style.display = 'none'
}
})
// Change navigation bar on scrolling down
let navBar = document.querySelector('nav')
let mainIcon = document.querySelector('#nav-main-icon')
let navAnchors = document.querySelectorAll('nav a')
let iconDesignGuideAnchor = document.querySelector('#nav-dropdown-guides-icon-design-guide')
let pixelPerfectIconsAnchor = document.querySelector('#nav-dropdown-guides-crafting-pixel-perfect-icons')
let dribbbleAudienceAnchor = document.querySelector('#nav-dropdown-guides-build-your-dribbble-audience')
window.onscroll = () => {
if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) {
navBar.style.height = '42px'
navBar.style.paddingTop = '10px'
navBar.style.boxShadow = '0px 0px 7px #0000001A'
mainIcon.style.top = '10px'
mainIcon.style.width = '97px'
mainIcon.style.height = '30px'
navAnchors.forEach(navAnchor => {
navAnchor.style.top = '14px'
navAnchor.style.height = '23px'
})
guidesDropdown.style.top = '42px'
searchBar.style.top = '52px'
iconDesignGuideAnchor.style.top = '65px'
pixelPerfectIconsAnchor.style.top = '108px'
dribbbleAudienceAnchor.style.top = '174px'
} else {
navBar.style.height = '80px'
navBar.style.paddingTop = '0px'
navBar.style.boxShadow = 'none'
mainIcon.style.top = '18px'
mainIcon.style.width = '139px'
mainIcon.style.height = '43px'
navAnchors.forEach(navAnchor => {
navAnchor.style.top = '28px'
navAnchor.style.height = '52px'
})
guidesDropdown.style.top = '80px'
searchBar.style.top = '80px'
iconDesignGuideAnchor.style.top = '103px'
pixelPerfectIconsAnchor.style.top = '146px'
dribbbleAudienceAnchor.style.top = '212px'
}
}
body {
margin: 0;
font-family: "Open Sans", Arial, sans-serif;
}
nav {
width: 100%;
height: 80px;
position: fixed;
border-bottom: 1px solid #E5E5E5;
z-index: 1;
background-color: #FFFFFF;
}
#nav-main-icon {
left: 135px;
top: 18px;
width: 139px;
height: 43px;
position: fixed;
}
a {
text-decoration: none;
}
nav a {
position: fixed;
top: 28px;
height: 52px;
font-family: "Open Sans", sans-serif;
font-size: 14px;
color: #666666;
}
nav a:hover {
color: #333333;
}
#nav-anchor-blog {
left: 748px;
}
#nav-anchor-guides {
left: 802px;
}
#nav-anchor-free-icons {
left: 887px;
}
#nav-anchor-free-wallpapers {
left: 979px;
}
#nav-anchor-about-me {
left: 1110px;
}
#nav-search-icon {
position: fixed;
left: 1197px;
width: 18px;
height: 17px;
font-size: 14px;
fill: #00000080;
}
#nav-search-icon:hover {
fill: #E74225;
}
.nav-dropdown {
top: 80px;
box-shadow: 0 2px 5px #0000001A;
border-top: 3px solid #E74225;
background-color: #FFFFFFFF;
display: none;
}
#dropdown-guides {
position: relative;
left: 776px;
width: 200px;
height: 175px;
padding: 20px;
z-index: 3;
}
#dropdown-guides a {
left: 796px;
width: 160px;
padding: 10px 20px;
line-height: 23px;
}
#dropdown-guides a:hover {
background-color: #00000008;
}
#nav-dropdown-guides-icon-design-guide {
top: 103px;
height: 23px;
}
#nav-dropdown-guides-crafting-pixel-perfect-icons {
top: 146px;
height: 46px;
}
#nav-dropdown-guides-build-your-dribbble-audience {
top: 212px;
height: 46px;
}
#search-bar {
position: absolute;
left: 895px;
width: 280px;
height: 35px;
padding: 20px;
z-index: 2;
}
#search-field {
left: 915px;
top: 103px;
width: 240px;
height: 15px;
padding: 10px 20px;
border: hidden;
background-color: #F8F8F8;
font-family: Arial;
font-weight: 400;
font-size: 13.3333px;
color: #757575;
}
#search-field:focus {
outline: none;
}
h1, h3, h4, p, a {
margin: 0;
font-weight: 500;
}
h1, h3, h4 {
text-align: center;
}
h1 {
font-size: 30px;
line-height: 30px;
color: #333333;
}
h3 {
font-size: 22px;
line-height: 22px;
color: #333333;
}
h4 {
font-size: 14px;
line-height: 24px;
color: #666666;
}
p {
font-size: 16px;
line-height: 27px;
color: #666666;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Main - Icon Utopia</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="index-styles.css">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
</head>
<body>
<header>
<nav>
<img id="nav-main-icon" src="icon-utopia.png">
<a id="nav-anchor-blog" href="blog.html">Blog</a>
<a id="nav-anchor-guides" href="www.iconutopia.com">Guides</a>
<a id="nav-anchor-free-icons" href="https://iconutopia.com/free-icons/">Free Icons</a>
<a id="nav-anchor-free-wallpapers" href="https://iconutopia.com/free-phone-wallpapers/">Free Wallpapers</a>
<a id="nav-anchor-about-me" href="https://iconutopia.com/about/">About Me</a>
<a id="search-icon_anchor"><svg id="nav-search-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32.2 32.2"><path d="M19 0C11.8 0 6 5.8 6 13c0 3.1 1.1 5.9 2.9 8.2l-8.6 8.6c-0.5 0.5-0.5 1.4 0 2 0.5 0.5 1.4 0.5 2 0l8.6-8.6C13.1 24.9 15.9 26 19 26c7.2 0 13-5.8 13-13S26.2 0 19 0zM19 24C12.9 24 8 19.1 8 13S12.9 2 19 2 30 6.9 30 13 25.1 24 19 24z"/></svg></a>
<div id="dropdown-guides" class="nav-dropdown">
<a id="nav-dropdown-guides-icon-design-guide" href="free-icon-design-guide.html">Icon Design Guide</a>
<a id="nav-dropdown-guides-crafting-pixel-perfect-icons" href="crafting-pixel-perfect-icons-the-right-way.html">Crafting Pixel Perfect Icons – The Right Way!</a>
<a id="nav-dropdown-guides-build-your-dribbble-audience" href="build-your-dribbble-audience.html">Build your Dribbble audience</a>
</div>
<div id="search-bar" class="nav-dropdown">
<form id="search-form">
<input id="search-field" type="text" placeholder="Search ...">
</form>
</div>
</nav>
</header>
</body>
<script src="nav.js"></script>
</html>
Please note that since the top set in CSS for the div is originally 80px, if I remove the code for changing the top of the div, after scrolling down, I can't reach it if I am hovering over the anchor, before it disappears. That's why I was not able to tell whether the eventListener stopped working because I scrolled down, or because I changed the top of the div.
I figured out the problem. In my javascript, I was setting the height of each navAnchor to fit only the text of the anchor. That's why the dropdown disappeared before I could hover over it. So I increased the height to extend the anchors to reach the bottom of the navigation bar. (I increased the height from 23px to 39px)

Html into wordpress theme

I need to make a fixed bottom footer to my WordPress web, with some buttons including js with a popover. I've Pillar Theme and I only need to make this change. I need to put it into my footer.php. But when I try, nothing works. I do not know if this is the best way to do that. Here is the code that I do for the footer:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Styles just for demo -->
<style>
#font-face {
font-family: 'social-icons';
font-weight: normal;
font-style: normal;
src: url('font/social.eot?44259375');
src: url('font/social.eot?44259375#iefix') format('embedded-opentype'), url('font/social.woff?44259375') format('woff'), url('font/social.ttf?44259375') format('truetype'), url('font/social.svg?44259375#social') format('svg');
}
/* Share button
***********************************************/
.need-share-button {
position: relative;
display: inline-block;
}
.need-share-button_dropdown {
position: absolute;
z-index: 10;
visibility: hidden;
overflow: hidden;
width: 240px;
-webkit-transition: .3s;
transition: .3s;
-webkit-transform: scale(.1);
-ms-transform: scale(.1);
transform: scale(.1);
text-align: center;
opacity: 0;
-webkit-border-radius: 4px;
border-radius: 4px;
}
.need-share-button-opened .need-share-button_dropdown {
visibility: visible;
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
opacity: 1;
}
.need-share-button_link {
display: inline-block;
width: 40px;
height: 40px;
line-height: 40px;
cursor: pointer;
text-align: center;
}
.need-share-button_link:after {
font: normal normal normal 16px/1 'social-icons';
text-align: center;
text-transform: none;
speak: none;
}
.need-share-button_link:hover {
-webkit-transition: .3s;
transition: .3s;
opacity: .7;
}
/* Dropdown position
***********************************************/
.need-share-button_dropdown-top-center {
bottom: 100%;
left: 50%;
margin-bottom: 10px;
}
/* Default theme
***********************************************/
.need-share-button-default .need-share-button_button {
display: inline-block;
margin-bottom: 0;
padding: 20px;
font-size: 14px;
line-height: 1.42857143;
font-weight: 400;
color: white;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
text-align: center;
vertical-align: middle;
white-space: nowrap;
background-image: url("share.png") no-repeat;
}
.need-share-button-default .need-share-button_button span {
background-image: url("share.png") no-repeat;
}
.need-share-button-default .need-share-button_button:hover {
color: #737373;
}
/* Network buttons
***********************************************/
.need-share-button_mailto {
color: #efbe00;
}
.need-share-button_mailto:after {
content: '\e80a';
}
.need-share-button_mailto.need-share-button_link-box {
color: #fff;
background: #efbe00;
}
.need-share-button_twitter {
color: #00acec;
}
.need-share-button_twitter:after {
content: '\e813';
}
.need-share-button_twitter.need-share-button_link-box {
color: #fff;
background: #00acec;
}
.need-share-button_facebook {
color: #3b5998;
}
.need-share-button_facebook:after {
content: '\e80e';
}
.need-share-button_facebook.need-share-button_link-box {
color: #fff;
background: #3b5998;
}
.wrapper {
text-align: center;
}
footer {
background-color: black;
position: fixed;
bottom: 0;
width: 100%;
left: 0;
height: 60px;
}
footer .col-sm {
text-align: center;
}
a {
color: white;
text-decoration: none;
}
footer .col-sm > span {
padding: 7px 0 0px;
display: inline-block;
}
footer .col-sm > span > a:hover {
color: #737373;
text-decoration: none;
}
#homefooter a{
background-image: url("home.png");
background-repeat: no-repeat;
padding-bottom: 35px;
}
#donarfooter a {
background-image: url("donar.png");
background-repeat: no-repeat;
padding-bottom: 35px;
}
footer a span {
visibility: hidden;
}
/* ------------------------------------ MEDIA QUERIES -------------------------------------------*/
#media (max-width: 900px){
footer .col-sm {
width: 25%;
}
footer span {
padding: 0 !important;
}
}
/* ------------------------------------ MEDIA QUERIES -------------------------------------------*/
/* ------------------------------------ SEARCH STYLES -------------------------------------------*/
* {
box-sizing: border-box;
}
.openBtn {
background: #f1f1f1;
border: none;
padding: 10px 15px;
font-size: 20px;
cursor: pointer;
}
.openBtn:hover {
background: #bbb;
}
.overlay {
height: 100%;
width: 100%;
display: none;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0, 0.9);
}
.overlay-content {
position: relative;
top: 46%;
width: 80%;
text-align: center;
margin-top: 30px;
margin: auto;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
cursor: pointer;
color: white;
}
.overlay .closebtn:hover {
color: #ccc;
}
.overlay input[type=text] {
padding: 15px;
font-size: 17px;
border: none;
float: left;
width: 80%;
background: white;
}
.overlay input[type=text]:hover {
background: #f1f1f1;
}
.overlay button {
float: left;
width: 20%;
padding: 15px;
background: #ddd;
font-size: 17px;
border: none;
cursor: pointer;
}
.overlay button:hover {
background: #bbb;
}
/* ------------------------------------ SEARCH STYLES -------------------------------------------*/
</style>
</head>
<body>
<section>
<div id="myOverlay" class="overlay">
<span class="closebtn" onclick="closeSearch()" title="Close Overlay">×</span>
<div class="overlay-content">
<form action="/action_page.php">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
</section>
<footer class="fixed-bottom">
<div class="container-fluid" style="height: 100%">
<div class="row" style="height: 100%">
<div class="col-sm" id="homefooter">
<span>
<span>HOME</span>
</span>
</div>
<div class="col-sm" style="height: 100%; border-left: solid 0.5px white; border-right: solid 0.5px white">
<div class="wrapper">
<img src="share.png">
<div id="share-button-2" class="need-share-button-default" data-share-position="topCenter" data-share-icon-style="box" data-share-networks="Mailto,Twitter,Facebook"></div>
</div>
</div>
<div class="col-sm" id="donarfooter">
<span>
<span>CONTRIBUIR</span>
</span>
</div>
<div class="col-sm" id="donarfooter">
<span>
<button class="openBtn" onclick="openSearch()">BUSCAR</button>
</span>
</div>
</div>
</div>
</footer>
<script>
/***********************************************
needShareButton
- Version 1.0.0
- Copyright 2015 Dzmitry Vasileuski
- Licensed under MIT (http://opensource.org/licenses/MIT)
***********************************************/
(function() {
// share dropdown class
window.needShareDropdown = function(elem, options) {
// create element reference
var root = this;
root.elem = elem;
root.elem.className += root.elem.className.length ? ' need-share-button' : 'need-share-button';
/* Helpers
***********************************************/
// get title from html
root.getTitle = function() {
var content;
// check querySelector existance for old browsers
if (document.querySelector) {
if (content = document.querySelector('meta[property="og:title"]') || document.querySelector('meta[name="twitter:title"]')) {
return content.getAttribute('content');
} else if (content = document.querySelector('title')) {
return content.innerText;
} else
return '';
} else {
if (content = document.title)
return content.innerText;
else
return '';
}
};
// get image from html
root.getImage = function() {
var content;
// check querySelector existance for old browsers
if (document.querySelector) {
if (content = document.querySelector('meta[property="og:image"]') || document.querySelector('meta[name="twitter:image"]')) {
return content.getAttribute('content');
} else
return '';
} else
return '';
};
// get description from html
root.getDescription = function() {
var content;
// check querySelector existance for old browsers
if (document.querySelector) {
if (content = document.querySelector('meta[property="og:description"]') || document.querySelector('meta[name="twitter:description"]') || document.querySelector('meta[name="description"]')) {
return content.getAttribute('content');
} else
return '';
} else {
if (content = document.getElementsByTagName('meta').namedItem('description'))
return content.getAttribute('content');
else
return '';
}
};
// share urls for all networks
root.share = {
'mailto' : function() {
var url = 'mailto:?subject=' + encodeURIComponent(root.options.title) + '&body=Thought you might enjoy reading this: ' + encodeURIComponent(root.options.url) + ' - ' + encodeURIComponent(root.options.description);
window.location.href = url;
},
'twitter' : function() {
var url = root.options.protocol + 'twitter.com/home?status=';
url += encodeURIComponent(root.options.title) + encodeURIComponent(root.options.url);
root.popup(url);
},
'facebook' : function() {
var url = root.options.protocol + 'www.facebook.com/sharer/share.php?';
url += 'u=' + encodeURIComponent(root.options.url);
url += '&title=' + encodeURIComponent(root.options.title);
root.popup(url);
},
}
// open share link in a popup
root.popup = function(url) {
// set left and top position
var popupWidth = 500,
popupHeight = 400,
// fix dual screen mode
dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left,
dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top,
width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width,
height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height,
// calculate top and left position
left = ((width / 2) - (popupWidth / 2)) + dualScreenLeft,
top = ((height / 2) - (popupHeight / 2)) + dualScreenTop,
// show popup
shareWindow = window.open(url,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + popupWidth + ', height=' + popupHeight + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus) {
shareWindow.focus();
}
}
/* Set options
***********************************************/
// create default options
root.options = {
shareButtonClass: false, // child selector of custom share button
iconStyle: 'default', // default or box
boxForm: 'horizontal', // horizontal or vertical
position: 'bottomCenter', // top / middle / bottom + Left / Center / Right
buttonText: 'COMPARTIR',
protocol: ['http', 'https'].indexOf(window.location.href.split(':')[0]) === -1 ? 'https://' : '//',
url: window.location.href,
title: root.getTitle(),
image: root.getImage(),
description: root.getDescription(),
networks: 'Mailto,Twitter,Facebook'
}
// integrate data attribute options
for (var option in root.elem.dataset) {
// replace only 'share-' prefixed data-attributes
if (option.match(/share/)) {
var new_option = option.replace(/share/, '');
if (!new_option.length) {
continue;
}
new_option = new_option.charAt(0).toLowerCase() + new_option.slice(1);
root.options[new_option] = root.elem.dataset[option];
}
}
// convert networks string into array
root.options.networks = root.options.networks.toLowerCase().split(',');
/* Create layout
***********************************************/
// create dropdown button if not exists
if (root.options.shareButtonClass) {
for (var i = 0; i < root.elem.children.length; i++) {
if (root.elem.children[i].className.match(root.options.shareButtonClass))
root.button = root.elem.children[i];
}
}
if (!root.button) {
root.button = document.createElement('span');
root.button.innerText = root.options.buttonText;
root.elem.appendChild(root.button);
}
root.button.className += ' need-share-button_button';
// show and hide dropdown
root.button.addEventListener('click', function(event) {
event.preventDefault();
if (!root.elem.className.match(/need-share-button-opened/)) {
root.elem.className += ' need-share-button-opened';
} else {
root.elem.className = root.elem.className.replace(/\s*need-share-button-opened/g,'');
}
});
// create dropdown
root.dropdown = document.createElement('span');
root.dropdown.className = 'need-share-button_dropdown';
root.elem.appendChild(root.dropdown);
// set dropdown position
setTimeout(function() {
switch (root.options.position) {
case 'topCenter':
root.dropdown.className += ' need-share-button_dropdown-top-center';
root.dropdown.style.marginLeft = - root.dropdown.offsetWidth / 2 + 'px';
break
}
},1);
// fill fropdown with buttons
var iconClass = root.options.iconStyle == 'default' ? 'need-share-button_link need-share-button_' : 'need-share-button_link-' + root.options.iconStyle + ' need-share-button_link need-share-button_';
for (var network in root.options.networks) {
var link = document.createElement('span');
network = root.options.networks[network];
link.className = iconClass + network;
link.dataset.network = network;
root.dropdown.appendChild(link);
// add share function to event listener
link.addEventListener('click', function() {
root.share[this.dataset.network]();
});
}
}
})();
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
new needShareDropdown(document.getElementById('share-button-2'));
</script>
<script>
function openSearch() {
document.getElementById("myOverlay").style.display = "block";
}
function closeSearch() {
document.getElementById("myOverlay").style.display = "none";
}
</script>
</body>
</html>
You can try Sticky footer with jQuery. Add this code in your js file.
var $ = jQuery.noConflict();
jQuery(document).ready(function($){
/* sticky footer function */
StickyFooter()
});
/* Script on resize */
jQuery(window).resize(function($) {
/* sticky footer function */
StickyFooter();
});
/* Script on load
----------------------------------*/
jQuery(window).load(function($) {
/* sticky footer function */
StickyFooter();
});
/* Sticky Footer Function */
function StickyFooter(){
var Stickyfooter = jQuery( 'footer' ).outerHeight()
jQuery('#wrapper').css('margin-bottom',-Stickyfooter) /* Here #wrapper is your main <div> of <body> */
jQuery('#wrapper').css('padding-bottom',Stickyfooter)
}

Compounding Value within an object used to slide dot across the page incrementally

I am unable to get a variable to function properly as the translateX value within my object. I am wanting to make the dot scroll across the page each time the next button is clicked. My code is only able to move it back and forth for the first step.
I am new to the animation API, and I have already made this work with CSS transitions but I am trying to get a good handle on the API.
html:
<div class="progress__container">
<div class="progress__bar">
<div id="progress__fill" class="step1"></div>
<div class="circ" id="circ__1"></div>
<div class="circ" id="circ__2"></div>
<div class="circ" id="circ__3"></div>
<div class="circ" id="circ__4"></div>
<div id="progress__dot" class="prog__1"></div>
</div>
<div class="backBar"></div>
<div class="flexrow">
<span class="stepName">Account</span>
<span class="stepName">Frequency</span>
<span class="stepName">Amount</span>
<span class="stepName">Taxes</span>
</div>
<div class="button__container">
<button class="buttonStep" id="back">Back</button>
<button class="buttonStep is-active" id="next">Next</button>
</div>
</div>
js:
// give a starting value for the transformation
var startVal = 0;
// define the keyframes
var moveDot = [
{ transform: `translateX(${startVal}px)`},
{ transform: `translateX(${startVal + 190}px)`}
];
// definte the timing
var dotTiming = {
duration: 400,
fill: "forwards",
easing: 'ease-in',
}
// make the animation happen
var movingDot = document.getElementById("progress__dot").animate(
moveDot,
dotTiming
);
// pause the animation until called
movingDot.pause();
// on click fire the animation
document.getElementById('next').addEventListener('click', function() {
movingDot.playbackRate = 1;
if (startVal <= 380) {
movingDot.play();
startVal += 190;
}
});
document.getElementById('back').addEventListener('click', function() {
movingDot.playbackRate = -1;
if (startVal >= 0) {
movingDot.play();
startVal -= 190;
}
});
css:
#progress__fill {
height:2px;
position: absolute;
top: 7px;
left: 0;
background-color: darkred;
}
#progress__dot {
background-color: darkred;
color: #fff;
border-radius: 50%;
height: 8px;
width: 8px;
position: absolute;
text-align:center;
line-height: 8px;
padding: 6px;
top: 0;
font-size: 12px;
}
/* Static Bar Elements */
.progress__container {
width: 600px;
margin: 20px auto;
position: relative;
}
.backBar {
height:2px;
width:96%;
position: absolute;
top: 7px;
left: 2%;
background-color: lightgrey;
}
.progress__bar {
z-index: 100;
position: relative;
width: 96%;
margin: 0 auto;
}
.circ {
background-color: #fff;
border: 2px solid lightgrey;
border-radius: 50%;
height: 12px;
width: 12px;
display: inline-block;
}
#circ__2, #circ__3 {
margin-left: 30%
}
#circ__4 {
float: right;
}
.passed {
background-color: darkred;
border: 2px solid darkred;
}
.hide {
visibility: hidden
}
.flexrow {
display: flex;
flex-direction: row;
justify-content: space-between;
}
/* Buttons */
.buttonStep {
background: grey;
color: #fff;
padding: 10px 25px;
border-radius: 10px;
font-size: 16px;
}
#back {
float: left;
}
#next {
float: right;
}
.is-active {
background: darkred;
}
The way I have it set up, I expect for the translateX values to increment or decrement depending on the click event listeners which would make the circle slide across the page. What is actually happening is that only the first step works. it will not go past the first stop point. If I log moveDot in the console it gives me the values that I am expecting, but it will only start/stop at 0 and 190. the back button functions the same way. link to fiddle
It is animated from and to the same place every time. Move the definition of moveDot into the event listener:
// give a starting value for the transformation
var startVal = 0;
// definte the timing
var dotTiming = {
duration: 400,
fill: "forwards",
easing: 'ease-in',
}
// on click fire the animation
document.getElementById('next').addEventListener('click', function() {
if (startVal > 380){return;}
// define the keyframes
var moveDot = [{transform: `translateX(${startVal}px)`},
{transform: `translateX(${startVal + 190}px)`}];
// make the animation happen
var movingDot = document.getElementById("progress__dot").animate(
moveDot,
dotTiming
);
movingDot.playbackRate = 1;
movingDot.play();
startVal += 190;
});
document.getElementById('back').addEventListener('click', function() {
movingDot.playbackRate = -1;
if (startVal >= 0) {
movingDot.play();
startVal -= 190;
}
});

Aligning items in a table

I made a "To-List" with two icons that animate on the side. the icon on the right is not in the table. So when animating you can see it moving beyond the table. I can't understand why? any help please?
Thank you!
Hi, here is the fiddle:
https://jsfiddle.net/rggo2tmv/
As you can see, the garbage-bin icon disappears inside the table while the other icon (on the right) continues outside the table.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List Project</title>
<!-- local css file sheet-->
<link rel="stylesheet" type="text/css" href="assets\css\todo.css">
<!-- Local JQuery js file-->
<script type ="text/javascript" src="assets/js/lib/jquery-3.1.0.min.js"></script>
<!-- googel fonts -->
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>
<!-- howel sounds -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.0/howler.core.min.js"></script>
<!-- Paper -->
<script type="text/javascript" src="papaer\dist\paper-full.js"></script>
<script type="text/paperscript" canvas="myCanvas">
<!-- two numbers are placing, last number is a radious-->
var circles = [];
var colors = ['blue', 'red', 'orange', 'purple'];
<!-- //DEFINING AN OBJECT -->
var keyData = {
a: {
color: 'purple',
},
b: {
color: 'green',
},
c: {
color: 'yellow',
},
d: {
color: 'orange',
},
e: {
color: 'NavajoWhite',
},
f: {
color: 'yellow',
},
g: {
color: 'orange',
},
h: {
color: 'grey',
},
i: {
color: 'SpringGreen',
},
j: {
color: 'black',
},
k: {
color: 'white',
},
l: {
color: 'darkgrey',
},
m: {
color: 'darkblue',
},
n: {
color: 'darkblue',
},
o: {
color: 'yellow',
},
p: {
color: 'cyan',
},
q: {
color: 'Maroon',
},
r: {
color: 'Red',
},
s: {
color: 'pink',
},
t: {
color: 'Salmon',
},
u: {
color: 'cyan',
},
v: {
color: 'FireBrick',
},
w: {
color: 'Tan',
},
x: {
color: 'Brown',
},
y: {
color: 'Olive',
},
z: {
color: 'YellowGreen',
},
};//closes keyData
function onKeyDown(event) {
if(keyData[event.key]){ //if key is defined
keyData[event.key].color;
<!-- will calc the max size of visible canvas-->
var maxPoint = new Point(view.size.width, view.size.height);
<!-- random is between 0 and 0.99 -->
var randomPoint = Point.random();
<!-- so multiplying max and a random decimal nmber will give us random locaiton inside the canvas -->
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point, 200);
newCircle.fillColor = keyData[event.key].color;
<!-- adds the circle to the array -->
circles.push(newCircle);
}//if
};
function onFrame(event) {
<!-- // Each frame, change the fill color of the path slightly by
// adding 1 to its hue: -->
for(var i = 0; i<circles.length; i++){
circles[i].fillColor.hue += 1;
circles[i].scale(.955);
};
};
</script>
</head>
<body>
<div id="container">
<h1>To-Do List <button <i class="fa fa-plus" aria-hidden="true"></i> </button></h1>
<input type="text" placeholder="Add New To-Do">
<!-- span is the button and its inside the li which contains the text -->
<!-- added table to each so they won't all aniamte toghther -->
<table>
<tr>
<td><span class="spanLeft"><i class="fa fa-trash"></i></span></td>
<td colspan="2">Hello There</td>
<td><span class="spanRight"><i class="fa fa-check-square-o"></i></span></td>
</tr>
</table>
<table>
<tr>
<td><span class="spanLeft"><i class="fa fa-trash"></i></span></td>
<td colspan="2">Hello There</td>
<td><span class="spanRight"><i class="fa fa-check-square-o"></i></span></td>
</tr>
</table>
<table>
<tr>
<td><span class="spanLeft"><i class="fa fa-trash"></i></span></td>
<td colspan="2">Hello There</td>
<td><span class="spanRight"><i class="fa fa-check-square-o"></i></span></td>
</tr>
</table>
</div>
<canvas id="myCanvas" resize></canvas>
<!-- Javascript -->
<!-- //icons -->
<script src="https://use.fontawesome.com/9430f1a1cb.js"></script>
<!-- local javascript -->
<script type="text/javascript" src="assets/js/todo.js"></script>
</body>
</html>
Javascript:
///// check-off and remove spicific to-do by clicking or restore it to not-done-yet
//will add/remove class "completed" - grey and line-through
$("div").on("click", "span.spanRight", function(){
$(this).parent().parent().toggleClass("completed"); //if class exists will remove and the opposite according to aprent from span.spanRight
});
var sound = new Howl({
src: ['https://raw.githubusercontent.com/jonobr1/Neuronal-Synchrony/master/assets/A/clay.mp3']
});
//click on delete button to remove to-do
$("div").on("click", "span.spanLeft", function(){
//will remove the to-do, which its li is the parent element of the span
$(this).parent().parent().fadeOut(500, function() //this here refers to the span, but now because of parent()
//fadeOut will not remove only hide element, so we add remove()
{$(this).remove();}); //this refers to the parent
event.stopPropagation(); //will stop the toggle to "completed" class
});
/////creation of new to-do
//event on key press. When we click "enter" it will add the new to-do (input)
$("input[type='text'").keypress(function(){ //only if input is 'text' it will select the input
if (event.which === 13){//if "enter" is clicked in input field
//grabbing text from input
var todoText = $(this).val(); //takes value that inside input
//create a new li and add to ul
if( todoText!== ''){
$("div").append("<table>" + "<tr><td><span class='spanLeft'><i class='fa fa-trash'></i></span></td>" +
"<td colspan='2'>" + todoText + "</td>" +
"<td><span class='spanRight'><i class='fa fa-check-square-o'></i></span></td>" +
"</tr></table>");
$("input").val('');
sound.play();
}
}
});
/////Add button
// selecting the icon
$(".fa-plus").on("click", function() {
if ( $("input").val() === "") {
// empty
$("input").focus();
} else { //make it do enter key /simulate an enter key, sends the input value and clears the input field (and value)
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 13;
$("input").trigger(press);
//wil ladd input value to feild
$("div").append("<table>" + "<tr><td><span class='spanLeft'><i class='fa fa-trash'></i></span></td>" +
"<td colspan='2'>" + $("input").val() + "</td>" +
"<td><span class='spanRight'><i class='fa fa-check-square-o'></i></span></td>" +
"</tr></table>");
$("input").val('');
sound.play();
} //else
$("input").val('');
});
CSS:
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/*layer index*/
z-index: -5;
}
body{
height: 100%;
margin: 0px;
background: linear-gradient(to left, #16BFFD , #CB3066);
}
#container {
width: 360px;
/*to center:*/
margin: 200px auto 200px auto;
/*slight black shadow around*/
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
background: #e6f3ff;
/**/
}
tbody, table {
/*removes bulletpoints*/
padding: 0;
border: none;
margin: 0;
width: 100%;
height: 100%;
/*removes annoying border from table that broswer creates*/
border-collapse:collapse;
background-color: white;
}
tr {
color: #666;
height: 40px;
/*centers the text*/
line-height: 40px;
width: 100%;
}
/*every second li will get this background color IMPORTANT*/
tr:nth-child(2n){
background: #f7f7f7;
}
td {
padding: 0;
margin: 0;
height: 100%;
border: none;
width: 20px;
}
/*mae the delete button appear. animated at span*/
tr:hover span{
/*40px so we'll see the icons which were set to 0 at start*/
width: 40px;
opacity: 1.0;
border: rgb(0, 0, 0, 0,);
}
span {
width: 0%;
padding: 0;
margin: 0;
}
.spanLeft {
background: #e74c3c;
height: 40px;
margin-right: 20px;
margin-left: 0px;
float: left;
text-align: center;
color: white;
/*set zero for animation*/
width: 0px;
/* display: inline-block;*/
/*animates*/
transition: 0.5s;
opacity: 1;
}
.spanRight {
background: blue;
height: 40px;
margin-right:0px;
margin-left: 20px;
float: right;
text-align: center;
color: white;
/*set zero for animation*/
width: 0px;
/* display: inline-block;*/
/*animates*/
transition: 0.5s;
opacity: 0;
}
input {
padding: 13px 13px 13px 20px;
font-size: 16px;
background-color: #f7f7f7;
width: 100%;
/*box sizing includes the padd, margin etc*/
box-sizing: border-box;
/*takes a way the small gaps around input*/
border: 3px solid rgba(0,0,0,0);
}
/*pnly when focued on an input*/
input:focus{
background: #fff;
border: 3px solid #2980b9;
outline: none;
}
.completed {
color: grey;
text-decoration: line-through;
}
/*the plus sign*/
.fa-plus{
background: none;
border: none;
float: right;
}
h1 {
color: white;
text-transform: uppercase;
background: #2980b9;
margin: 0;
padding: 10px 20px;
font-size: 24px;
font-weight: normal;
/*a google font*/
font-family: 'Roboto', sans-serif;
}
The icon inside the span element that you animate, doesn't "shrink" with the span as you might expect. It is shown to the right of the 0 width span instead (i.e. it overflows). You have the same effect both on the left and right side which is visible if you change the color of the icons.
Span is an inline element so it normally doesn't have the overflow property but you can use display: inline-block to display it with a given width and height. Use overflow: hidden to hide the icon when squeezing the width of the span element.

Categories

Resources