I've found this and tried to fix it as the logic behind it is similar to what I'm trying to achieve. I've manage to get it working with minimal editing. but it isn't working as expected.
note: I have commented out the click feature as it is working fine.
What is happening
If you click on the volumeBtn and accidentally move the cursor out of the volumeRange div height or width while sliding either left or right, the mouseup event listener doesn't get executed when you stop clicking the mouse.
Like 1, after clicking the volumeBtn you cannot drag the volumeBtn left or right once it goes outside the `volumeRange' div.
There is a flicker from the zeroth position to the desired position.
What I Want to happen
If you click on the volumeBtn then stop clicking the mouse, the mouseup event should be executed even if the cursor is no longer on the volumeRange.
If you click on the volumeBtn you should be able to drag the volumeBtn left or right even if the cursor is no longer on the volumeRange.
const volume = document.querySelector('.volume');
const volumeRange = document.querySelector('.volume-range');
const volumeBtn = document.querySelector('.volume-button');
// volumeRange.addEventListener("click", volumeClick );
// function volumeClick(event) {
// let x = event.offsetX;
// volume.style.width = (Math.floor(x) + 10) + 'px';
// }
let mouseIsDown = false;
volumeBtn.addEventListener("mouseup", up);
volumeBtn.addEventListener("mousedown", down);
volumeRange.addEventListener("mousemove", volumeSlide);
function down(){ mouseIsDown = true; }
function up(){ mouseIsDown = false; }
function volumeSlide(event) {
if (mouseIsDown) {
let x = event.offsetX;
console.log(x);
volume.style.width = Math.floor(x + 10) + 'px';
}
}
body {
background-color: #2a2a2a;
}
.volume-range {
margin-top: 80px;
height: 5px;
width: 250px;
background: #555;
border-radius: 15px;
}
.volume-range>.volume {
height: 5px;
width: 50px;
background: #2ecc71;
border: none;
border-radius: 10px;
outline: none;
position: relative;
}
.volume-range>.volume>.volume-button {
width: 20px;
height: 20px;
border-radius: 20px;
background: #FFF;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Volume</title <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<style>
</style>
<body>
<div class="volume-range">
<div class="volume">
<div class="volume-button"></div>
</div>
</div>
</body>
</html>
Why it doesn't work
This is working the way you described it because mouse events will only be fired when the mouse is inside the element that have the listeners attached.
An immediate (but not very good) solution to this will be to move the listener for "mouseup" and "mousemove" from the volumeBtn/volumeRange to the window object. This is not very good because if you will later need to remove this element, you should also remove the listeners from the window object.
Better solution
It would be better to encapsulate the slider inside another element that will give it some padding, and then put the event listeners on that "container" element. It will still stop moving when you go outside the element, but at least everything is self-contained.
This is shown in the following snippet:
const volume = document.querySelector('.volume');
const volumeRange = document.querySelector('.volume-range');
const volumeContainer = document.querySelector('.volume-container');
const volumeBtn = document.querySelector('.volume-button');
// volumeRange.addEventListener("click", volumeClick );
// function volumeClick(event) {
// let x = event.offsetX;
// volume.style.width = (Math.floor(x) + 10) + 'px';
// }
let mouseIsDown = false;
volumeContainer.addEventListener("mouseup", up);
volumeBtn.addEventListener("mousedown", down);
volumeContainer.addEventListener("mousemove", volumeSlide, true);
function down(){ mouseIsDown = true; }
function up(){ mouseIsDown = false; }
const volumeRangeWidth = volumeRange.getBoundingClientRect().width; // This will be the volume limit (100%)
function volumeSlide(event) {
if (mouseIsDown) {
let x = event.offsetX;
if (event.target.className == "volume-container") {
x = Math.floor(x);
if (x < 0) x = 0; // check if it's too low
if (x > volumeRangeWidth) x = volumeRangeWidth; // check if it's too high
volume.style.width = (x+10) + 'px';
}
}
}
body {
background-color: #2a2a2a;
}
.volume-container {
padding: 40px 0px;
margin: 0px 20px;
}
.volume-range {
height: 5px;
width: 250px;
background: #555;
border-radius: 15px;
}
.volume-range>.volume {
height: 5px;
width: 50px;
background: #2ecc71;
border: none;
border-radius: 10px;
outline: none;
position: relative;
}
.volume-range>.volume>.volume-button {
width: 20px;
height: 20px;
border-radius: 20px;
background: #FFF;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Volume</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<style>
</style>
<body>
<div class="volume-container">
<div class="volume-range">
<div class="volume">
<div class="volume-button"></div>
</div>
</div>
</div>
</body>
</html>
Other problems
In the fiddle it is also shown how to avoid the volume to go outside the container.
Related
//Global variables
let count = 1;
let canvas = document.querySelector('#canvas');
let canvasContainer = document.querySelector('.canvas-container');
let designBtn = document.querySelector('#design-btn');
let editBtn = document.querySelector('#edit-btn');
let isDesign = false;
let isEdit = false;
let circleArray = [];
let offset = [];
//Click event listener for design button
designBtn.addEventListener('click', (event)=>{
isDesign = true;
isEdit = false;
designBtn.style.backgroundColor = '#BA4A00'
designBtn.style.color = '#17202A'
editBtn.style.backgroundColor = null;
editBtn.style.color = null
//Invoke being_design function
begin_design()
})
//Click event listener for edit button
editBtn.addEventListener('click', (event)=>{
isDesign = false;
isEdit = true;
editBtn.style.backgroundColor = '#BA4A00'
editBtn.style.color = '#17202A'
designBtn.style.backgroundColor = null;
designBtn.style.color = null
//Invoke edit_design function
edit_design()
})
//Function creates new element and then appends it to the parent div
function create_circle_element(x, y){
let circle = document.createElement('div')
const circleHeight = 40;
const circleWidth = 40;
circle.style.position = 'absolute';
circle.style.backgroundColor = 'orange';
circle.style.height = `${circleHeight}px`;
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = '50%'
circle.style.textAlign = 'center';
circle.style.lineHeight = `${circleHeight}px`;
circle.style.cursor = 'pointer';
circle.style.left = `${(x - (canvas.offsetLeft + canvasContainer.offsetLeft - window.scrollX)) - (circleWidth/2)}px`;
circle.style.top = `${(y -(canvas.offsetTop + canvasContainer.offsetTop - window.scrollY)) - (circleHeight/2)}px`
circle.textContent = `${count}`;
canvas.append(circle)
circleArray.push(circle)
count++
}
//Function responsible for adding circles to the canvas
//Function is invoked when design button is clicked
function begin_design(){
let mousePosition;
canvas.addEventListener('mousedown', (event)=>{
if(isDesign){
mousePosition = {
x: event.clientX,
y: event.clientY
}
create_circle_element(mousePosition.x, mousePosition.y);
}
})
}
//Function responsible for editing the circles on the canvas i.e moving them around on mousedown/mousemove event
//Function is invoked when edit button is clicked
function edit_design(){
if(isEdit){
let mouseDown = false;
let offset = [];
let circleClickedOn = [];
//Set mouseDown to false
canvas.addEventListener('mouseup', ()=>{
mouseDown = false
})
//Loop through the newly created circles and attached 'mousedown' event to each
circleArray.forEach((circleElement)=>{
circleElement.addEventListener('mousedown', (event)=>{
mouseDown = true;
offset = [
circleElement.offsetLeft - event.clientX,
circleElement.offsetTop - event.clientY
]
circleClickedOn = [circleElement]
})
})
//Move circles around
canvas.addEventListener('mousemove', (event)=>{
if(mouseDown){
let mousePosition;
mousePosition = {
x: event.clientX,
y: event.clientY
}
circleClickedOn[0].style.left = `${offset[0] + mousePosition.x}px`
circleClickedOn[0].style.top = `${offset[1] + mousePosition.y}px`
}
})
}
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
width: 100%;
min-height: 100vh;
}
.sidebar{
position: fixed;
top: 0;
left: 0;
background-color: #17202A;
width: 50px;
min-height: 100vh;
}
.sidebar .sidebar-top{
position: relative;
height: 35px;
}
.sidebar .sidebar-top #toggle-btn{
position: absolute;
display: flex;
height: 35px;
width: 100%;
justify-content: center;
align-items: center;
font-size: 18px;
cursor: pointer;
color: #808B96
}
.sidebar .sidebar-center{
position: relative;
width: 100%;
margin-top: 15px;
}
.sidebar .sidebar-center ul li{
position: relative;
height: 35px;
margin-bottom: 5px;
list-style: none;
}
.sidebar .sidebar-center ul li a{
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 35px;
text-decoration: none
}
.sidebar .sidebar-center ul li a{
font-size: 18px;
color: #808B96
}
.sidebar .sidebar-center ul li a:hover{
background-color: #2e4053
}
.canvas-container{
position: absolute;
top: 0;
width: calc(100% - 50px);
min-height: 100vh;
left: 50px;
padding: 20px;
background-color: #2E4053
}
.canvas-container #canvas{
position: relative;
width: 100%;
min-height: 100vh;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>testing</title>
<link rel="stylesheet" href="style.css">
<!-- Boxicons CDN Link -->
<link href='https://unpkg.com/boxicons#2.0.7/css/boxicons.min.css' rel='stylesheet'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="sidebar">
<div class="sidebar-top">
<i class='bx bx-menu' id="toggle-btn"></i>
</div>
<div class="sidebar-center">
<ul class="nav-list">
<li>
<a href="#" id="design-btn">
<i class='bx bx-pyramid'></i>
</a>
</li>
<li>
<a href="#" id="edit-btn">
<i class='bx bxs-edit-alt'></i>
</a>
</li>
</ul>
</div>
</div>
<div class="canvas-container">
<div id="canvas"></div>
<script src="script.js"></script>
</body>
</html>
Objective - When user clicks design button, the circles are added to the canvas on mousedown event. When user clicks the edit button, they are able to move the circles around. When the design button is clicked again, user is able to continue adding circles and incrementing the number from where it was left off.
Error to resolve - When design is first clicked, I am able to successfully add circles to the canvas. If I click on edit button and move the circles around and then click on design button right after, it appends two circles on on click. Why is it appending two circles? This only happens after I click on edit.
***JAVASCRIPT***
//Global variables
let count = 1;
let canvas = document.querySelector('#canvas');
let canvasContainer = document.querySelector('.canvas-container')
let designBtn = document.querySelector('#design-btn');
let editBtn = document.querySelector('#edit-btn');
let isDesign = false;
let isEdit = false;
let circleArray = [];
let offset = []
//Click event listener for design button
designBtn.addEventListener('click', (event)=>{
isDesign = true;
isEdit = false;
designBtn.style.backgroundColor = '#BA4A00'
designBtn.style.color = '#17202A'
editBtn.style.backgroundColor = null;
editBtn.style.color = null
//Invoke being_design function
begin_design()
})
//Click event listener for edit button
editBtn.addEventListener('click', (event)=>{
isDesign = false;
isEdit = true;
editBtn.style.backgroundColor = '#BA4A00'
editBtn.style.color = '#17202A'
designBtn.style.backgroundColor = null;
designBtn.style.color = null
//Invoke edit_design function
edit_design()
})
//Function creates new element and then appends it to the parent div
function create_circle_element(x, y){
let circle = document.createElement('div')
const circleHeight = 40;
const circleWidth = 40;
circle.style.position = 'absolute';
circle.style.backgroundColor = 'orange';
circle.style.height = `${circleHeight}px`;
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = '50%'
circle.style.textAlign = 'center';
circle.style.lineHeight = `${circleHeight}px`;
circle.style.cursor = 'pointer';
circle.style.left = `${(x - (canvas.offsetLeft + canvasContainer.offsetLeft - window.scrollX)) - (circleWidth/2)}px`;
circle.style.top = `${(y -(canvas.offsetTop + canvasContainer.offsetTop - window.scrollY)) - (circleHeight/2)}px`
circle.textContent = `${count}`;
canvas.append(circle)
circleArray.push(circle)
count++
}
//Function responsible for adding circles to the canvas
//Function is invoked when design button is clicked
function begin_design(){
let mousePosition;
canvas.addEventListener('mousedown', (event)=>{
if(isDesign){
mousePosition = {
x: event.clientX,
y: event.clientY
}
create_circle_element(mousePosition.x, mousePosition.y)
}
})
}
//Function responsible for editing the circles on the canvas i.e moving them around on mousedown/mousemove event
//Function is invoked when edit button is clicked
function edit_design(){
if(isEdit){
let mouseDown = false;
let offset = [];
let circleClickedOn = [];
//Set mouseDown to false
canvas.addEventListener('mouseup', ()=>{
mouseDown = false
})
//Loop through the newly created circles and attached 'mousedown' event to each
circleArray.forEach((circleElement)=>{
circleElement.addEventListener('mousedown', (event)=>{
mouseDown = true;
offset = [
circleElement.offsetLeft - event.clientX,
circleElement.offsetTop - event.clientY
]
circleClickedOn = [circleElement]
})
})
//Move circles around
canvas.addEventListener('mousemove', (event)=>{
if(mouseDown){
let mousePosition;
mousePosition = {
x: event.clientX,
y: event.clientY
}
circleClickedOn[0].style.left = `${offset[0] + mousePosition.x}px`
circleClickedOn[0].style.top = `${offset[1] + mousePosition.y}px`
}
})
}
}
***HTML***
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Testing</title>
<link rel="stylesheet" href="style.css">
<!-- Boxicons CDN Link -->
<link href='https://unpkg.com/boxicons#2.0.7/css/boxicons.min.css' rel='stylesheet'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="sidebar">
<div class="sidebar-top">
<i class='bx bx-menu' id="toggle-btn"></i>
</div>
<div class="sidebar-center">
<ul class="nav-list">
<li>
<a href="#" id="design-btn">
<i class='bx bx-pyramid'></i>
</a>
</li>
<li>
<a href="#" id="edit-btn">
<i class='bx bxs-edit-alt'></i>
</a>
</li>
</ul>
</div>
</div>
<div class="canvas-container">
<div id="canvas"></div>
<script src="script.js"></script>
</body>
</html>
***CSS***
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
width: 100%;
min-height: 100vh;
}
.sidebar{
position: fixed;
top: 0;
left: 0;
background-color: #17202A;
width: 50px;
min-height: 100vh;
}
.sidebar .sidebar-top{
position: relative;
height: 35px;
}
.sidebar .sidebar-top #toggle-btn{
position: absolute;
display: flex;
height: 35px;
width: 100%;
justify-content: center;
align-items: center;
font-size: 18px;
cursor: pointer;
color: #808B96
}
.sidebar .sidebar-center{
position: relative;
width: 100%;
margin-top: 15px;
}
.sidebar .sidebar-center ul li{
position: relative;
height: 35px;
margin-bottom: 5px;
list-style: none;
}
.sidebar .sidebar-center ul li a{
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 35px;
text-decoration: none
}
.sidebar .sidebar-center ul li a{
font-size: 18px;
color: #808B96
}
.sidebar .sidebar-center ul li a:hover{
background-color: #2e4053
}
.canvas-container{
position: absolute;
top: 0;
width: calc(100% - 50px);
min-height: 100vh;
left: 50px;
padding: 20px;
background-color: #2E4053
}
.canvas-container #canvas{
position: relative;
width: 100%;
min-height: 100vh;
}
The issue is you're registering the mouse-down event handler in design mode every time user switches to the design mode.
However you never unregister the mouse-down event handler upon switching to edit mode.
This results in multiple event handler to be registered for canvas click event(mouse-down).
So whenever you switch back to the design mode and click upon the canvas, it fires click handler for previously registered listener as well as the newly registered listener.
Check the updated snippet
Comment lines marked with // Solution :
//Global variables
let count = 1;
let canvas = document.querySelector('#canvas');
let canvasContainer = document.querySelector('.canvas-container');
let designBtn = document.querySelector('#design-btn');
let editBtn = document.querySelector('#edit-btn');
let isDesign = false;
let isEdit = false;
let circleArray = [];
let offset = [];
//Click event listener for design button
designBtn.addEventListener('click', (event)=>{
isDesign = true;
isEdit = false;
designBtn.style.backgroundColor = '#BA4A00'
designBtn.style.color = '#17202A'
editBtn.style.backgroundColor = null;
editBtn.style.color = null
//Invoke being_design function
begin_design()
})
//Click event listener for edit button
editBtn.addEventListener('click', (event)=>{
isDesign = false;
isEdit = true;
editBtn.style.backgroundColor = '#BA4A00'
editBtn.style.color = '#17202A'
designBtn.style.backgroundColor = null;
designBtn.style.color = null
//Invoke edit_design function
edit_design()
})
//Function creates new element and then appends it to the parent div
function create_circle_element(x, y){
let circle = document.createElement('div')
const circleHeight = 40;
const circleWidth = 40;
circle.style.position = 'absolute';
circle.style.backgroundColor = 'orange';
circle.style.height = `${circleHeight}px`;
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = '50%'
circle.style.textAlign = 'center';
circle.style.lineHeight = `${circleHeight}px`;
circle.style.cursor = 'pointer';
circle.style.left = `${(x - (canvas.offsetLeft + canvasContainer.offsetLeft - window.scrollX)) - (circleWidth/2)}px`;
circle.style.top = `${(y -(canvas.offsetTop + canvasContainer.offsetTop - window.scrollY)) - (circleHeight/2)}px`
circle.textContent = `${count}`;
canvas.append(circle)
circleArray.push(circle)
count++
}
// Solution : Define a click handler
var designClickHandler = (event)=>{
if(isDesign){
mousePosition = {
x: event.clientX,
y: event.clientY
}
create_circle_element(mousePosition.x, mousePosition.y);
}
}
//Function responsible for adding circles to the canvas
//Function is invoked when design button is clicked
function begin_design(){
let mousePosition;
// Solution : Register click handler
canvas.addEventListener('mousedown', designClickHandler)
}
//Function responsible for editing the circles on the canvas i.e moving them around on mousedown/mousemove event
//Function is invoked when edit button is clicked
function edit_design(){
if(isEdit){
// Solution : unregister click handler
canvas.removeEventListener('mousedown', designClickHandler)
let mouseDown = false;
let offset = [];
let circleClickedOn = [];
//Set mouseDown to false
canvas.addEventListener('mouseup', ()=>{
mouseDown = false
})
//Loop through the newly created circles and attached 'mousedown' event to each
circleArray.forEach((circleElement)=>{
circleElement.addEventListener('mousedown', (event)=>{
mouseDown = true;
offset = [
circleElement.offsetLeft - event.clientX,
circleElement.offsetTop - event.clientY
]
circleClickedOn = [circleElement]
})
})
//Move circles around
canvas.addEventListener('mousemove', (event)=>{
if(mouseDown){
let mousePosition;
mousePosition = {
x: event.clientX,
y: event.clientY
}
circleClickedOn[0].style.left = `${offset[0] + mousePosition.x}px`
circleClickedOn[0].style.top = `${offset[1] + mousePosition.y}px`
}
})
}
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
width: 100%;
min-height: 100vh;
user-select: none;
}
.sidebar{
position: fixed;
top: 0;
left: 0;
background-color: #17202A;
width: 50px;
min-height: 100vh;
}
.sidebar .sidebar-top{
position: relative;
height: 35px;
}
.sidebar .sidebar-top #toggle-btn{
position: absolute;
display: flex;
height: 35px;
width: 100%;
justify-content: center;
align-items: center;
font-size: 18px;
cursor: pointer;
color: #808B96
}
.sidebar .sidebar-center{
position: relative;
width: 100%;
margin-top: 15px;
}
.sidebar .sidebar-center ul li{
position: relative;
height: 35px;
margin-bottom: 5px;
list-style: none;
}
.sidebar .sidebar-center ul li a{
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 35px;
text-decoration: none
}
.sidebar .sidebar-center ul li a{
font-size: 18px;
color: #808B96
}
.sidebar .sidebar-center ul li a:hover{
background-color: #2e4053
}
.canvas-container{
position: absolute;
top: 0;
width: calc(100% - 50px);
min-height: 100vh;
left: 50px;
padding: 20px;
background-color: #2E4053
}
.canvas-container #canvas{
position: relative;
width: 100%;
min-height: 100vh;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>hiveport</title>
<link rel="stylesheet" href="style.css">
<!-- Boxicons CDN Link -->
<link href='https://unpkg.com/boxicons#2.0.7/css/boxicons.min.css' rel='stylesheet'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="sidebar">
<div class="sidebar-top">
<i class='bx bx-menu' id="toggle-btn"></i>
</div>
<div class="sidebar-center">
<ul class="nav-list">
<li>
<a href="#" id="design-btn">
<i class='bx bx-pyramid'></i>
</a>
</li>
<li>
<a href="#" id="edit-btn">
<i class='bx bxs-edit-alt'></i>
</a>
</li>
</ul>
</div>
</div>
<div class="canvas-container">
<div id="canvas"></div>
<script src="script.js"></script>
</body>
</html>
how can i create dialog effect like google keep.i tried to debug the css but without any success.
is there code example out there ?
i see that they using hidden position fixed modal that triggering on click but how they calculate the position.
This is what i could make out of your question(pure JS and CSS).
Below is the code
var example_note = document.getElementsByClassName('example_note')[0];
var close_btn = document.getElementById('close_btn');
example_note.onclick = function() {
document.getElementsByClassName('background_change')[0].style.display = "block";
document.getElementsByClassName('display_block')[0].style.display = "block";
example_note.style.display="none";
}
close_btn.onclick = function() {
document.getElementsByClassName('background_change')[0].style.display = "none";
document.getElementsByClassName('display_block')[0].style.display = "none";
example_note.style.display="block";
}
* {
margin: 0px;
padding: 0px;
font-family: 'arial';
}
.example_note {
position: absolute;
width: 250px;
margin-top: 10%;
margin-left: 15%;
box-shadow: -1px 1px 10px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: -1px 1px 10px 3px rgba(0, 0, 0, 0.2);
-moz-box-shadow: -1px 1px 10px 3px rgba(0, 0, 0, 0.2);
padding: 30px;
border-radius: 15px;
background-color: white;
}
.example_note h1 {
font-size: 23px;
}
.display_block {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 450px;
background-color: white;
padding: 30px;
border-radius: 15px;
transform-origin: 0 25%;
animation: show_block 0.2s 1;
}
#keyframes show_block {
from {
transform: translate(-50%, -50%)scale(0);
}
to {
transform: translate(-50%, -50%)scale(1);
}
}
input[type="text"] {
width: 390px;
padding: 10px;
border: none;
}
input[type="text"]:focus {
outline: none;
}
button {
float: right;
background-color: white;
padding: 10px 20px 10px 20px;
border-radius: 8px;
border: none;
font-size: 17px;
transition: 0.4s;
font-weight: bold;
outline: none;
}
button:hover {
background-color: #E3E3E3;
}
.background_change {
display: none;
height: 100%;
width: 100%;
position: absolute;
background-color: black;
opacity: 0.6;
animation: show_back 0.5s 1;
}
#keyframes show_back {
from {
opacity: 0;
}
to {
opacity: 0.6;
}
}
<div class="example_note">
<h1>Example Note</h1>
</div>
<div class="background_change"></div>
<div class="display_block">
<input type="text" name="title" placeholder="Title" style="font-size: 25px;">
<br>
<input type="text" name="name" value="Example Note" style="font-size: 15px; font-weight: bold;">
<br>
<button id="close_btn">close</button>
</div>
This answer is plain JavaScript and CSS (no libraries), and produces the following effect:
A full working example is contained in the following snippet (best previewed full screen):
function openModal(noteEl, modalEl, modalContainerEl) {
// Compute and apply the transform to deform the modal to cover the note with a transition to make it animate
const transform = computeTransform(noteEl);
modalEl.style.transform = transform;
modalEl.style.transition = 'transform 250ms';
// Setup the modal background animate in too
modalContainerEl.style.backgroundColor = 'transparent';
modalContainerEl.style.transition = 'background-color 250ms';
// Show the modal
modalContainerEl.classList.add('modal-container--open');
// Put the rest in a setTimeout to allow the styles applied above to take
// affect and render before we overwrite them with new ones below
setTimeout(function () {
// Remove the transform to allow the modal to return to it's natural shape and position
modalEl.style.transform = 'none';
modalContainerEl.style.backgroundColor = 'rgba(33, 33, 33, 0.5)';
}, 0)
}
function computeTransform(noteEl) {
// Modal positions here are hardcoded to match styles set in CSS
const modalTop = 150;
const modalLeft = (document.body.offsetWidth / 2) - 300;
const modalWidth = 600;
const modalHeight = 150;
// Get note div's position relative to the viewport
const notePosition = noteEl.getBoundingClientRect();
// Compute a CSS transform that moves the modal to match the note's position
const translateX = notePosition.left - modalLeft;
const translateY = notePosition.top - modalTop;
const scaleX = notePosition.width / modalWidth;
const scaleY = notePosition.height / modalHeight;
return `translateX(${translateX}px) translateY(${translateY}px) scaleX(${scaleX}) scaleY(${scaleY})`;
}
// Handle click events using event delegation
document.addEventListener('click', function (event) {
// Handle click events on note elements (open modal)
if (event.target.className === 'note') {
// Get a reference
const modalContainerEl = document.querySelector('.modal-container');
const modalEl = document.querySelector('.modal');
openModal(event.target, modalEl, modalContainerEl);
}
// Handle click event on modal background element (close modal)
if (event.target.classList.contains('modal-container')) {
event.target.classList.remove('modal-container--open');
}
})
body {
display: flex;
flex-wrap: wrap;
width: 100%;
color: #333;
}
.note {
flex: 0 0 200px;
width: 200px;
height: 200px;
border: 1px solid #CCC;
margin: 12px;
border-radius: 10px;
}
.modal-container {
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(33, 33, 33, 0.5);
}
.modal-container--open {
display: block;
}
.modal {
position: absolute;
top: 150px;
left: 50%;
margin-left: -300px;
width: 600px;
height: 150px;
transform-origin: top left;
will-change: transform; /* makes the animation run smoother */
background-color: #EEE;
border-radius: 10px;
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css" />
</style>
<script type="text/javascript">
</script>
</head>
<body>
<div class="note">1</div>
<div class="note">2</div>
<div class="note">3</div>
<div class="note">4</div>
<div class="note">5</div>
<div class="note">6</div>
<div class="note">7</div>
<div class="note">8</div>
<div class="note">9</div>
<div class="note">10</div>
<div class="note">11</div>
<div class="note">12</div>
<div class="note">13</div>
<div class="note">14</div>
<div class="note">15</div>
<div class="note">16</div>
<div class="note">17</div>
<div class="note">18</div>
<div class="note">19</div>
<div class="note">20</div>
<div class="modal-container">
<div class="modal">
Modal
</div>
</div>
</body>
</html>
The trick is to apply a CSS transform to the modal in order to deform into the shape/position of the clicked note before showing the modal. We can then remove the transform and use a CSS transition to get it to smoothly animate into it's natural shape/position.
We calculate the transform as follows:
function computeTransform(noteEl) {
// Modal positions here are hardcoded to match styles set in CSS
const modalTop = 150;
const modalLeft = (document.body.offsetWidth / 2) - 300;
const modalWidth = 600;
const modalHeight = 150;
// Get note div's position relative to the viewport
const notePosition = noteEl.getBoundingClientRect();
// Compute a CSS transform that moves the modal to match the note's position
const translateX = notePosition.left - modalLeft;
const translateY = notePosition.top - modalTop;
const scaleX = notePosition.width / modalWidth;
const scaleY = notePosition.height / modalHeight;
return `translateX(${translateX}px) translateY(${translateY}px) scaleX(${scaleX}) scaleY(${scaleY})`;
}
And we apply it as follows:
function openModal(noteEl, modalEl, modalContainerEl) {
// Compute and apply the transform to deform the modal to cover the note with a transition to make it animate
const transform = computeTransform(noteEl);
modalEl.style.transform = transform;
modalEl.style.transition = 'transform 250ms';
// Setup the modal background animate in too
modalContainerEl.style.backgroundColor = 'transparent';
modalContainerEl.style.transition = 'background-color 250ms';
// Show the modal
modalContainerEl.classList.add('modal-container--open');
// Put the rest in a setTimeout to allow the styles applied above to take
// affect and render before we overwrite them with new ones below
setTimeout(function () {
// Remove the transform to allow the modal to return to it's natural shape and position
modalEl.style.transform = 'none';
modalContainerEl.style.backgroundColor = 'rgba(33, 33, 33, 0.5)';
}, 0)
}
Note the setTimeout between applying and removing the transform. This is important as otherwise the transform will never actually be applied.
See the snippet for the full details, but also of note: the transform-origin: top left; style on the modal is important to make the transform computation work.
I did like the example above, wich worked perfectly. I added opacity to de card selected to remove erase the card from the screen when it is clicked
<style type="text/css">
body {
display: flex;
flex-wrap: wrap;
width: 100%;
color: #333;
}
.note {
flex: 0 0 200px;
width: 200px;
height: 200px;
border: 1px solid #CCC;
margin: 12px;
border-radius: 10px;
}
.modal-container {
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(33, 33, 33, 0.5);
}
.modal-container--open {
display: block;
}
.modal {
position: absolute;
top: 150px;
left: 50%;
margin-left: -300px;
width: 600px;
height: 150px;
transform-origin: top left;
will-change: transform;
/* makes the animation run smoother */
background-color: #EEE;
border-radius: 10px;
}
</style>
<script type="text/javascript">
function openModal(noteEl, modalEl, modalContainerEl) {
// Compute and apply the transform to deform the modal to cover the note with a transition to make it animate
const transform = computeTransform(noteEl);
modalEl.style.transform = transform;
modalEl.style.transition = 'transform 250ms';
// Setup the modal background animate in too
modalContainerEl.style.backgroundColor = 'transparent';
modalContainerEl.style.transition = 'background-color 250ms';
// Show the modal
modalContainerEl.classList.add('modal-container--open');
noteEl.style.opacity = 0;
// Put the rest in a setTimeout to allow the styles applied above to take
// affect and render before we overwrite them with new ones below
setTimeout(function () {
// Remove the transform to allow the modal to return to it's natural shape and position
modalEl.style.transform = 'none';
modalContainerEl.style.backgroundColor = 'rgba(33, 33, 33, 0.5)';
}, 0)
}
function computeTransform(noteEl) {
// Modal positions here are hardcoded to match styles set in CSS
const modalTop = 150;
const modalLeft = (document.body.offsetWidth / 2) - 300;
const modalWidth = 600;
const modalHeight = 150;
// Get note div's position relative to the viewport
const notePosition = noteEl.getBoundingClientRect();
// Compute a CSS transform that moves the modal to match the note's position
const translateX = notePosition.left - modalLeft;
const translateY = notePosition.top - modalTop;
const scaleX = notePosition.width / modalWidth;
const scaleY = notePosition.height / modalHeight;
return `translateX(${translateX}px) translateY(${translateY}px) scaleX(${scaleX}) scaleY(${scaleY})`;
}
// Handle click events using event delegation
let cardSelected;
document.addEventListener('click', function (event) {
// Handle click events on note elements (open modal)
if (event.target.className === 'note') {
// Get a reference
cardSelected = event.target
const modalContainerEl = document.querySelector('.modal-container');
const modalEl = document.querySelector('.modal');
openModal(event.target, modalEl, modalContainerEl);
}
// Handle click event on modal background element (close modal)
if (event.target.classList.contains('modal-container')) {
event.target.classList.remove('modal-container--open');
cardSelected.style.opacity = 1;
}
})
</script>
<div class="note">1</div>
<div class="note">2</div>
<div class="note">3</div>
<div class="note">4</div>
<div class="note">5</div>
<div class="note">6</div>
<div class="note">7</div>
<div class="note">8</div>
<div class="note">9</div>
<div class="note">10</div>
<div class="note">11</div>
<div class="note">12</div>
<div class="note">13</div>
<div class="note">14</div>
<div class="note">15</div>
<div class="note">16</div>
<div class="note">17</div>
<div class="note">18</div>
<div class="note">19</div>
<div class="note">20</div>
<div class="modal-container">
<div class="modal">
Modal
</div>
</div>
To create a modal, you can use a library called Swal. Swal, however does not look like keep's popups, so I've restyled it below.
script links you must reference to:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#sweetalert2/theme-material-ui/material-ui.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10"></script>. You may also wish to visit Google Fonts and pick a nice font-family. Test this pop-up by clicking run this snippet.
const MySwal = Swal.mixin({
//background: "rgb(10,10,10)",
background: "white",
showCloseButton: true,
backdrop: "rgba(0,0,0,0.7)",
showClass: {
popup: "animate__animated animate__fadeInDown med"
},
hideClass: {
popup: "animate__animated animate__fadeOutUp fast"
},
width: "95vw"
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.js" integrity="sha512-HBD0cOZJYcymSn0H0CnN3VBhQLdiH8imucm16ZQ792TT2n48u6nmX+T7hZTCwmzIrgMt76x4rHhR7KkZqhIGxA==" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10"></script>
<script src="alpha.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
<link rel="shortcut icon" href="favicon.png" id="iconshort">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#sweetalert2/theme-material-ui/material-ui.css">
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap" rel="stylesheet">
</head>
<body>
<button onclick="MySwal.fire('Title','Content')">LAUNCH POP-UP</button>
</body>
const MySwal = Swal.mixin({
//background: "rgb(10,10,10)",
background: "white",
showCloseButton: true,
backdrop: "rgba(0,0,0,0.7)",
showClass: {
popup: "animate__animated animate__fadeInDown med"
},
hideClass: {
popup: "animate__animated animate__fadeOutUp fast"
},
width: "95vw",
willOpen: function() {
open_audio.play();
},
willClose: function() {
confirm_audio.play();
}
});
so here's the code I wrote, as you can see when the trigger hits the red line, the boxes start changing the color to red, but when the trigger passes the red line again, some of the boxes turn the color to red again.
function what() {
const trigger1 = document.querySelector(".trigger1").getBoundingClientRect().y;
const element = document.querySelectorAll(".ele");
if (trigger1 < 100) {
function why() {
for (let i = 0; i < element.length; i++) {
setTimeout(() => {
element[i].classList.add('newColor');
}, i * 500)
}
}
why();
} else {
element.forEach((e) => {
e.classList.remove('newColor');
})
}
}
window.addEventListener("scroll", what);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-size: 62.5%;
}
h1 {
background-color: lightcoral;
text-align: center;
padding: 1rem;
font-size: 2.5rem;
}
section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
ul {
position: fixed;
top: 50%;
left: 20%;
transform: translate(-50%, -50%);
text-align: center;
list-style: none;
}
ul li {
margin: 1rem;
padding: 1rem;
font-size: 2rem;
background-color: rgb(134, 146, 211);
}
.newColor {
color: white;
background-color: red;
}
.line {
position: fixed;
top: 100px;
width: 100%;
height: 1px;
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<section>
<div class="line"></div>
<div>
<h1 class="trigger1">here's the trigger</h1>
<ul>
<li class="ele">ayyyo</li>
<li class="ele">woooo</li>
<li class="ele">yoooo</li>
<li class="ele">loool</li>
</ul>
</div>
</section>
<section>
<div>
<h1 class="trigger2">this is trigger 2</h1>
</div>
</section>
</body>
</html>
what I want to do is, when the trigger hits the red line, the boxes change the color to red.
After that when the trigger goes back (or leave the red line to bottom), the boxes change the color to the original color and never changes the color to red unless the trigger hits the red line again.
I might need to use clearTimeout thing but not sure where or how to put.
that'd be great if you let me know how I can solve this... thanks
You can use global variable as timeout handler for clearTimeout.
Try following code.
var timeOutHandler = [];
function what() {
const trigger1 = document.querySelector(".trigger1").getBoundingClientRect().y;
const element = document.querySelectorAll(".ele");
if(trigger1 < 100){
for(let i = 0; i < element.length; i++){
if ( typeof timeOutHandler[i] === 'undefined'){
timeOutHandler[i] = setTimeout(()=> {
element[i].classList.add('newColor');
}, i *500);
}
}
} else {
for (i = 0; i < timeOutHandler.length; i++ ){
clearTimeout( timeOutHandler[i] );
timeOutHandler[i] = undefined;
}
element.forEach((e) => {
e.classList.remove('newColor');
});
}
}
window.addEventListener("scroll", what);
Explanation:
According to your code, repeated setTimeout will executed everytime when user scroll.
To prevent repeated setTimeout, you can assign handler to every element, and execute setTimeout only when handler is undefined.
So, there will be only 1 setTimeout for every element when trigger hit red line for the first time.
And when trigger went back to below of red line, stop and remove all timeouts and assign undefined to all handlers.
I'm working on my personal project and i need to change div style which is my cursor (from width and height 10px to width and height 100px) when i'm hovering it on h1 element inside another div.
I tried
h1:hover ~ .cursor{
width: 100px;
height: 100px;
}
and
h1:hover + .cursor{
width: 100px;
height: 100px;
}
but it didn't work in this case. Do you know how to do it?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<header class="mainHeader">
<h1>WELCOME</h1>
</header>
<div class="cursor"></div>
<script src="js/cursor.js"></script>
</body>
</html>
CSS:
#import url('https://fonts.googleapis.com/css?family=Montserrat:400,700,800&display=swap');
*, html{
margin: 0;
font-family: 'Montserrat', sans-serif;
cursor: none;
}
.mainHeader{
background: rgb(255, 255, 255);
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
h1{
color: rgb(255, 255, 255), 255);
font-weight: 800;
}
.cursor{
width: 10px;
height: 10px;
background: rgb(255, 255, 255);
position: absolute;
border-radius: 50%;
box-sizing: border-box;
pointer-events: none;
transition: 200ms ease-out;
mix-blend-mode: difference;
}
h1:hover ~ .cursor{
width: 100px;
height: 100px;
}
here is my js code responsible for following div with the mouse:
const cursor = document.querySelector('.cursor');
document.addEventListener('mousemove', e => {
cursor.setAttribute("style", "top: " + (e.pageY - 5) + "px; left: " + (e.pageX - 5) + "px;");
});
The cursor works because when I changed the code so that the "~" works, everything was ok.
I'm open to solutions in javascript.
Codepen version: https://codepen.io/Flayy/pen/vYBwzgE
You need to add a class (or an id) on the H1 tag to be able to select it in the script, e.g.:
<h1 class="bigCursor">WELCOME</h1>
And in the script:
const bigCursor = document.querySelector('.bigCursor')
So change your 'mousemove' event function to a more flexible way to edit style:
document.addEventListener('mousemove', e => {
cursor.style.top = e.pageY + 'px';
cursor.style.left = e.pageX + 'px';
});
And add this to functions to respectively increase and decrease size of the cursor
bigCursor.addEventListener('mouseenter', e => {
cursor.style.width = "100px";
cursor.style.height = "100px";
});
bigCursor.addEventListener('mouseleave', e => {
cursor.style.width = "10px";
cursor.style.height = "10px";
});
At this point you may have realised that the cursor is not centered on the mouse, so add this line inside the .cursor CSS tag to fix this:
transform: translate(-50%, -50%);
Codepen version
Hey in CSS you can only change the CSS properties of another element on hover if the element is a child or adjacent to the hovered element.
I moved your cursor div to be adjacent to the H1 element and added a + to your h1 hover css property:
CodePen: https://codepen.io/sudoxx2/pen/dybEqqY
just write two functions one on mouseenter and second on mouseleave
document.getElementById(hoverElement).addEventListener("mouseenter",function(){
document.getElementById(cursorElement).style.width = "100px"
document.getElementById(cursorElement).style.height = "100px"})
and add another on mouseleave
document.getElementById(hoverElement).addEventListener("mouseleave",function(){
document.getElementById(cursorElement).style.width = "10px"
document.getElementById(cursorElement).style.height = "10px"})
After discovering the difficulties of styling inputs of type range, I though it best to simply create one using css and hiding the original. I'm trying to Make a volume slider, but I don't think I fully understand how to connect onmousemove and onmousedown. I tried following the following post
How to connect onmousemove with onmousedown?
but my volumeSlider function - the javascript code that is commented out - still isn't working;
What I want is that onmousemove is only activated on onmousedown and not by simply moving the mouse.
const volume_div = document.querySelector('.volume');
const volumeBtn_div = document.querySelector('.volume-button');
function volumeClick(event) {
let x = event.offsetX;
volume_div.style.width = (Math.floor(x) + 10) + 'px';
}
/*
volumeBtn_div.onmousedown = function() {
volumeBtn_div.onmousemove = volumeSlide;
};
function volumeSlide(event) {
let x = event.offsetX;
volume_div.style.width = Math.floor(x) + 'px';
}*/
body {
background-color: #2a2a2a;
}
.volume-range {
margin-top: 80px;
height: 5px;
width: 250px;
background: #555;
border-radius: 15px;
}
.volume-range>.volume {
height: 5px;
width: 50px;
background: #2ecc71;
border: none;
border-radius: 10px;
outline: none;
position: relative;
}
.volume-range>.volume>.volume-button {
width: 20px;
height: 20px;
border-radius: 20px;
background: #FFF;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Volume</title <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<body>
<div class="volume-range" onclick="volumeClick(event)">
<div class="volume">
<div class="volume-button"></div>
</div>
</div>
If I understand your question correctly, I think you could just set a flag onmousedown and reset it onmouseup. Something like:
let mouseIsDown = false;
volumeBtn_div.onmousedown = function() { mouseIsDown = true };
volumeBtn_div.onmouseup = function() { mouseIsDown = false };
volumeBtn_div.onmousemove = volumeSlide;
function volumeSlide(event) {
if(mouseIsDown){
let x = event.offsetX;
volume_div.style.width = Math.floor(x) + 'px';
}
}
...
In response to your comment, this similar example works in Chrome. I changed the EventListener syntax. It should get you on the right track.
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 200px; height: 100px; border: 1px solid black; }
</style>
</head>
<body>
<div id="input"></div>
<p id="output"></p>
<script>
const input = document.getElementById("input");
const output = document.getElementById("output");
let mouseIsDown = false;
input.addEventListener("mouseup", up);
input.addEventListener("mousedown", down);
input.addEventListener("mousemove", slide);
function down(){ mouseIsDown = true; }
function up(){ mouseIsDown = false; }
function slide(e) {
if(mouseIsDown){
var x = e.clientX;
var pos = "pos: " + x;
output.innerHTML = pos;
}
}
</script>
</body>
</html>