How to create this range bar using JavaScript? - javascript

.range {-moz-box-sizing: border-box;box-sizing: border-box;-webkit-background-clip: padding-box;background-clip: padding-box;vertical-align: top;outline: none;line-height: 1;-webkit-appearance: none;-webkit-border-radius: 4px;border-radius: 4px;border: none;height: 2px;-webkit-border-radius: 0;border-radius: 0;-webkit-border-radius: 3px;border-radius: 3px;background-image: -webkit-gradient(linear, left top, left bottom, from(#ddd), to(#ddd));background-image: -webkit-linear-gradient(#ddd, #ddd);background-image: -moz-linear-gradient(#50b1f9, #50b1f9);background-image: -o-linear-gradient(#ddd, #ddd);background-image: linear-gradient(#50b1f9,#50b1f9);background-position: left center;-webkit-background-size: 100% 2px;background-size: 100% 2px;background-repeat: no-repeat;overflow: hidden;height: 31px;}
.range::-moz-range-track {position: relative;border: none;background-color: #50b1f9;height: 2px;border-radius: 30px;box-shadow: none;top: 0;margin: 0;padding: 0;}
.range::-webkit-slider-thumb {cursor: pointer;-webkit-appearance: none;position: relative;height: 29px;width: 29px;background-color: #fff;border: 1px solid #ddd;-webkit-border-radius: 30px;border-radius: 30px;-webkit-box-shadow: none;box-shadow: none;top: 0;margin: 0;padding: 0;}
.range::-moz-range-thumb {cursor: pointer;position: relative;height: 15px;width: 15px;background-color:#fff;border: 1px solid #ddd;border-radius: 30px;box-shadow: none;margin: 0;padding: 0}
.range::-webkit-slider-thumb:before {position: absolute;top: 13px;right: 0px;left: -1024px;width: 1024px;height: 2px;background-color: #50b1f9;;content: '';margin: 0;padding: 0;}
.range:disabled {opacity: 0.3;cursor: default;pointer-events: none;}
<input type="range" class="range">
I have to make this range bar and when I slide the months will also change accordingly. I tried making it into css but for changing range I would need JavaScript.

var range = document.getElementById("range"),
progress = document.getElementById("progress"),
handle = document.getElementById("handle"),
valueBox = document.getElementById("value"),
movable = false,
offsetX = range.offsetLeft,
rangeWidth = range.offsetWidth,
handleWidth = handle.offsetWidth,
max = 100, left, mouseX, value;
function move(e) {
if ( movable === true ) {
left = e.clientX - offsetX;
handle.style.left = left - ( handleWidth / 2 ) + "px";
progress.style.width = left + "px";
if ( left >= rangeWidth ) {
handle.style.left = rangeWidth - ( handleWidth / 2 ) + "px";
progress.style.width = rangeWidth + "px";
} if ( left <= 0 ) {
handle.style.left = "-" + handleWidth / 2 + "px";
progress.style.width = "0px";
}
value = Number(parseFloat(progress.style.width) / ( rangeWidth / max )).toFixed(0);
valueBox.textContent = value;
}
};
function on(e) {
movable = true;
mouseX = e.clientX;
};
function off() {
movable = false;
};
handle.addEventListener("mousedown", on, false);
window.addEventListener("mousemove", move, false);
window.addEventListener("mouseup", off, false);
* { margin: 0; padding: 0; border: 0; outline: 0; }
body { background-color: #FF0000; }
#range {
width: 350px;
height: 14px;
background-color: #242424;
margin: 100px auto 15px;
border-radius: 50px;
position: relative;
}
#progress {
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: #00A79D;
border-radius: 50px;
}
#handle {
position: absolute;
top: -3px;
height: 20px;
width: 20px;
background-color: #eee;
border-radius: 50px;
cursor: pointer;
}
#handle:hover, #handle:active {
background-color: #ddd;
}
#value-box {
text-align: center;
font: 14px arial;
line-height: 35px;
color: #eee;
width: 170px;
height: 35px;
background-color: rgba(0, 0, 0, .2);
margin: auto;
border-radius: 2px;
}
<div id="range">
<div id="progress"></div>
<div id="handle"></div>
</div>
<div id="value-box">Range bar Value : <span id="value">0</span></div>
Check output in Snippet Also.
Finally Output :

Related

Variable not changing from its initial value when it outputs in the result

I have tried and tried at finding why the variable OdEv is not changing from its initial value. It should change depending on whether x is odd or even in the function workingOdd(), but it just stays at the initial placeholder value of 'T'.
Code:-
<!DOCTYPE html>
<html>
<body style="background: grey; font-family: Arial, sans-serif;">
<script>
function closebox() {
document.getElementById("box").style.visibility="hidden";
document.getElementById("closeboxbutton").style.visibility="hidden";
document.getElementById("openboxbutton").style.visibility="visible";
}
function openbox() {
document.getElementById("box").style.visibility="visible";
document.getElementById("closeboxbutton").style.visibility="visible";
document.getElementById("openboxbutton").style.visibility="hidden";
}
</script>
<div style="background:black;color:white;padding:10px;text-align:left; height:20px;">
<div id="togglestakesshow"><button style="float:left; width:220px;" onclick="showstakes()">SHOW STAKES STRUCTURE</button></div>
<div id="togglestakeshide"><button style="float:left; width:100px;" onclick="hidestakes()">HIDE STAKES STRUCTURE</button></div>
<div id="openboxbutton"><button style="display:inline-block;" onclick="openbox()">OPEN INPUT BOX</button></div>
<div id="closeboxbutton"><button style="display:inline-block;" onclick="closebox()">CLOSE INPUT BOX</button></div>
<div id="bankrollwindow" style="margin-top: -4px; width:70px; text-align:center; float:right; padding:5px; color:black; background:white; display:inline-block;">£</div>
<div style="float:right; margin-right:10px;">BANKROLL</div>
</div>
<div id="stakespanel">CONTENT OF STAKES</div>
<div id="results" style="border:5px solid white; height:730px; overflow:scroll;background:white;">
</div>
<div>
<div id="betsdiv" style=" position: fixed; bottom: 0; left: 50%; transform: translateX(-50%);height:160px; width:1200px; border: 5px solid white; background: green; ">
<div id="toprow">
<div class="toprowbets">1st 12</div>
<div class="toprowbets">2nd 12</div>
<div class="toprowbets">3rd 12</div>
<div style="clear:both;"></div>
<div class="bottomrowbets">1-18</div>
<div class="bottomrowbets">EVEN</div>
<div class="bottomrowbets">RED</div>
<div class="bottomrowbets">BLACK</div>
<div class="bottomrowbets">ODD</div>
<div class="bottomrowbets">19-36</div>
</div>
</div>
</div>
<div id="box" ondrop="drop(event)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event)">
<div id="modal-content">
<p>Select a number between 0 and 36:</p>
<div id="numberButtons"></div>
<button id="close-button" onclick="closebox()">Close</button>
</div>
</div>
</div>
<style>
.toprowbets {
height:75px;
line-height:75px;
vertical-align: middle;
width:390px;
border: 5px solid white;
float:left;
text-align:center;
font-size:30px;
font-weight:600;
color:white;
}
.bottomrowbets {
height:75px;
line-height:75px;
vertical-align: middle;
width:190px;
border: 5px solid white;
float:left;
text-align:center;
font-size:30px;
font-weight:600;
color:white;
}
#openboxbutton
{ visibility: hidden;
display: inline-block;
position: relative;
top: -6px }
#closeboxbutton
{ visibility: visible;
display: inline-block;
position: relative;
top: -6px;
left: -113px; }
#togglestakesshow {
font-size:10px;
width: 200px;
overflow: hidden;
display: inline-block;
}
#togglestakeshide {
font-size:10px;
width: 0px;
overflow: hidden;
display: inline-block;
}
#stakespanel {
overflow: hidden;
height:0px;
border:1px solid black;
background: white;
}
/* The modal background */
#modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
/* The modal content */
#modal-content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: #fefefe;
padding: 20px;
width: 18%;
border: 3px solid black;
#box {
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 300px;
z-index: 1;
margin-top: -150px; /* half of the box's height */
margin-left: -150px; /* half of the box's width */
visibility: visible;
}
}
#stakesbox {
position: absolute;
top: 50%;
left: 50%;
width: 800px;
height: 200px;
z-index: 2;
margin-top: -150px; /* half of the box's height */
margin-left: -150px; /* half of the box's width */
visibility: visible;
border: 2px solid black;
Background-color:white;
}
/* The close button */
#close-button {
display: block;
margin: 0 auto;
}
#numberButtons button {
color: white;
width: 50px;
height: 50px;
font-size:30px;
font-weight:600;
}
#modal.inactive{
opacity: 0.2;
}
</style>
<script>
var odEv="T";
var txtOdEv="#33ccff";
var bankRoll = parseFloat(prompt("Please enter your starting bankroll:"));
if(isNaN(bankRoll)){
bankRoll = parseFloat(prompt("Invalid input. Please enter a valid number for your starting bankroll:"));
}
bankRoll = bankRoll.toFixed(2);
updateBankroll()
var spinNumber=0;
var x=0;
var backline="";
var isDragging = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
const modalContent = document.querySelector("#modal-content");
modalContent.addEventListener("mousedown", dragStart);
modalContent.addEventListener("mouseup", dragEnd);
modalContent.addEventListener("mousemove", drag);
function dragStart(e) {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
if (e.target === modalContent) {
isDragging = true;
}
}
let inactivityTimeout;
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
isDragging = false;
clearTimeout(inactivityTimeout);
inactivityTimeout = setTimeout(() => {
modal.classList.add("inactive")
}, 15000)
}
function drag(e) {
if (e.buttons === 1) {
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, modalContent);
clearTimeout(inactivityTimeout);
modal.classList.remove("inactive")
}
}
function updateBankroll() {
document.getElementById("bankrollwindow").innerHTML = "£" + bankRoll;
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
function roulette(number) {
// Determine the color of the number
var color;
if (number === 0) {
color = "Green";
} else if (number === 1 || number === 3 || number === 5 || number === 7 || number === 9 || number === 12 || number === 14 || number === 16 || number === 18 || number === 19 || number === 21 || number === 23 || number === 25 || number === 27 || number === 30 || number === 32 || number === 34 || number === 36) {
color = "Red";
} else {
color = "Black";
}
// Map the color names to CSS color values
if (color === "Green") {
return "rgb(0, 128, 0)";
} else if (color === "Red") {
return "rgb(255, 0, 0)";
} else {
return "rgb(0, 0, 0)";
}
}
function workingOdd() {
var odEv;
if (x % 2 === 0) {
odEv = 'Ev';
} else {
odEv = 'Od';
}
// the rest of the function
}
function backgroundline() {
if (spinNumber % 2 === 0) {
backline="#D3D3D3"
} else {
backline="#E5E4E2";
}
}
function spin(number) {
// Determine the color of the number
var color = roulette(number);
spinNumber= spinNumber+1;
bankRoll=bankRoll-10.25;
backgroundline();
// Display the result
var resultsDiv = document.getElementById("results");
var resultHTML = `${number}`;
resultHTML = `<div style="background: ${backline}; vertical-align:middle; margin-bottom:0px; border-bottom: 1px solid white;">
<div style="padding:5px; display: inline-block; background: yellow; color:black;vertical-align:middle; width:30px; text-align:right;">${spinNumber}</div>
<div style="margin: 0 10px; display:inline-block; width: 80px; text-align:center;vertical-align:middle">£${bankRoll}</div>
<div style="color: white; display: inline-block; width:30px;font-size: 25px; font-weight:600; height:30px; text-align:center; line-height: 30px; vertical-align:middle; background-color: ${color}; ">${number}</div>
<div style="color: white; display: inline-block; width:30px;font-size: 25px; font-weight:600; height:30px; text-align:center; line-height: 30px; vertical-align:middle; background-color: ${txtOdEv}; ">${odEv}</div>
</div>`;
resultsDiv.innerHTML += resultHTML;
document.getElementById('results').scrollTop = document.getElementById('results').scrollHeight;
updateBankroll();
}
// Set up the buttons
for (let i = 0; i <= 36; i++) {
let button = document.createElement("button");
button.innerHTML = i;
button.style.backgroundColor = roulette(i);
button.addEventListener("click", function() {
x = i;
workingOdd();
spin(i);
});
document.getElementById("numberButtons").appendChild(button);
}
function closeModal() {
// Get the modal element
var modal = document.getElementById("box");
// Remove the modal element from the DOM
modal.remove();
}
function showstakes() {
// show
document.getElementById("stakespanel").style.height="300px";
document.getElementById("togglestakesshow").style.width="0px";
document.getElementById("togglestakeshide").style.width="150px";};
function hidestakes() {
// hide
document.getElementById("stakespanel").style.height="0px";
document.getElementById("togglestakeshide").style.width="0px";
document.getElementById("togglestakesshow").style.width="150px";};
</script>
</body>
</html>
I have tried lots of different ways to get this working, and have done some testing, and it appears that the value does change at a certain moment in the script, but when the result is outputted when the number buttons are pressed it is always still as 'T'.
"${odEv}"
This is because odEv is a global variable, but then you declare it as a local variable (this becomes a separate variable with no relation to the original). The local variable is the one you're changing.
Remove the var odEv; from workingOdd(), then it will operate on the global variable.
function workingOdd() {
// var odEv; // remove this
if (x % 2 === 0) {
odEv = 'Ev';
} else {
odEv = 'Od';
}
// the rest of the function
}

HTML5 Canvas rectangles click coordinates is inconsistent

I made a canvas size as A4, i draw a rectangles inside and when i click the light blue rectangle it will call a function but the coordinates of the click on the rectangle is inconsistent and every row the y level is needed to click more lower then the light blue rectangle.
How i make the coordinates more accurate?
(Code need full screen)
'use strict';
function mmTopx(mm) {
//return mm * 3.7795275591;
//return mm * 3.7795275590551;
return (mm * 96) / 25.4;
}
function cmTopx(cm) {
return cm * 1; /* NEED TO FIX */
}
// Get mouse position
function getMousePos(c, evt) {
var rect = c.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top,
};
}
class sticker {
#width;
#height;
#fullheight;
constructor(width = 1, height = 1, fullheight = 1) {
if (!sticker.isNumber(width) || !sticker.isNumber(height) || !sticker.isNumber(fullheight)) throw 'Only accept number';
this.#width = width;
this.#height = height;
this.#fullheight = fullheight;
}
static isNumber(n) {
return !isNaN(parseFloat(n)) && !isNaN(n - 0) && typeof n != 'string';
}
get size() {
return { width: this.#width, height: this.#height, fullheight: this.#fullheight };
}
get width() {
return this.#width;
}
get height() {
return this.#height;
}
get fullheight() {
return this.#fullheight;
}
set width(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#width = n;
}
set height(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#height = n;
}
set fullheight(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#fullheight = n;
}
}
window.onload = () => {
const controls = document.querySelectorAll('.control');
const canvas = document.querySelector('.A4');
const canvasPadding = {
left:
window
.getComputedStyle(canvas, null)
.getPropertyValue('padding-left')
.match(/\d+.\d+|\d+/)[0] - 0,
top:
window
.getComputedStyle(canvas, null)
.getPropertyValue('padding-top')
.match(/\d+.\d+|\d+/)[0] - 0,
};
/* ///////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////// */
/* ///// CANVAS ///// */
/* ///////////////////////////////////////////////////// */
/* canvas */
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext('2d');
const _sticker = new sticker(mmTopx(25), mmTopx(12), mmTopx(37));
let Stickers = [];
const drawSticker = (x, y, width, height, fullheight) => {
Stickers.push({
color: '#d8d8d8',
width: width,
height: height,
x: x,
y: y,
clicked: function () {
console.log(`you clicked me, ${this.x} ${this.y}`);
},
});
/* full area */
ctx.fillStyle = '#e8f2f8';
ctx.fillRect(x, y, width, fullheight); // x y width height
/* print area */
ctx.fillStyle = '#d8d8d8';
ctx.fillRect(x, y, width, height, fullheight); // x y width height
};
const render = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Stickers = [];
const size = _sticker.size;
for (let y = 0; y < canvas.height - size.fullheight; y += size.fullheight + 10) {
for (let x = 10; x < canvas.width - size.width; x += size.width + 1) {
drawSticker(x, y, size.width, size.height, size.fullheight);
}
}
};
/* ///////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////// */
/* ///// Event Listeners ///// */
/* ///////////////////////////////////////////////////// */
canvas.addEventListener('updateRender', (event) => {
const lengthType = event.detail.dimensionValue.match(/mm|cm/)[0];
let value = event.detail.dimensionValue.match(/\d+/)[0] - 0;
switch (lengthType) {
case 'cm':
//value = cmTopx(value);
break;
case 'mm':
default:
value = mmTopx(value);
break;
}
/* Set the new sticker size */
switch (event.detail.dimension) {
case 'width':
_sticker.width = value;
break;
case 'height':
_sticker.height = value;
break;
case 'fullheight':
_sticker.fullheight = value;
break;
}
render();
});
const event = new Event('change');
controls.forEach((_control) => {
_control.addEventListener(
'change',
(event) => {
const value = event.target.value;
const name = event.target.name;
const dimension = event.target.getAttribute('data-sticker-dim');
const detail = {};
detail['dimension'] = dimension;
detail['dimensionValue'] = value;
detail['name'] = name;
const updateSticker = new CustomEvent('updateRender', { detail: detail });
canvas.dispatchEvent(updateSticker);
},
true
);
const input = _control.querySelector('input');
input.dispatchEvent(event);
});
/* click event for text input */
canvas.addEventListener('click', function (e) {
e.preventDefault();
let x = parseInt(e.clientX - canvas.offsetLeft - canvasPadding.left);
let y = parseInt(e.clientY - canvas.offsetTop - canvasPadding.top);
if (x >= 0 && y >= 0) {
for (let index = 0; index < Stickers.length; index++) {
const _sticker = Stickers[index];
if (
x >= _sticker.x &&
x <= Math.floor(_sticker.x + _sticker.width) &&
y >= _sticker.y &&
y <= Math.floor(_sticker.y + _sticker.height)
) {
_sticker.clicked();
break;
}
}
}
});
/* ///////////////////////////////////////////////////// */
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
background-color: #fafafa;
}
/* //////////////////////////////////////////////////////////// */
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-self: flex-start;
overflow: auto;
}
/* //////////////////////////////////////////////////////////// */
.container .controllers {
position: sticky;
top: 50%;
transform: translateY(-50%);
width: 250px;
height: 500px;
flex: 0 0 100px;
border-radius: 20px;
box-sizing: border-box;
padding: 20px;
margin-left: 5px;
border: 1px solid #9e9e9e;
}
.container .controllers .control {
position: relative;
flex: 0 0 100%;
height: 50px;
padding: 5px;
}
.container .controllers .control:first-child {
margin-top: 5px;
}
.container .controllers .control:not(:first-child) {
margin-top: 20px;
}
.container .controllers .control label::before {
content: attr(data-placeholder);
position: absolute;
left: 20px;
top: 20px;
color: #65657b;
font-family: sans-serif;
line-height: 14px;
pointer-events: none;
transform-origin: 0 50%;
transition: transform 200ms, color 200ms;
}
.container .controllers .control .cut {
position: absolute;
border-radius: 10px;
height: 20px;
width: fit-content;
left: 20px;
top: -20px;
transform: translateY(0);
transition: transform 200ms;
}
.container .controllers .control input {
height: 100%;
padding: 4px 20px 0;
width: 100%;
background-color: #eeeeee;
border-radius: 12px;
border: 0;
outline: 0;
box-sizing: border-box;
color: #eee;
font-size: 18px;
color: black;
}
.container .controllers .control input:focus ~ .cut,
.container .controllers .control input:not(:placeholder-shown) ~ .cut {
transform: translateY(8px);
}
.container .controllers .control input:focus ~ label::before,
.container .controllers .control input:not(:placeholder-shown) ~ label::before {
content: attr(data-focus-placeholder);
transform: translateY(-30px) translateX(10px) scale(0.75);
}
.container .controllers .control input:not(:placeholder-shown) ~ label::before {
content: attr(data-focus-placeholder);
color: #808097;
}
.container .controllers .control input:focus ~ label::before {
color: #dc2f55;
}
/* //////////////////////////////////////////////////////////// */
.container textarea {
background: none;
outline: none;
}
.container .A4 {
align-self: center;
width: 21cm;
flex: 0 0 29.7cm;
padding: 1cm;
border: 1px #d3d3d3 solid;
border-radius: 5px;
background: #f5f5f5;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
/* //////////////////////////////////////////////////////////// */
#page {
size: A4;
margin: 0;
}
#media print {
html,
body {
height: 99%;
}
.page {
margin: 0;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>A4 Render Stickers</title>
</head>
<body>
<div class="container">
<div class="controllers">
<button>print</button>
<div class="control">
<input type="text" value="25mm" data-sticker-dim="width" name="printWidth" placeholder=" " />
<div class="cut"></div>
<label for="printWidth" data-focus-placeholder="Width print" data-placeholder="Width size of print area"></label>
</div>
<div class="control">
<input type="text" value="12mm" data-sticker-dim="height" name="printHeight" placeholder=" " />
<div class="cut"></div>
<label for="printHeight" data-focus-placeholder="Height print" data-placeholder="Height size of print area"></label>
</div>
<div class="control">
<input type="text" value="37mm" data-sticker-dim="fullheight" name="stikcerHeight" placeholder=" " />
<div class="cut"></div>
<label for="stikcerHeight" data-focus-placeholder="Full height sticker" data-placeholder="Height size of full sticker"></label>
</div>
</div>
<canvas width="800" height="800" class="A4"></canvas>
</div>
</body>
</html>

Website code works fine on Chrome and Firefox, desktop or mobile, but does not work on Safari

A certain piece of my website works fine on Chrome and Firefox, but does not seem to work on Safari. I checked and all the people trying the website on iPhones had Javascript enabled. Is there something about my code that cannot be read by Safari? Are there any tools out there to test how code would be perceived on Safari that I can use with a windows computer?
Below is the code to the piece of my website. I had to replace all images and text with different content because I am forbidden to share the actual content. Essentially, this piece of the website would allow someone to input a certain metric in, via a slider bar, and see what something would look like with said metric. The slider bar seems to be movable, but images are not appearing, nor are they moving when viewing through Safari. As an additional note, I converted this code to https (what Wix refers to as all in one text block) and inserted it into my Wix website as an html element.
I realize that my JavaScript has quite a few redundancies, such as defining the same variable locally twice instead of defining it globally once. I'm looking to fix those later and get this working first (although this could be why it doesn't work on Safari?). I've never developed anything before, so any help at all would be much appreciated.
Update: I had a few people send me screenshots and the slider bar AND javascript are working, the images are just not showing up on Safari.
HTML
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<!-- Box-->
<div class="wholething">
<div class="box">
<!-- Dude -->
<img class="img-square img-dude" src="https://i.pinimg.com/474x/ff/5a/74/ff5a741afd59d527f4492c593b329106--free-clipart-downloads-free-clipart-images.jpg" id="dude" </img>
<!-- Banana-->
<img class="img-square img-bn" src=" https://upload.wikimedia.org/wikipedia/commons/0/0a/Candy-clipart.svg" id="flag">
</img>
<div class="whitebox" id="whiteboxID">
</div>
<img class="gorilla" src="https://openclipart.org/download/249534/1464300474.svg" id="gorillaID" </img>
</div>
<h1 class="sliderlabel" id="sliderlabelID">Hunger level</h1>
<h1 class="sliderlabelinfo" id="sliderlabelinfoID">(drag to select)</h1>
<!-- Slider -->
<div class="slidecontainer">
<input type="range" min="3" max="10" value="5" step="0.1" class="slider" id="inchslider">
<output name="rangeVal" id="value"></output>
</div>
</div>
</body>
</html>
CSS
html {
overflow-y: hidden;
}
.wholething {
height: 100%;
width: 100%;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
.box {
background-color: #F5F4EF;
height: 60%;
width: 81.25%;
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
border-radius: 5%;
}
.img-dude {
position: absolute;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
margin-left: 20px;
height: 90%;
}
.img-bn {
position: absolute;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
z-index: 2;
height: 10.125%;
}
.whitebox {
position: absolute;
background-color: #F5F4EF;
top: 0;
bottom: 0;
height: calc(15% + 15px);
width: calc(15% + 20px);
margin-top: auto;
margin-bottom: auto;
z-index: 1;
}
.gorilla {
position: absolute;
top: 0;
bottom: 0;
right: 0%;
margin-top: auto;
margin-bottom: auto;
z-index: 2;
height: 90%;
display: none;
}
.sliderlabel {
position: absolute;
left: 12.5%;
top: 61%;
font-size: 16px;
font-family: Arial;
font-weight: 900;
}
.sliderlabelinfo {
position: absolute;
left: 12.5%;
top: 66.5%;
font-size: 14px;
font-family: Arial;
font-weight: 500;
}
.slidervalue {
position: absolute;
top: 20px;
left: 28.5%;
}
.slidecontainer {
width: 75%;
position: absolute;
left: 0;
right: 0;
top: 90%;
margin-left: auto;
margin-right: auto;
}
.slider {
-webkit-appearance: none;
-moz-apperance: none;
width: 100%;
height: 10px;
background-image: -webkit-gradient( linear, left top, right top, color-stop(0.15, #4BD1A0), color-stop(0.15, #F5F4EF));
position: absolute;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
border-radius: 5px;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
.slider:hover {
opacity: 1;
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider::-webkit-slider-thumb:hover+output {
display: block;
transform: translateX(-50%);
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider:active {
opacity: 1;
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider::-webkit-slider-thumb:active {
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: #F5F4EF;
cursor: pointer;
border-radius: 50%;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
output {
position: absolute;
top: -50px;
left: calc(28.57% + 3.25px);
width: 80px;
height: 30px;
border: 1px solid #e2e2e2;
background-color: #4BD1A0;
border-radius: 10px;
color: white;
font-size: 14px;
line-height: 30px;
text-align: center;
vertical-align: middle;
display: block;
transform: translateX(-50%);
}
input[type=range]:hover+output {
display: block;
transform: translateX(-50%);
}
input[type=range]:active+output {
display: block;
transform: translateX(-50%);
}
input[type=range] {
background-image: -webkit-gradient(linear, left top, right top, color-stop(0.2857, #4BD1A0), color-stop(0.2857, #F5F4EF))
}
output:after {
content: "";
position: absolute;
width: 0;
height: 0;
border-top: 10px solid #4BD1A0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
top: 100%;
left: 40%;
margin-top: -1px;
}
JavaScript
$(function() {
var element = document.getElementById('dude'),
style = window.getComputedStyle(element),
width = style.getPropertyValue('width'),
height = style.getPropertyValue('height');
var slicedwidth = width.slice(0, -2);
var slicedheight = height.slice(0, -2);
var widthmargarin = ((Number(slicedwidth) * 0.55) + 20).toString() + "px";
var heightmargarin = (Number(slicedheight) * 0.488).toString() + "px";
var whiteboxwidthmargarin = ((Number(slicedwidth) * 0.55) + 25).toString() + "px";
document.getElementById("flag").style.marginLeft = widthmargarin;
document.getElementById("flag").style.marginBottom = heightmargarin;
document.getElementById("value").innerHTML = "5 points";
document.getElementById("whiteboxID").style.marginLeft = whiteboxwidthmargarin;
});
function setIcon(x, y) {
var element = document.getElementById('dude'),
style = window.getComputedStyle(element),
width = style.getPropertyValue('width'),
left = style.getPropertyValue('left'),
height = style.getPropertyValue('height');
var slicedwidth = width.slice(0, -2);
var slicedheight = height.slice(0, -2);
var widthmargarin = ((Number(slicedwidth) * 0.55) + (((x - 5) / 100 * 4.6) * Number(slicedwidth)) + 20).toString() + "px";
var heightmargarin = ((Number(slicedheight) * 0.485) + (((y - 5) / 100 * 0.5) * Number(slicedheight))).toString() + "px";
document.getElementById("flag").style.marginLeft = widthmargarin;
document.getElementById("flag").style.marginBottom = heightmargarin;
document.getElementById("flag").style.transform = "rotate(" + (7 - (x * 1.3)) + "deg)";
document.getElementById("whiteboxID").style.marginLeft = (Number(widthmargarin.slice(0, -2)) + 5).toString() + "px";
document.getElementById("whiteboxID").style.transform = "rotate(" + (7 - (x * 1.5)) + "deg)";
}
var slider = document.getElementById("inchslider");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
var positionXslider = 0;
var positionYslider = 0;
if (this.value >= 5) {
positionXslider = output.innerHTML;
positionYslider = output.innerHTML;
document.getElementById("flag").src = "https://upload.wikimedia.org/wikipedia/commons/0/0a/Candy-clipart.svg";
} else if (this.value >= 4 && this.value < 5) {
positionXslider = 5;
positionYslider = 5;
document.getElementById("flag").src = "https://openclipart.org/download/284444/1502025489.svg";
} else if (this.value < 4) {
positionXslider = 5;
positionYslider = 5;
document.getElementById("flag").src = "https://image.shutterstock.com/image-vector/slice-pizza-on-white-background-260nw-597727904.jpg";
} else {
positionXslider = output.innerHTML;
positionYslider = output.innerHTML;
}
setIcon(positionXslider, positionYslider);
};
$('input[type="range"]').on('input', function() {
var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
$(this).css('background-image',
'-webkit-gradient(linear, left top, right top, ' +
'color-stop(' + val + ', #4BD1A0), ' +
'color-stop(' + val + ', #F5F4EF)' +
')'
);
});
$('input[type="range"]').on('input', function() {
var control = $(this),
controlMin = control.attr('min'),
controlMax = control.attr('max'),
controlVal = control.val(),
controlThumbWidth = 25;
var range = controlMax - controlMin;
var position = ((controlVal - controlMin) / range) * 100;
var positionOffset = Math.round(controlThumbWidth * position / 100) - (controlThumbWidth / 2) + 2.25;
var output = control.next('output');
var controlValNumber = Number(controlVal)
var controlValLabel = 0;
if (controlValNumber >= 5) {
controlValLabel = controlVal.slice(0, 3);
} else if (controlValNumber >= 4 && controlValNumber < 5) {
controlValLabel = 4;
} else if (controlValNumber < 4) {
controlValLabel = 3;
}
if (controlValNumber >= 10) {
document.getElementById("gorillaID").style.display = "block";
} else {
document.getElementById("gorillaID").style.display = "none";
}
output
.css('left', 'calc(' + position + '% - ' + positionOffset + 'px)')
.text(controlValLabel + " points")
});

Fit colliding elements in the container dynamically

I have absolutely positioned elements with different position.top and height generated from database.
All I'm trying to do is to un-collide these elements by shifting them to the right while adjusting width to fit inside the <body> container.
I'm having an issue applying 'left' position to the collided elements.
I use https://sourceforge.net/projects/jquerycollision/ to detect collision.
Here is how the final picture should look:
$('div').each(function() {
var name = $(this).text();
var hits = $(this).collision('div').not(this); // Find colliding elements
console.log(name + ' collides with: ' + hits.length + ' others');
if (hits.length > 0) {
var widthAll = 100 / (hits.length + 1);
// Shift colliding elements to the right with equal width
$(hits).add(this).each(function(i) {
var name = $(this).text();
$(this).css({ 'left': widthAll * i + '%', 'width': widthAll + '%' });
});
}
});
div {
position: absolute;
width: 10em;
font-size: 0.75em;
color: white;
}
.blue {
top: 0;
height: 80%;
background-color: blue;
}
.red {
top: 15%;
height: 5%;
background-color: red;
}
.yellow {
top: 17%;
height: 10%;
background-color: yellow;
color: black;
}
.green {
top: 30%;
height: 5%;
background-color: green;
}
.magenta {
top: 36%;
height: 3%;
background-color: magenta;
}
.cyan {
top: 50%;
height: 5%;
background-color: cyan;
color: black;
}
.brown {
top: 81%;
height: 5%;
background-color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://rawgit.com/dsbaars/jquery-collision/master/js/jquery-collision.min.js"></script>
<div class='blue'>blue</div>
<div class='red'>red</div>
<div class='yellow'>yellow</div>
<div class='green'>green</div>
<div class='magenta'>magenta</div>
<div class='cyan'>cyan</div>
<div class='brown'>brown</div>
I think I have completed your code as you have requested. The idea is,
First block of code shifts the divs to the right so that they don't overlap.
Second block makes the width of the divs evenly distributed according to size of the body.
Last block increases the width of rest of the divs to take remaining space.
"use strict";
var divs = $('div'),
mx = 0,
mxs = [0],
bw = $("body").outerWidth(),
steps = 1;
divs.each(function(i) {
for (var j = i + 1; j < divs.length; j++) {
if (!$(this).data("x")) $(this).data("x", 0);
if (j < divs.length) {
var hit = $(this).collision(divs[j]);
if (hit.length) {
hit = $(divs[j]);
hit.css("left", "+=" + Math.ceil($(this).outerWidth()));
hit.data("x", hit.position().left);
if (mx < hit.data("x")) {
mxs.push(mx = hit.data("x"));
steps++;
}
}
}
}
});
divs.each(function(i) {
let iw = $(this).outerWidth(),
fw = bw / steps;
$(this).outerWidth(fw);
for (var j = i + 1; j < divs.length; j++) {
$(this).collision(divs[j]).css("left", "+=" + Math.ceil((fw - iw) * mxs.indexOf($(divs[j]).data("x"))));
}
});
divs.each(function() {
var os = $(this).outerWidth(),
ts = bw - $(this).position().left;
$(this).outerWidth(ts);
if ($(this).collision(divs).not(this).length) {
$(this).outerWidth(os);
}
});
body {
margin: 0;
}
div {
position: absolute;
width: 10em;
font-size: 0.75em;
color: white;
left: 0;
}
.blue {
top: 0;
height: 80%;
background-color: blue;
}
.red {
top: 15%;
height: 5%;
background-color: red;
}
.yellow {
top: 17%;
height: 10%;
background-color: yellow;
color: black;
}
.green {
top: 20%;
height: 50%;
background-color: green;
}
.magenta {
top: 36%;
height: 3%;
background-color: magenta;
}
.cyan {
top: 50%;
height: 5%;
background-color: cyan;
color: black;
}
.brown {
top: 81%;
height: 5%;
background-color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/dsbaars/jquery-collision/master/js/jquery-collision.min.js"></script>
<div class='blue'>blue</div>
<div class='red'>red</div>
<div class='yellow'>yellow</div>
<div class='green'>green</div>
<div class='magenta'>magenta</div>
<div class='cyan'>cyan</div>
<div class='brown'>brown</div>
Above snippet is non-responsive. If you wish it to be responsive, then simply listen to resize event, change the value of bw and repeat code blocks 2 and 3.
As mentioned in the comments: jquery-collision.min.js had some unressolved bugs so, as suggested by Alex G, https://www.48design.de/de/news/2009/11/20/kollisionsabfrage-per-jquery-plugin-update-v11/ may be an alternative.

Positioning this element to the center of the page - CSS

I've been battling this for quite some time and I'm not having much luck, it always gets repositioned all over the place!
I essentially want my control to center this component in the middle of the page. I also want to rotate flip it(3d) around it's center axis(Y or X, doesn't matter) but I'm having no luck with the first step which is just getting it to the center.
<div className="note-container">
<div className="note"
style={Object.assign({}, note.position) }>
<p>{note.text}</p>
<span>
<button onClick={() => onExpand(note.id) }
className="btn btn-warning glyphicon glyphicon-resize-full"/>
<button onClick={() => onEdit(note.id) }
className="btn btn-primary glyphicon glyphicon-pencil"/>
<button onClick={onRemove}
className="btn btn-danger glyphicon glyphicon-trash"/>
</span>
</div>
</div>
The function I'm calling to reposition it to the center is function onExpand(noteId){...}
Here is the CSS for .note-container and .note
div.note-container {
position: fixed;
top: 5%;
left: 90%;
}
div.note {
height: 150px;
width: 150px;
background-color: yellow;
margin: 2px 0;
position: relative;
cursor: -webkit-grab;
-webkit-box-shadow: 5px 5px 15px 0 rgba(0, 0, 0, .2);
box-shadow: 5px 5px 15px 0 rgba(0, 0, 0, .2);
}
div.note:active {
cursor: -webkit-grabbing;
}
div.note p {
font-size: 22px;
padding: 5px;
font-family: "Shadows Into Light", Arial;
}
div.note div.back p {
font-size: 30px;
padding: 5px;
font-family: "Shadows Into Light", Arial;
}
div.note:hover> span {
opacity: 1;
}
div.note> span {
position: absolute;
bottom: 2px;
right: 2px;
opacity: 0;
transition: opacity .25s linear;
}
div.note button {
margin: 2px;
}
div.note> textarea {
height: 75%;
background: rgba(255, 255, 255, .5);
}
And here is the onExpand function
onExpand(noteId) {
//This needs a lot of work....
event.preventDefault();
let flippedNote = this.props.notes
.filter(note => note.id === noteId)[0];
flippedNote.position.transition = "1.0s";
flippedNote.position.transformStyle = "preserve-3d";
flippedNote.position.backgroundColor = "#3498db";
flippedNote.position.color = "white";
flippedNote.position.width = "300px";
flippedNote.position.height = "300px";
flippedNote.position.position = "absolute";
flippedNote.position.right = `50% -${flippedNote.position.width / 2}px`;
flippedNote.position.top = `50% -${flippedNote.position.height / 2}px`;
// flippedNote.position.transform = "translate(-50%, -50%) rotateY(180deg)";
this.setState({/*Stuff later... */});
}
Also when I render the note on the page I assign it a random location on the page based on this logic(this is what is initially passed into the style attribute in the div.note element:
position: {
right: randomBetween(0, window.innerWidth - 150) + "px",
top: randomBetween(0, window.innerHeight - 150) + "px",
transform: "rotate(" + randomBetween(-15, 15) + "deg)"
}
Here is what the html on the page looks like(note I am also dragging the sticky note across the page using transform: translate(...).
try this:
div.note
{
position: relative;
width: 150px;
left: 0;
right: 0;
margin: 2px auto;
}
To control the position, you can set position: relative; or position: absolute; on your div.note.
Alternatively, this can be done by manipulating margins, but it's not really a good way.
You can test your code manually by opening the page in browser and manipulating CSS values through Chrome's developer tools.
Here is the final solution after working on it this weekend:
onExpand(noteId, currentNotePosition) {
event.preventDefault();
let note = this.props.notes
.filter(specificNote => specificNote.id === noteId)[0];
const centerOfWindow = {
left: window.innerWidth / 2,
top: window.innerHeight / 2
};
if (!note.centered) {
note.position.transition = "all 1s";
note.position.transformStyle = "preserve-3d";
note.position.backgroundColor = "#3498db";
note.position.color = "white";
note.position.width = "300px";
note.position.height = "300px";
note.position.zIndex = "100";
note.position.position = "relative";
const offset = {
x: 150,
y: 150
};
const translatedCoordinates = this.getCoordinateTarget(centerOfWindow, offset, currentNotePosition);
note.position.transform = `translate(${translatedCoordinates.x}px, ${translatedCoordinates.y}px) rotateY(180deg)`;
note.originalPosition = {
left: currentNotePosition.left,
top: currentNotePosition.top,
width: currentNotePosition.width,
movement: translatedCoordinates
};
note.centered = true;
} else {
note.position.backgroundColor = "yellow";
note.position.color = "black";
note.position.width = "150px";
note.position.height = "150px";
note.position.transform = "";
note.centered = false;
}
this.props.stickyNoteActions.repositionedNoteSuccess(Object.assign({}, note));
}

Categories

Resources