How volume button is generated [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hello i've gotten this code from codepen and i was wondering if anybody could explain me how and where in the code the volume button is generated not the track but the megaphone symbol.
HTML
<h1>Youtube Volume Control</h1>
<div class='bsp-volume-wrap'>
<button id='bsp-volume'>
<span class='fa fa-volume-up'></span>
</button>
<div class='bsp-volume-panel'>
<div class='bsp-volume-slider'>
<div class='bsp-volume-slider-track'>
<div class='bsp-volume-slider-progress'>
<div class='bsp-volume-slider-handle'></div>
</div>
</div>
</div>
</div>
</div>
CSS
#import "//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css";
#import "//fonts.googleapis.com/css?family=Roboto:700";
html, body {
font-family: 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #333333;
text-align: center;
background: #1a1a1a;
}
h1 {
margin: 70px 0 50px;
font-size: 40px;
}
button {
background: none;
border: none;
color: #cccccc;
font-size: 20px;
padding: 0 10px;
height: 40px;
outline: none;
transition: color 0.2s;
cursor: pointer;
float: left;
}
button:hover {
color: white;
}
.bsp-volume-wrap {
padding: 0 10px 0 0;
display: inline-block;
}
.bsp-volume-wrap #bsp-volume {
float: left;
}
.bsp-volume-wrap.bsp-volume-show button {
color: white;
}
.bsp-volume-wrap.bsp-volume-show .bsp-volume-panel {
width: 73px;
}
.bsp-volume-wrap .bsp-volume-panel {
float: left;
height: 40px;
width: 0;
overflow: hidden;
transition: width 0.2s;
cursor: pointer;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider {
position: relative;
height: 100%;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider-track {
height: 2px;
width: 70px;
position: absolute;
top: 50%;
right: 0;
margin-top: -1px;
background: gray;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider-progress {
height: 100%;
width: 0%;
background: red;
position: relative;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider-handle {
height: 12px;
width: 3px;
position: absolute;
top: -5px;
right: 0;
background: white;
}
Javascript
(function () {
var VolumeControl, control, getElementPercentage, bind = function (fn, me) {
return function () {
return fn.apply(me, arguments);
};
};
getElementPercentage = function (click, elm) {
var rect;
rect = elm.getBoundingClientRect();
return (click.pageX - rect.left) / rect.width * 100;
};
VolumeControl = function () {
function VolumeControl() {
this.volumeMute = bind(this.volumeMute, this);
this.volumeStopHandler = bind(this.volumeStopHandler, this);
this.volumeMoveHandler = bind(this.volumeMoveHandler, this);
this.volumeDrag = bind(this.volumeDrag, this);
this.volumeClick = bind(this.volumeClick, this);
this.volumeHoverOut = bind(this.volumeHoverOut, this);
this.volumeHoverIn = bind(this.volumeHoverIn, this);
this.video = new Audio('http://garethweaver.com/codepen/media/bensound-jazzcomedy.mp3');
this.video.volume = 0;
this.video.play();
this.elm = {
volumeWrap: document.getElementsByClassName('bsp-volume-wrap')[0],
volumeSlider: document.getElementsByClassName('bsp-volume-slider')[0],
volumeProgress: document.getElementsByClassName('bsp-volume-slider-progress')[0]
};
this.elm.volumeWrap.addEventListener('mouseenter', this.volumeHoverIn);
this.elm.volumeWrap.addEventListener('mouseleave', this.volumeHoverOut);
this.elm.volumeSlider.addEventListener('click', this.volumeClick);
this.elm.volumeSlider.addEventListener('mousedown', this.volumeDrag);
document.getElementById('bsp-volume').addEventListener('click', this.volumeMute);
}
VolumeControl.prototype.volumeHoverIn = function (e) {
if (this.volumeHoverTimout) {
clearTimeout(this.volumeHoverTimout);
}
return this.elm.volumeWrap.classList.add('bsp-volume-show');
};
VolumeControl.prototype.volumeHoverOut = function (e) {
return this.volumeHoverTimout = setTimeout(function (_this) {
return function () {
return _this.elm.volumeWrap.classList.remove('bsp-volume-show');
};
}(this), 300);
};
VolumeControl.prototype.volumeClick = function (e) {
var percent;
percent = getElementPercentage(e, this.elm.volumeSlider);
return this.volumeSet(percent);
};
VolumeControl.prototype.volumeSet = function (percent) {
this.elm.volumeProgress.style.width = percent + '%';
return this.lastVolume = this.video.volume = percent / 100;
};
VolumeControl.prototype.volumeDrag = function (e) {
e.preventDefault();
document.addEventListener('mousemove', this.volumeMoveHandler);
return document.addEventListener('mouseup', this.volumeStopHandler);
};
VolumeControl.prototype.volumeMoveHandler = function (e) {
var percent;
percent = getElementPercentage(e, this.elm.volumeSlider);
if (percent < 0) {
percent = 0;
} else if (percent > 100) {
percent = 100;
}
return this.volumeSet(percent);
};
VolumeControl.prototype.volumeStopHandler = function (e) {
document.removeEventListener('mousemove', this.volumeMoveHandler);
return document.removeEventListener('mouseup', this.volumeStopHandler);
};
VolumeControl.prototype.volumeMute = function () {
var vol;
vol = this.video.volume > 0 ? 0 : this.lastVolume || 1;
this.video.volume = vol;
return this.elm.volumeProgress.style.width = vol * 100 + '%';
};
return VolumeControl;
}();
control = new VolumeControl();}.call(this));
For and easier way to read here is the link: http://codepen.io/garethdweaver/pen/EjqNxO

That is Font Awesome:
https://fortawesome.github.io/Font-Awesome/icons/
Go there and search (ctrl+F) for "volume".
Font Awesome is loaded on the first line of the CSS file:
#import "//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css";
If you want to know more, visit the fa's home page: https://fortawesome.github.io/Font-Awesome/
edit:
Besides CSS, the HTML file needs to use this simple line to show the megaphone:
<span class='fa fa-volume-up'></span>

Related

<a class='gotoLine' href='#230:45'>230:45</a> Uncaught TypeError :

"230:45 Uncaught TypeError: Cannot read properties of undefined (reading 'shouldStopExecution')"
I got the following error can you fix it. I am trying to add HTML, CSS, and javascript on the same page.
I found this code in codepen i am trying to solve the issue but it's not working anymore...
But javascript not working here...
<div class="wrapper">
<div class="poll-box">
<div class="poll-container">
<div class="poll-question">Do You Love to Play FreeFire?</div>
<div class="poll-panel row mt-30">
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="0"> <span>Yes</span></div>
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="1"> <span>No</span></div>
</div>
</div>
</div>
</div>
<style>* {
box-sizing: border-box;
}
body {
background: #1b1b1b;
margin: 0;
}
.wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.mt-30 {
margin: 30px 0 0 0;
}
.row, .column {
display: flex;
}
.row {
flex-direction: row;
}
.column {
flex-direction: column;
}
.btn:not([disabled]) {
cursor: pointer;
}
.poll-box {
background: linear-gradient(#803af7, #500cc4);
border-radius: 3px;
box-shadow: 0px 5px 11px -7px #000;
text-align: center;
}
.poll-container {
padding: 25px 30px;
position: relative;
}
.poll-question {
width: max-content;
max-width: 700px;
color: #FFF;
font-family: "Poppins", sans-serif;
}
.poll-panel.poll-voted {
overflow: hidden;
border-radius: 50px;
}
.poll-panel.poll-voted .poll-panel-btn.--user-choice {
background: #FFF;
color: #000;
}
.poll-panel.poll-voted .poll-panel-btn.--user-choice:hover {
color: #000;
background: #FFF;
}
.poll-panel.poll-voted .poll-panel-btn {
background: #676464;
color: #FFF;
border-radius: 0;
margin: 0;
border: 0;
position: relative;
}
.poll-panel.poll-voted .poll-panel-btn:hover {
color: #FFF;
background: #676464;
}
.poll-panel.poll-voted .poll-panel-btn:after {
content: attr(data-result);
font-size: 9px;
display: block;
opacity: 0.5;
animation: slideWithFade 0.2s ease;
}
.poll-panel.poll-voted .poll-panel-btn:active {
transform: inherit;
}
.poll-panel.poll-voted .poll-panel-btn span {
display: block;
}
.poll-panel {
width: 100%;
}
.poll-panel-btn {
padding: 7px 10px;
font-family: "Roboto", sans-serif;
font-size: 0.7rem;
width: 100%;
border-radius: 50px;
border: 1px solid #FFF;
margin: 0 20px;
color: #FFF;
transition: 0.15s cubic-bezier(0.17, 0.67, 0.79, 1.24);
}
.poll-panel-btn:hover {
background: #FFF;
color: #000;
}
.poll-panel-btn:active {
transform: scale(0.95);
}
#keyframes slideWithFade {
0% {
opacity: 0;
transform: translateY(10px);
}
100% {
opacity: 1;
}
}</style>
<script>// POLL PLUGIN
class poll {
constructor(question, answers, options) {
const defaultOptions = {};
this.options = Object.assign({}, defaultOptions, options);
this.history = [];
this.possibleAnswers = answers;
}
clear() {
this.history = [];
}
get results() {
let numberOfVotes = this.history.length,
votesResults = [];
Object.keys(this.possibleAnswers).forEach(answerId => {
let answerIdCounter = 0;
let voters = [];
this.history.forEach(vote => {
if (answerId == vote.id) {
answerIdCounter++;
voters.push(vote.name);
}
});
let percentOfAllVotes = answerIdCounter / numberOfVotes * 100;
let formatedPercent = isNaN(percentOfAllVotes) ?
0 :
parseFloat(percentOfAllVotes).
toFixed(3).
slice(0, -1);
votesResults.push({
votes: answerIdCounter,
voters: voters,
percent: formatedPercent });
});
return votesResults;
}
vote(answerId, name = "Anonymouse") {
if (this.possibleAnswers[answerId]) {
let getCurrentDate = new Date().toLocaleString();
this.history.push({ id: answerId, name: name, date: getCurrentDate });
return true;
} else throw new Error("Incorrect answer's id");
}}
// Plugin: https://codepen.io/badurski/pen/RJvJQZ
const q1 = new poll("Will Poland win the footboal match?", {
0: { title: "Yes" },
1: { title: "No" } });
// Add some randome votes
for (let i = 0; i < 20; i++) {if (window.CP.shouldStopExecution(0)) break;
q1.vote(Math.floor(Math.random() * (1 - 0 + 1)) + 0);
}
// Poll interface script
window.CP.exitedLoop(0);let pollButtons = document.querySelectorAll('.poll-panel-btn'),
pollPanel = document.querySelector('.poll-panel');
pollButtons.forEach(button => {
button.onclick = () => {
if (button.getAttribute('disabled') != 'disabled') {
q1.vote(button.dataset.vote);
pollPanel.classList.add('poll-voted');
button.classList.add('--user-choice');
pollButtons.forEach(b => {
b.setAttribute('disabled', 'disabled');
let percent = q1.results[b.dataset.vote].percent + '%';
b.style.width = percent;
b.dataset.result = percent;
});
}
};
});</script>
In codepen everything is separated but in your HTML you should put the scripts before the divs.
Something like:
<script>
//blabla.yourscripts - you got it
</script>
<div class="wrapper">
<div class="poll-box">
<div class="poll-container">
<div class="poll-question">Do You Love to Play FreeFire?</div>
<div class="poll-panel row mt-30">
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="0"> <span>Yes</span></div>
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="1"> <span>No</span></div>
</div>
</div>
</div>
</div>
So just put the scripts before the stuff reading them.
You have included CP which is the CodePan component.
Please remove window.CP lines, then it will work:
window.CP.exitedLoop(0);
if (window.CP.shouldStopExecution(0)) break;
<script>
// POLL PLUGIN
class poll {
constructor(question, answers, options) {
const defaultOptions = {};
this.options = Object.assign({}, defaultOptions, options);
this.history = [];
this.possibleAnswers = answers;
}
clear() {
this.history = [];
}
get results() {
let numberOfVotes = this.history.length,
votesResults = [];
Object.keys(this.possibleAnswers).forEach(answerId => {
let answerIdCounter = 0;
let voters = [];
this.history.forEach(vote => {
if (answerId == vote.id) {
answerIdCounter++;
voters.push(vote.name);
}
});
let percentOfAllVotes = answerIdCounter / numberOfVotes * 100;
let formatedPercent = isNaN(percentOfAllVotes) ?
0 :
parseFloat(percentOfAllVotes).
toFixed(3).
slice(0, -1);
votesResults.push({
votes: answerIdCounter,
voters: voters,
percent: formatedPercent });
});
return votesResults;
}
vote(answerId, name = "Anonymouse") {
if (this.possibleAnswers[answerId]) {
let getCurrentDate = new Date().toLocaleString();
this.history.push({ id: answerId, name: name, date: getCurrentDate });
return true;
} else throw new Error("Incorrect answer's id");
}}
// Plugin: https://codepen.io/badurski/pen/RJvJQZ
const q1 = new poll("Will Poland win the footboal match?", {
0: { title: "Yes" },
1: { title: "No" } });
// Add some randome votes
for (let i = 0; i < 20; i++) {
q1.vote(Math.floor(Math.random() * (1 - 0 + 1)) + 0);
}
// Poll interface script
let pollButtons = document.querySelectorAll('.poll-panel-btn'),
pollPanel = document.querySelector('.poll-panel');
pollButtons.forEach(button => {
button.onclick = () => {
if (button.getAttribute('disabled') != 'disabled') {
q1.vote(button.dataset.vote);
pollPanel.classList.add('poll-voted');
button.classList.add('--user-choice');
pollButtons.forEach(b => {
b.setAttribute('disabled', 'disabled');
let percent = q1.results[b.dataset.vote].percent + '%';
b.style.width = percent;
b.dataset.result = percent;
});
}
};
});
</script>

`offsetWidth` of element seems to change randomly

I noticed that the offsetWidth of this.ratingSliderInput = document.querySelector(".js-rating-slider-input") changes randomly.
It goes from the real width to switching to 129 (no idea where that value is coming from).
This affects setting the position of this.ratingSliderThumb negatively.
Why does offsetWidth change to 129 randomly?
JavaScript:
class RatingSlider {
constructor() {
this.ratingSliderForm = document.querySelector(".js-rating-slider-form");
this.ratingSliderInput = document.querySelector(".js-rating-slider-input");
this.ratingSliderThumb = document.querySelector(".js-rating-slider-thumb");
this.ratingSliderValue = document.querySelector(".js-rating-slider-value");
this.ratingSliderIcon = document.querySelector(".js-rating-slider-icon");
this.isPressed = false;
this.setEvents();
this.bind();
}
setEvents() {
this.moveEvent;
this.startEvent;
this.endEvent;
if ("ontouchstart" in document.documentElement) {
this.moveEvent = "touchmove";
this.startEvent = "touchstart";
this.endEvent = "touchend";
} else {
this.moveEvent = "mousemove";
this.startEvent = "mousedown";
this.endEvent = "mouseup";
}
}
setThumbStyle() {
this.ratingSliderIcon.style.transform = `scale(${1 +
this.ratingSliderInput.value / 150})`;
this.ratingSliderValue.innerText = `${this.ratingSliderInput.value}°`;
}
setPositionThumb() {
this.ratingSliderThumb.style.left = `${(this.ratingSliderInput.offsetWidth /
100) *
this.ratingSliderInput.value -
10}px`;
}
handleOffsetOnChange(event) {
if ("ontouchstart" in document.documentElement) {
let touch = event.touches[0] || event.changedTouches[0];
let target = document.elementFromPoint(touch.clientX, touch.clientY);
event.offsetX = touch.clientX - target.getBoundingClientRect().x;
}
if (
event.offsetX > 0 &&
event.offsetX < this.ratingSliderInput.offsetWidth
) {
this.ratingSliderThumb.style.left = `${event.offsetX - 10}px`;
}
}
bind() {
if (!this.ratingSliderForm) {
return;
}
this.setPositionThumb();
this.setThumbStyle();
this.ratingSliderInput.addEventListener(
this.startEvent,
() => (this.isPressed = true)
);
this.ratingSliderInput.addEventListener(this.endEvent, () => {
this.isPressed = false;
this.ratingSliderForm.submit();
});
this.ratingSliderInput.addEventListener(this.moveEvent, (event) => {
if (!this.isPressed) {
return;
}
this.handleOffsetOnChange(event);
this.setThumbStyle();
});
}
}
export default RatingSlider;
CSS:
.rating-slider__inner-container {
position: relative;
padding-top: 100px;
}
.rating-slider__input {
-webkit-appearance: none;
width: 100%;
height: 5px;
background: $form-gray;
&:focus {
outline: none;
}
}
.rating-slider__input::-webkit-slider-thumb {
-webkit-appearance: none;
background: transparent;
border-color: transparent;
height: 20px;
width: 20px;
margin-top: -8px;
cursor: pointer;
}
.rating-slider__input::-moz-range-thumb {
background: transparent;
border-color: transparent;
height: 20px;
width: 20px;
cursor: pointer;
}
.rating-slider__input::-moz-focus-outer {
border: 0;
}
.rating-slider__thumb {
display: flex;
flex-direction: column;
align-items: center;
position: absolute;
top: 50px;
left: -10px;
font-size: $text-3xl;
pointer-events: none;
}
.rating-slider__value {
color: $brand-primary;
font-size: $text-lg;
}
.rating-slider__range-labels-container {
display: flex;
justify-content: space-between;
}
Here's the project live: https://wagon-city-guides.herokuapp.com/spots/32
And code on GitHub:
JS: https://github.com/mirhamasala/lw_city_guide/blob/master/app/javascript/components/rating_slider.js
CSS:
https://github.com/mirhamasala/lw_city_guide/blob/master/app/assets/stylesheets/components/_rating_slider.scss
HTML:
https://github.com/mirhamasala/lw_city_guide/blob/master/app/views/spots/_spot_rating.html.erb
I realized that your bug only appeared on fresh reload of the page, not coming from another and suspected turbolinks to be the culprit (as often...)
So I added this listener to your app/javascript/packs/application.js
window.onload = function() {
console.log("Window loaded")
let ratingSliderInput = document.querySelector(".js-rating-slider-input");
if(ratingSliderInput) {
console.log("setPositionThumb", ratingSliderInput)
console.log("setPositionThumb", ratingSliderInput.offsetWidth)
}
}
And a similar log in your setPositionThumb I get this:
I'm guessing that the event turbolinks:load may fire too early before the display is actually fully in place.

Stopping a Finite State Machine

I have an application that I have written that adds a set of traffic lights on the screen upon the press of a button. The traffic light automatically cycles from red to yellow after 10 seconds, then on to green after two seconds, then back to yellow after 10 seconds and finally back to red. I have added a control which allows the user to start each traffic light individually. I am trying to figure out how to enable the user to permanently stop each traffic light, without it stopping all the others.
Here is my updated code so far - note the addition of the 'this.stop()' function inside of var Red. I would like the code to stop the rotation there, rather than continue to yellow and green.
Thanks,
Rob
var i = 1;
var TrafficLight = function(i) {
var count = 0;
var light_container = document.getElementById('light-container-' + i);
var currentState = new Red(this, light_container);
this.change = function(state) {
currentState = state;
currentState.go();
}
this.start = function() {
currentState.go();
}
this.stop = function() {
currentState.stop();
}
}
var Red = function(light, light_container) {
this.light = light;
this.go = function() {
light_container.querySelector('.inner-circle-red').style.backgroundColor = '#d8412c';
console.log(light_container);
setTimeout(function() {
light.change(new Yellow(light, 'red', light_container))
}, 12000);
}
this.stop = function() {
light_container.querySelector('.inner-circle-red').style.backgroundColor = '#111111';
light_container.querySelector('.inner-circle-yellow').style.backgroundColor = '#111111';
light_container.querySelector('.inner-circle-green').style.backgroundColor = '#111111';
// Switch all the lights off.
return;
}
}
var Yellow = function(light, origin, light_container) {
this.light = light;
this.go = function() {
light_container.querySelector('.inner-circle-yellow').style.backgroundColor = '#fad201';
setTimeout(function() {
if (origin == 'red') {
light.change(new Green(light, light_container));
light_container.querySelector('.inner-circle-red').style.backgroundColor = '#111111';
light_container.querySelector('.inner-circle-yellow').style.backgroundColor = '#111111';
} else if (origin == 'green') {
light.change(new Red(light, light_container));
light_container.querySelector('.inner-circle-yellow').style.backgroundColor = '#111111';
}
}, 2000);
}
}
var Green = function(light, light_container) {
this.light = light;
console.log('here');
this.go = function() {
light_container.querySelector('.inner-circle-green').style.backgroundColor = '#33A532';
setTimeout(function() {
light.change(new Yellow(light, 'green', light_container))
light_container.querySelector('.inner-circle-green').style.backgroundColor = '#111111';
}, 14000);
}
};
function initiate() {
var light_container = document.createElement('div');
light_container.id = "light-container-" + i;
light_container.className = "light-container";
light_container.innerHTML = '<div class="outer-circle-red"><div class="inner-circle-red"></div></div><div class="outer-circle-yellow"><div class="inner-circle-yellow"></div></div><div class="outer-circle-green"><div class="inner-circle-green"></div></div><label class="switch"><input type="checkbox" class="off" onclick="toggleRun(this, ' + i + ');"><span class="slider round"></span></label>';
document.getElementById("container").appendChild(light_container);
i++;
}
function toggleRun(item, i) {
if (item.className == "off") {
item.className = "on";
run(i);
} else {
item.className = "off";
stop(i);
}
}
function run(i) {
var light = new TrafficLight(i);
light.start();
}
function stop(i) {
var light = new TrafficLight(i);
light.stop();
}
function exit(status) {
var i;
if (typeof status === 'string') {
alert(status);
}
window.addEventListener('error', function(e) {
e.preventDefault();
e.stopPropagation();
}, false);
var handlers = [
'copy', 'cut', 'paste',
'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
];
function stopPropagation(e) {
e.stopPropagation();
// e.preventDefault(); // Stop for the form controls, etc., too?
}
for (i = 0; i < handlers.length; i++) {
window.addEventListener(handlers[i], function(e) {
stopPropagation(e);
}, true);
}
if (window.stop) {
window.stop();
}
throw '';
}
#button {
width: 200px;
height: 20px;
padding: 10px;
background-color: blue;
color: #ffffff;
cursor: pointer;
}
.button {
width: 15px;
height: 20px;
padding: 10px;
background-color: red;
color: #ffffff;
cursor: pointer;
margin: 20px auto;
text-align: center;
text-transform: uppercase;
font-weight: bold;
}
.outer-circle-red,
.outer-circle-yellow,
.outer-circle-green {
background-color: #696969;
margin: 0 auto;
border: 2px solid black;
width: 50px;
height: 40px;
border-radius: 15px;
display: table;
}
.light-container {
margin: 20px 30px 0 30px;
margin-top: 20px;
float: left;
}
.inner-circle-red,
.inner-circle-yellow,
.inner-circle-green {
width: 20px;
height: 20px;
border-radius: 25px;
border: 2px solid #111111;
margin: 0 auto;
margin-top: 7.5px;
background-color: #111111;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
margin-top: 20px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked+.slider {
background-color: #2196F3;
}
input:focus+.slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
<div id="button" onclick="initiate()">+ Add a new traffic light</div>
<div id="container">
</div>
The solution to this is to save the id returned by var id = setTimeout(), so you can use clearTimeout( id ); later on to completely stop the timeout function from triggering again.
So something like: this.timeout = setInterval(function(){ /* insert the color changing code */ }, 10000 );.
If you opt for such a solution, it would be handy to put the timeout code into a single timeout instead of having a separate class for each color. But you can always use an array to store all timeouts and loop over that to cancel if you like having different timeouts for each color.

Make a splitter very thin and grab it

I want to make a draggle splitter between 2 panels. The following is a working version.
Now, I want to make the width of handle as thin as possible (less than 0.1px?), so there is no way to make the width (appear) smaller than 1px?
Additionally, when the splitter is thin, it is hard to select by the mouse. Is there a way to make a splitter easy to grab?
Taking JSBin as example, how did they manage to realise the splitters among the panels?
(function($) {
$.fn.drags = function(opt) {
opt = $.extend({
handle: "",
cursor: "ew-resize",
min: 10
}, opt);
if (opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
var priorCursor = $('body').css('cursor');
return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
priorCursor = $('body').css('cursor');
$('body').css('cursor', opt.cursor);
if (opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
var mouseMove = function(e) {
var prev = $('.draggable').prev();
var next = $('.draggable').next();
var total = prev.outerWidth() + next.outerWidth();
var totalPercentage = parseFloat(prev.css('flex')) + parseFloat(next.css('flex'));
var offset = prev.offset();
if(offset){
var leftPercentage = ((e.pageX - offset.left - drg_w / 2) / total) * totalPercentage;
var rightPercentage = totalPercentage - leftPercentage;
if (leftPercentage * 100 < opt.min || rightPercentage * 100 < opt.min) {
return;
}
prev.css('flex', leftPercentage.toString());
next.css('flex', rightPercentage.toString());
}
}
$drag.css('z-index', 1000).parent().on("mousemove", mouseMove).on("mouseup", function() {
$(this).off("mousemove", mouseMove).off("mouseup");
$('body').css('cursor', priorCursor);
$('.draggable').removeClass('draggable').css('z-index', z_idx);
});
e.preventDefault(); // disable selection
});
}
})(jQuery);
$('.handle').drags();
.flex-box {
display: flex;
width: 100%;
margin: 0;
height: 300px;
}
.flex-box .col {
border: 1px solid grey;
flex: 0.33;
padding: 12px;
overflow-y: auto;
overflow-x: hide;
}
.handle {
width: 1px;
text-align: center;
background: grey;
transition: all ease-in 0.1s;
}
.draggable {
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex-box">
<div class="col">
<p>Pellentesque ...</p>
</div>
<div class="handle"></div>
<div class="col">
<p>Pellentesque ...</p>
</div>
</div>
If you'd like the handle to appear thinner try applying a negative value to the right "col" e.g. margin-left: -2px; so it overlaps the left "col" border on the left of it. I don't think you can make the width "appear" as 0.1px. Firefox is the only browser that renders such value. (https://css-tricks.com/forums/topic/0-1px-borders/)
.flex-box .col:last-child {
margin-left: -2px;
}
//raise handle layer to top
.handle {
.....
z-index: 9999;
}
Hope this helps...
*Edit:
This is the closest I could get to your request:
.flex-box {
display: flex;
width: 100%;
margin: 0;
height: 300px;
}
.flex-box .col {
border: 1px solid grey;
flex: 0.33;
padding: 12px;
overflow-y: auto;
overflow-x: hide;
}
.flex-box .col:last-child {
margin-left: -6px;
}
.handle {
width: 5px;
text-align: center;
transition: all ease-in 0.1s;
z-index: 999;
overflow: visible;
}
.handle-inner{
width: 5px;
height: 100%;
position: relative;
margin-left: -10px;
}
.draggable {
background: grey;
}
Jsbin :
https://jsbin.com/nupefekuhu/edit?html,css,js,output

A javascript slider array issue

Having a slider with images implementation from array, cant figure out why images dont want to be shown up from array, tryed to make a path but it didnt work.I want this code to reflect this image every time a push the button: fpoimg.com/100x100.
Im trying to fix it only with clean javascript.
Here is a sandbox
var slider = {
slides: ['100x100', '100x100', '100x100', '100x100'],
frame:0,
set:function(image){
path = path || 'http://fpoimg.com/';
document.getElementById('scr').style.backgroundImage ="url ("+path+ image+")";
},
init:function() {
this.set(this.slides[this.frame]);
},
left:function() {
this.frame--;
if(frame < 0) this.frame = this.slides.length - 1;
this.set(this.slides[this.frame]);
},
right:function() {
if(this.frame == this.slides.length) this.frame = 0;
this.set(this.slides[this.frame]);
}
};
window.onload = function() {
slider.init();
setInterval(function() {
slider.right();
},5000);
};
.scr {
margin:20px auto;
width: 600px;
height: 320px;
margin-top:20px;
background-color: white;
background-size:cover;
}
button {
position: absolute;
top: 150px;
width: 25px;
height: 150px;
font-size: 30px;
text-align: center;
background:none;
border:none;
}
.left {
left:25px;
}
.right {
right:25px;
}
<body>
<button class="left" onclick="slider.left();"><</button>
<div class="scr"></div>
<button class="right" onclick="slider.right();">></button>
</body>
On Line 6 of your Javascript, you have used getElementById('scr'). You have no element with an Id or scr, you needed to use getElementsByClassName('scr')
Your new code:
var slider = {
slides: ['100x100', '100x100', '100x100', '100x100'],
frame: 0,
set: function(image) {
path = path || 'http://fpoimg.com/';
document.getElementsByClassName('scr').style.backgroundImage = "url (" + path + image + ")";
},
init: function() {
this.set(this.slides[this.frame]);
},
left: function() {
this.frame--;
if (frame < 0) this.frame = this.slides.length - 1;
this.set(this.slides[this.frame]);
},
right: function() {
if (this.frame == this.slides.length) this.frame = 0;
this.set(this.slides[this.frame]);
}
};
window.onload = function() {
slider.init();
setInterval(function() {
slider.right();
}, 5000);
};
.scr {
margin: 20px auto;
width: 600px;
height: 320px;
margin-top: 20px;
background-color: white;
background-size: cover;
}
button {
position: absolute;
top: 150px;
width: 25px;
height: 150px;
font-size: 30px;
text-align: center;
background: none;
border: none;
}
.left {
left: 25px;
}
.right {
right: 25px;
}
<body>
<button class="left" onclick="slider.left();">
</button>
<div class="scr"></div>
<button class="right" onclick="slider.right();"></button>
</body>
It seems you've got getElementById() when you meant getElementsByClassName()

Categories