canvas.getContext is undefined when generating blurHash Angular 11 - html

I am trying to show blur hash on my images in my angular application before they fully load. But I'm getting the canvas context as undefined inside my function. I can't figure out where the problem is occurring.
I am using the blurhash package.
My code is as follows:
#ViewChild('imageCanvas', {static: false}) imageCanvas: ElementRef<HTMLCanvasElement>;
private context: CanvasRenderingContext2D;
ngAfterViewInit() {
this.getLatestClubPosts()
}
getLatestClubPosts() {
let tempPosts = [];
this._postService
.getClubPosts("Club", 0, 15).pipe(takeUntil(this.destroy$))
.subscribe((res: ApiResponse<any>) => {
res.data.map((singleClubPost: Post, idx, self) => {
this._postService
.getPostCommentsAndReactions(singleClubPost.id, 0, 4)
.subscribe((reactionsAndComments: ApiResponse<any>) => {
singleClubPost.reactionCount =
reactionsAndComments.data.count.reactionCount;
singleClubPost.commentsCount =
reactionsAndComments.data.count.commentsCount;
singleClubPost.reactions = reactionsAndComments.data.reaction;
if(singleClubPost.captureFileURL !== '') {
singleClubPost.media.forEach((image, i) => {
const validRes = isBlurhashValid(image.blurHash);
if(validRes.result == true) {
this.cf.detectChanges();
const blurhashPixels = decode(image.blurHash, 200, 200);
this.context = this.imageCanvas?.nativeElement?.getContext("2d"); //where the error occurs
const imageData = this.context?.createImageData(200, 200);
if (!imageData) {
this.toast.error('Could not prepare Blurhash canvas', 'Error');
}
else {
imageData?.data.set(blurhashPixels)
}
}
})
}
tempPosts.push(singleClubPost);
if (idx == self.length - 1) {
tempPosts.sort(function compare(a, b) {
const dateA = new Date(a.postedDate) as any;
const dateB = new Date(b.postedDate) as any;
return dateB - dateA;
});
this.recentClubPosts = tempPosts;
console.log(this.recentClubPosts)
this.cf.detectChanges();
}
});
});
});
}
My HTML is as follows:
<ng-container *ngFor="let media of post.media; let i = index;">
<img *ngIf="media.blurHash === undefined" [src]="media.captureFileURL"
style="
flex-grow: 1;
flex-direction: row;
flex-wrap: wrap;
display: block;
padding: 0.2em;
box-sizing: border-box;
width: 50%;
height: 400px;
object-fit: cover;
border-radius: 12px;
" />
<canvas #imageCanvas *ngIf="media.blurHash !== undefined" style="
flex-grow: 1;
flex-direction: row;
flex-wrap: wrap;
display: block;
padding: 0.2em;
box-sizing: border-box;
width: 50%;
height: 400px;
object-fit: cover;
border-radius: 12px;">
</canvas>
</ng-container>
Even when I am calling this function inside AfterViewInit it still gives the same error: this.context is undefined. I am really stuck and any help is greatly appreciated. Thanks!

Related

React make a full-page Carousel

I am trying to make an animation that scrolls from left to right the child elements of a div, I have looked around but none of the other questions with answers seem to work, so far this is what I have accomplished:
Home.css:
#keyframes scroll {
20% {
transform: translateX(-100vw);
}
40% {
transform: translateX(-200vw);
}
60% {
transform: translateX(-300vw);
}
80% {
transform: translateX(-400vw);
}
100% {
transform: translateX(0vw);
}
}
.section {
display: flex;
flex-direction: row;
font-family: Arial, sans-serif;
font-weight: bold;
transition: 1s;
width: 100vw;
height: 100vh;
animation-name: scroll;
animation-duration: 1s;
}
.child1 {
background-color: #c0392b;
flex: none;
width: 100vw;
height: 100vh;
}
.child2 {
background-color: #e67e22;
flex: none;
width: 100vw;
height: 100vh;
}
.child3 {
background-color: #27ae60;
flex: none;
width: 100vw;
height: 100vh;
}
.child4 {
background-color: #2980b9;
flex: none;
width: 100vw;
height: 100vh;
}
.child5 {
background-color: #8e44ad;
flex: none;
width: 100vw;
height: 100vh;
}
Home.jsx:
import { forwardRef, useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import './Home.css';
const Child1 = forwardRef((props, ref) => {
return <div className="child1">
<h1>Child1</h1>
</div>;
});
const Child2 = forwardRef((props, ref) => {
return <div className="child2">
<h1>Child2</h1>
</div>;
});
const Child3 = forwardRef((props, ref) => {
return <div className="child3">
<h1>Child3</h1>
</div>;
});
const Child4 = forwardRef((props, ref) => {
return <div className="child4">
<h1>Child4</h1>
</div>;
});
const Child5 = forwardRef((props, ref) => {
return <div className="child5">
<h1>Child5</h1>
</div>;
});
function Home() {
let section = useRef();
let [currentSection, setCurrentSection] = useState(0);
useEffect(() => {
window.addEventListener("keypress", (event) => {
if(event.key === "d") {
// scroll right (play animation forwards by one step)
} else if(event.key === "a") {
// scroll left (play animation backwards by one step)
}
});
});
return <div ref={section} className="section">
<Child1></Child1>
<Child2></Child2>
<Child3></Child3>
<Child4></Child4>
<Child5></Child5>
</div>
}
export default Home;
The problem is that the animation plays all at the beginning and I cannot figure out a way to play it only when the keyboard event is triggered, if the event.key is an "a" then the elements should scroll to the left otherwise if the event.key is a "d" then the elements should scroll to the right.
Here is the link to the CodeSandbox.
As I understood you want to make parent scrollable only with pressing keys "a" and "d". I think I have found a solution which would work for you.
My solution:
Removing keyframes and separating it into 5 different classes. So here is CSS file:
.section1 {
transform: translateX(0);
}
.section2 {
transform: translateX(-100vw);
}
.section3 {
transform: translateX(-200vw);
}
.section4 {
transform: translateX(-300vw);
}
.section5 {
transform: translateX(-400vw);
}
.section {
display: flex;
flex-direction: row;
font-family: Arial, sans-serif;
font-weight: bold;
transition: 1s;
width: 100vw;
height: 100vh;
animation-name: scroll;
animation-duration: 1s;
}
.child1 {
background-color: #c0392b;
flex: none;
width: 100vw;
height: 100vh;
}
.child2 {
background-color: #e67e22;
flex: none;
width: 100vw;
height: 100vh;
}
.child3 {
background-color: #27ae60;
flex: none;
width: 100vw;
height: 100vh;
}
.child4 {
background-color: #2980b9;
flex: none;
width: 100vw;
height: 100vh;
}
.child5 {
background-color: #8e44ad;
flex: none;
width: 100vw;
height: 100vh;
}
Now I added some JS behaviour to appropriately 'scroll' left or right. I divided moving left or right into functions, and adding numberOfSections as constant. Here is JS file:
import { forwardRef, useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import "./Home.css";
const Child1 = forwardRef((props, ref) => {
return (
<div className="child1">
<h1>Child1</h1>
</div>
);
});
const Child2 = forwardRef((props, ref) => {
return (
<div className="child2">
<h1>Child2</h1>
</div>
);
});
const Child3 = forwardRef((props, ref) => {
return (
<div className="child3">
<h1>Child3</h1>
</div>
);
});
const Child4 = forwardRef((props, ref) => {
return (
<div className="child4">
<h1>Child4</h1>
</div>
);
});
const Child5 = forwardRef((props, ref) => {
return (
<div className="child5">
<h1>Child5</h1>
</div>
);
});
const numberOfSections = 5;
function Home() {
const section = useRef();
const [currentSection, setCurrentSection] = useState(1);
const moveLeft = () => {
section.current.classList.remove(`section${currentSection}`);
section.current.classList.add(`section${currentSection - 1}`);
setCurrentSection((prevSection) => prevSection - 1);
};
const moveRight = () => {
section.current.classList.remove(`section${currentSection}`);
section.current.classList.add(`section${currentSection + 1}`);
setCurrentSection((prevSection) => prevSection + 1);
};
const changeSection = (event) => {
if (event.key === "d") {
if (currentSection < numberOfSections) {
moveRight();
}
} else if (event.key === "a") {
if (currentSection > 1) {
moveLeft();
}
}
};
useEffect(() => {
window.addEventListener("keypress", changeSection);
return () => window.removeEventListener("keypress", changeSection);
}, [currentSection]);
return (
<div ref={section} className="section">
<Child1></Child1>
<Child2></Child2>
<Child3></Child3>
<Child4></Child4>
<Child5></Child5>
</div>
);
}
export default Home;
I have tested it and it works.
By the way, my suggestions is to wrap some of these functions into useCallback if you plan to expand Home component. And I suggest to use some of npm packages compatible with React for directly manipulating CSS within JS, such as styled-components, which in this case would make it a lot easier to create Carousel, becouse now in order to create more Child components, you need to make new CSS classes.
But this above fixes the given problem. I hope I helped you :)
this solution is tightly cuppled to your example but from my perspective, you could make it more generic.
I didn't use CSS animation instead I used the scrollTo method to achieve scroll behavior.
codesandbox link
Home.jsx
import { forwardRef, useEffect, useRef, useState } from "react";
import "./styles.css";
// I not using forwardRef and ref at all
const Child1 = forwardRef((props, ref) => {
return (
<div className="child1">
<h1>Child1</h1>
</div>
);
});
const Child2 = forwardRef((props, ref) => {
return (
<div className="child2">
<h1>Child2</h1>
</div>
);
});
const Child3 = forwardRef((props, ref) => {
return (
<div className="child3">
<h1>Child3</h1>
</div>
);
});
const Child4 = forwardRef((props, ref) => {
return (
<div className="child4">
<h1>Child4</h1>
</div>
);
});
const Child5 = forwardRef((props, ref) => {
return (
<div className="child5">
<h1>Child5</h1>
</div>
);
});
function App() {
let section = useRef();
let [currentSection, setCurrentSection] = useState(0);
useEffect(() => {
const handler = (event) => {
if (event.key === "d") {
if (currentSection === 4) return;
setCurrentSection((prev) => prev + 1);
} else if (event.key === "a") {
if (currentSection === 0) return;
setCurrentSection((prev) => prev - 1);
}
};
window.addEventListener("keypress", handler);
// you should clean up you EventListener
return () => {
window.removeEventListener("keypress", handler);
};
}, [currentSection]);
useEffect(() => {
window.scrollTo({
behavior: "smooth",
left: window.innerWidth * currentSection,
top: 0,
});
}, [currentSection]);
return (
<div ref={section} className="section">
<Child1></Child1>
<Child2></Child2>
<Child3></Child3>
<Child4></Child4>
<Child5></Child5>
</div>
);
}
export default App;
Home.css
.section {
display: flex;
flex-direction: row;
font-family: Arial, sans-serif;
font-weight: bold;
transition: 1s;
width: 100vw;
height: 100vh;
}
.child1 {
background-color: #c0392b;
flex: none;
width: 100vw;
height: 100vh;
}
.child2 {
background-color: #e67e22;
flex: none;
width: 100vw;
height: 100vh;
}
.child3 {
background-color: #27ae60;
flex: none;
width: 100vw;
height: 100vh;
}
.child4 {
background-color: #2980b9;
flex: none;
width: 100vw;
height: 100vh;
}
.child5 {
background-color: #8e44ad;
flex: none;
width: 100vw;
height: 100vh;
}

Fixed table layout and a single row w/ pseudo element leading to shrunk table width

I've a table in my project with a pseudo element to show which row is active. Having changed the table layout to fixed (which is needed), I started getting this strange layout where the active row would expand to take up the entire table, but the other rows would not:
I've replicated a similar problem here (codepen, snippet below) - it's not exactly the same (the active row doesn't extend), but I'm fairly sure any answer to this would help me fix my problem.
If you comment out the top active::after style you'll see the table return to its correct size.
Thanks
// TABLE DATA
const headers = ['Id', 'Name', 'Age', 'Location'];
const datasetOne = [
['1','John Jones','27','Swindon'],
['2', 'Pete Best', '23', 'Glasgow'],
['3', 'Jules West', '22', 'Exeter'],
['4', 'Kate Ford', '33', 'Fife'],
];
const datasetTwo = [
['5','Ruth Thompson','27','Birmingham'],
['6', 'Dominic Lawson', '23', 'Greater London'],
['7', 'Really really long name', '22', 'Manchester'],
['8', 'Nicholas Johnson', '33', 'Liverpool'],
];
const tableWrapper = document.querySelector('.table-wrapper');
const btn = document.querySelector('.btn');
let dataset = 1;
// Listeners
window.addEventListener('load', () => {
const data = formatData(datasetOne);
tableWrapper.insertAdjacentHTML('afterbegin', createTable(headers, data));
});
btn.addEventListener('click', () => {
// Remove the table
const table = document.querySelector('.table')
table.parentElement.removeChild(table);
// Create and insert a new table
let data;
if(dataset === 1) {
data = formatData(datasetTwo);
dataset = 2;
}
else if(dataset === 2) {
data = formatData(datasetOne);
dataset = 1;
}
tableWrapper.insertAdjacentHTML('afterbegin', createTable(headers, data));
})
// Functions to create the table
function formatData(data) {
const rows = data.map(row => {
return createHTMLRow(row);
});
return rows;
}
function createHTMLRow([id, name, age, location]) {
const row = [
`<td class="td--id">${id}</td>`,
`<td class="td--name">${name}</td>`,
`<td class="td--age">${age}</td>`,
`<td class="td--location">${location}</td>`
];
return row;
}
function createTable (theads, rows) {
const markup = `
<table class="table">
<thead class="thead">
<tr>
${theads.map((thead) => {
return `<th class="th--${thead.toLowerCase()}">${thead}</th>`;
}).join('')}
</tr>
</thead>
<tbody class="tbody">
${
rows.map((row, index) => {
return `<tr class="row ${index===0? 'active':''}">${row.map(col => {
return `${col}`
}).join('')}</tr>`
}).join('')
}
</tbody>
</table>
`;
return markup;
};
.active::after {
position: absolute;
content: '';
left: 0;
top: 0;
width: 2px;
height: 100%;
background-color: green;
}
* {
margin: 0;
box-sizing: border-box;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
background-color: firebrick;
}
.table-wrapper {
display: flex;
background-color: white;
width: 30rem;
overflow: hidden;
}
.table {
display: table;
table-layout:fixed;
border-collapse: collapse;
overflow: hidden;
width: 100%;
}
th {
text-align: start;
padding: 1rem;
background-color: lemonchiffon;
border: 1px solid lightgrey;
}
.th--age, .th--id {
width: 4rem;
}
td {
padding: .5rem 1rem;
border: 1px solid lightgrey;
white-space: nowrap;
}
.td--name {
overflow: hidden;
text-overflow: ellipsis;
}
.row {
position: relative;
height: 2rem;
}
.btn {
padding: 1rem .8rem;
width: 7rem;
background-color: white;
margin-top: 2rem;
}
<div class="container">
<div class="table-wrapper"></div>
<div class="btn">Change Data</div>
</div>
**Edit:
#zer00ne's answer of using min-width did fix the row issue, but it's unfortunately caused other problems with text-overflow:ellipsis and column widths
If you click on the codepen, item 7 currently works and overflows as intended, and all the columns remain a fixed width, even if they aren't given a width in the css (extra space seems to be distributed evenly between them).
Adding min-width to the table, while fixing the row issue, unfortunately breaks this behaviour
Was hoping someone had any ideas on how I can keep the columns fixed (as the codepen currently behaves), while being able to add the pseudo element (or some way of achieving the same effect)
Thanks!
**Edit 2:
I guess I could just manually divide up the total table width between each of the columns, but that seems a bit fragile
Update
I believe that the pseudo-element .active::after may still be the culprit. It feels like a code smell, a quick google lead me to nowhere official, but from what little I found coincides with what I was saying before, It's basically an extra cell in a single row. Because it's a pseudo-element, it's not part of the DOM so if you put one in a place where other elements cannot exist (like being a child of a <tr>), you may get unexpected results.
So here's what I did, it looks good. Try to break it and let me know if it actually does:
I changed where .active is generated -- it is now assigned to the first <td> of the first <tr> within the <tbody>. <td> can hold just about anything and it looks exactly like it did as it was on the <tr>.
Figure I
function formatData(data) { // ↙️ Add the index parameter
const rows = data.map((row, idx) => {
return createHTMLRow(idx, row);
}); // ↖️ Pass it as the 1st parameter
//...
Figure II
// ↙️ Pass the index reference as 1st parameter
function createHTMLRow(i, [id, name, age, location]) {
const row = [
`<td class="td--id ${i===0? 'active':''}">${id}</td>`,
//... ↖️ Here's the index reference interpolated
Original Solution
Still good for most cases. The update is for an edge case.
The table is at width: 100% which doesn't guarantee 100% with fixed tables that have undefined <th> widths. Change table width:
table {min-width: 100%}
// TABLE DATA
const headers = ['Id', 'Name', 'Age', 'Location'];
const datasetOne = [
['1', 'John Jones', '27', 'Swindon'],
['2', 'Pete Best', '23', 'Glasgow'],
['3', 'Jules West', '22', 'Exeter'],
['4', 'Kate Ford', '33', 'Fife'],
];
const datasetTwo = [
['5', 'Ruth Thompson', '27', 'Birmingham'],
['6', 'Dominic Lawson', '23', 'Greater London'],
['7', 'XXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXx XXXXXX', '22', 'Manchester'],
['8', 'Nicholas Johnson', '33', 'Liverpool'],
];
const tableWrapper = document.querySelector('.table-wrapper');
const btn = document.querySelector('.btn');
let dataset = 1;
// Listeners
window.addEventListener('load', () => {
const data = formatData(datasetOne);
tableWrapper.insertAdjacentHTML('afterbegin', createTable(headers, data));
});
btn.addEventListener('click', () => {
// Remove the table
const table = document.querySelector('.table')
table.parentElement.removeChild(table);
// Create and insert a new table
let data;
if (dataset === 1) {
data = formatData(datasetTwo);
dataset = 2;
} else if (dataset === 2) {
data = formatData(datasetOne);
dataset = 1;
}
tableWrapper.insertAdjacentHTML('afterbegin', createTable(headers, data));
});
// Functions to create the table
function formatData(data) {
const rows = data.map((row, idx) => {
return createHTMLRow(idx, row);
});
return rows;
}
function createHTMLRow(i, [id, name, age, location]) {
const row = [
`<td class="td--id ${i===0? 'active':''}">${id}</td>`,
`<td class="td--name">${name}</td>`,
`<td class="td--age">${age}</td>`,
`<td class="td--location">${location}</td>`
];
return row;
}
function createTable(theads, rows) {
const markup = `
<table class="table">
<thead class="thead">
<tr>
${theads.map((thead) => {
return `<th class="th--${thead.toLowerCase()}">${thead}</th>`;
}).join('')}
</tr>
</thead>
<tbody class="tbody">
${
rows.map((row, index) => {
return `<tr class="row">${row.map(col => {
return `${col}`
}).join('')}</tr>`
}).join('')
}
</tbody>
</table>
`;
return markup;
};
.active::after {
position: absolute;
content: '';
left: 0;
top: 0;
width: 2px;
height: 100%;
background-color: green;
}
* {
margin: 0;
box-sizing: border-box;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background-color: firebrick;
}
.table-wrapper {
display: flex;
background-color: white;
width: 30rem;
overflow: hidden;
}
.table {
display: table;
table-layout: fixed;
border-collapse: collapse;
overflow: hidden;
width: 100%;
}
th {
text-align: start;
padding: 1rem;
background-color: lemonchiffon;
border: 1px solid lightgrey;
}
.th--age,
.th--id {
width: 4rem;
}
td {
padding: .5rem 1rem;
border: 1px solid lightgrey;
white-space: nowrap;
}
.td--name {
overflow: hidden;
text-overflow: ellipsis;
}
.row {
position: relative;
height: 2rem;
}
.btn {
padding: 1rem .8rem;
width: 7rem;
background-color: white;
margin-top: 2rem;
}
<div class="container">
<div class="table-wrapper"></div>
<div class="btn">Change Data</div>
</div>

Stripe CarElement not visible in React js

Below is my code for a checkout page where i have the CardElement and Iam processing the payment through stripe. It was working fine 2 days back but it has disappeared from the UI all of a sudden. enter image description hereIs there any changes Stripe has made in its CardElement package or Am I missing anything in my code?
import React, { useEffect, useState } from "react";
import Header from "./Header";
import styled from "styled-components";
import { useSelector, useDispatch } from "react-redux";
import { selectUserName, selectUserEmail } from "../features/userSlice";
import {
selectCart,
selectCartTotalAmount,
removeAllItems,
} from "../features/cartSlice";
import Orders from "./Orders";
import { CardElement, useStripe, useElements } from "#stripe/react-stripe-js";
import { useHistory } from "react-router-dom";
import axios from "../axios";
import { db } from "../firebase";
function Checkout() {
const userName = useSelector(selectUserName);
const userEmail = useSelector(selectUserEmail);
const cart = useSelector(selectCart);
const cartTotalAmount = useSelector(selectCartTotalAmount);
const history = useHistory();
const [succeeded, setSucceeded] = useState(false);
const [required, setRequired] = useState("");
const [msg, setMsg] = useState("");
const [processing, setProcessing] = useState("");
const [address, setAddress] = useState("");
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState(true);
const stripe = useStripe();
const elements = useElements();
const dispatch = useDispatch();
console.log("email", userEmail);
const handlechange = (e) => {
setAddress(e.target.value);
// else {
// setRequired(false);
// }
//localStorage.setItem("address", address);
};
// const goToPreview = () => {
// return <Preview address={address} />;
// };
const validateAddress = () => {};
useEffect(() => {
const getClientSecret = async () => {
const response = await axios({
method: "post",
url: `/payments/create?total=${cartTotalAmount * 100}`,
});
setClientSecret(response.data.clientSecret);
};
getClientSecret();
}, [cart]);
console.log("secret is", clientSecret);
const handleSubmit = async (e) => {
e.preventDefault();
if (address === "") {
setRequired(true);
setMsg("*Address is required!");
} else {
setProcessing(true);
console.log(processing);
const payload = await stripe
.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement),
},
})
.then(({ paymentIntent }) => {
db.collection("users")
.doc(userEmail)
.collection("orders")
.doc(paymentIntent.id)
.set({
cart: cart,
amount: paymentIntent.amount,
created: paymentIntent.created,
address: address,
});
setSucceeded(true);
setError(null);
setProcessing(false);
dispatch(removeAllItems());
history.replace("/orders");
});
}
};
const handleCardChange = (e) => {
setDisabled(e.empty);
setError(e.error ? e.error.message : "");
};
return (
<div>
<Header />
<Container>
<Name>
<p>Name : {userName}</p>
</Name>
<Email>
<p>Email : {userEmail}</p>
</Email>
<Address>
<p>Address : </p>
<input type="text" onChange={handlechange} />
</Address>
<small>{msg}</small>
<Order>
<p>Order : </p>
</Order>
{cart.map((item) => (
<OrderCard>
<img src={item.image} />
<p>{item.title}</p>
<small>x</small>
<p>{item.cartQuantity}</p>
</OrderCard>
))}
<Payment>
Payment method :
<form>
<CardElement onChange={handleCardChange} />
</form>
</Payment>
<Total>Total : ${cartTotalAmount}</Total>
<button
onClick={handleSubmit}
disabled={processing || disabled || succeeded}
>
{processing ? "Processing" : "Place your order"}
</button>
{error && <div>{error}</div>}
</Container>
</div>
);
}
export default Checkout;
const Container = styled.div`
padding-top: 70px;
width: 100%;
height: 100vh;
background: linear-gradient(to bottom right, #feedf6, #fcf0e2);
margin: auto;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
button {
margin-top: 30px;
margin-bottom: 30px;
margin-left: 40rem;
align-items: center;
}
small {
margin-top: 5px;
margin-left: 20rem;
}
`;
const Name = styled.div`
margin-left: 35rem;
/* margin-right: 10px;
margin-left: 10px; */
`;
const Email = styled.div`
margin-left: 35rem;
/* margin-right: 10px;
margin-left: 10px; */
`;
const Address = styled.div`
display: flex;
justify-content: center;
margin-left: 35rem;
h3 {
margin-right: 10px;
margin-left: 5rem;
}
input {
margin-top: 20px;
margin-left: 5px;
width: 300px;
height: 100px;
}
`;
const Order = styled.div`
margin-left: 35rem;
`;
const OrderCard = styled.div`
display: flex;
justify-content: center;
margin-left: 35rem;
img {
width: 40px;
height: 40px;
}
small {
margin-top: 17px;
margin-left: 10px;
}
p {
margin-left: 20px;
}
`;
const Total = styled.div`
margin-left: 35rem;
`;
const Payment = styled.div`
margin-left: 35rem;
margin-bottom: 20px;
form {
margin-top: 10px;
flex: 0.8;
width: 600px;
height: 40px;
}
`;

Animation should start when I hover over the div

I would like to implement the following: The animation should only start when I hover the mouse over the div. After I hovered over the div, the end number should remain visible and not change to the start value.
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animation</title>
<style>
.counter{
color: white;
font-size: 100px;
height: 300px;
width: 400px;
background-color: black;
display: flex;
align-items:center;
justify-content: center;
}
.animate{
position:absolute;
opacity:0;
transition:0s 180s;
}
.animate:hover {
opacity:1;
transition:0s;
}
</style>
</head>
<body>
<div id="animate" style="background-color: orange; width: 300px; height: 200px;" class="counter" data-target="500">0</div>
<script>
const counters = document.querySelectorAll('.counter');
for(let n of counters) {
const updateCount = () => {
const target = + n.getAttribute('data-target');
const count = + n.innerText;
const speed = 5000; // change animation speed here
const inc = target / speed;
if(count < target) {
n.innerText = Math.ceil(count + inc);
setTimeout(updateCount, 1);
} else {
n.innerText = target;
}
}
updateCount();
}
</script>
</body>
</html>
Add onmousover to id="animate"
<div id="animate" style="background-color: orange; width: 300px; height: 200px;" class="counter" data-target="500" onmouseover="animationEffect();">0</div>
Wrap the whole script in a method:
function animationEffect(){
const counters = document.querySelectorAll('.counter');
for(let n of counters) {
const updateCount = () => {
const target = + n.getAttribute('data-target');
const count = + n.innerText;
const speed = 5000; // change animation speed here
const inc = target / speed;
if(count < target) {
n.innerText = Math.ceil(count + inc);
setTimeout(updateCount, 1);
} else {
n.innerText = target;
}
}
updateCount();
}
}
Should solve the problem
EDIT:
The old answer was refering to the question before being edited. For the current case the following could be done:
const updateCount = n => {
const target = +n.getAttribute('data-target')
const count = +n.innerText
const speed = 5000 // change animation speed here
const inc = target / speed
if (count < target) {
n.innerText = Math.ceil(count + inc)
requestAnimationFrame(() => updateCount(n))
} else {
n.innerText = target
}
}
const counters = document.querySelectorAll('.counter')
for (let n of counters) {
n.addEventListener('mouseenter', () => updateCount(n), {
once: true
})
}
.counter {
color: white;
font-size: 100px;
height: 300px;
width: 400px;
background-color: black;
display: flex;
align-items: center;
justify-content: center;
}
.animate {
position: absolute;
opacity: 0;
transition: 0s 180s;
}
.animate:hover {
opacity: 1;
transition: 0s;
}
<div id="animate" style="background-color: orange; width: 300px; height: 200px" class="counter" data-target="500">
0
</div>
Old answer:
You would need to add a mouseenter event to the parent element. Note that the {once: true} option will make the event only fire once.
const parent = document.getElementById('parent')
parent.addEventListener('mouseenter', mouseEnterHandler, {once: true})
Then define the mouseEnterHandler callback as follows:
function mouseEnterHandler() {
for (let n of counters) {
n.style.display = 'block'
updateCount(n)
}
/* If you only have one counter then just get it by its Id:
const div = document.getElementById('hover-content')
div.style.display = 'block'
updateCount(div)
*/
}
n.style.display = 'block' will make the counter visible so no need for the css rule #parent:hover #hover-content { display:block; }.
Here is a working example:
const updateCount = n => {
const target = +n.getAttribute('data-target')
const count = +n.innerText
const speed = 5000 // change animation speed here
const inc = target / speed
if (count < target) {
n.innerText = Math.ceil(count + inc)
requestAnimationFrame(() => updateCount(n))
} else {
n.innerText = target
}
}
const counters = document.querySelectorAll('.counter')
const parent = document.getElementById('parent')
parent.addEventListener('mouseenter', mouseEnterHandler, {
once: true
})
function mouseEnterHandler() {
for (let n of counters) {
n.style.display = 'block'
updateCount(n)
}
}
.counter {
color: white;
font-size: 100px;
height: 140px;
width: 400px;
background-color: black;
display: flex;
align-items: center;
justify-content: center;
}
#hover-content {
display: none;
}
<div id="parent">
Some content
<div hidden id="hover-content" class="counter" data-target="232">0</div>
</div>

socket.io - show the users in the correct div

I'm pretty new to express and socket.io and I'm trying to achieve a little website:
What is it supposed to do:
You can connect to the website and enter a username
You have to select a column where you want to write (it's stored in var column)
Once on the page with the four column, you can see your username at the top of your column and start doing things there.
The other users see you in the correct column.
What it is not doing:
Actually the three points above are working quite well, my issue is with the last point :
The other users see you in the correct column.
My code is somehow not displaying every user in the correct column, in fact, it's displaying them in the same column as you are
Here is the code
$(document).ready(function () {
var socket = io();
var username = prompt("premier utilisateur : ", "nom");
var column = prompt("colonne ", "1,2,3 ou 4");
var gdhb = "";
socket.emit("new user entered his name");
socket.emit("nomUser", username);
if (column === "1") { column = ".one"; gdhb = ".dir1" }
if (column === "2") { column = ".two"; gdhb = ".dir2" }
if (column === "3") { column = ".three"; gdhb = ".dir3" }
if (column === "4") { column = ".four"; gdhb = ".dir4" }
socket.emit("user chose a column");
socket.emit("columnUser", column);
$(column).append($("<p class='username'>" + username + "</p>"))
$(document.body).click(function (b) {
var verbes = [
"appuie",
"bouscule",
"pousse"
];
var adverbes = [
"puis",
"ensuite",
"pour finir",
"alors"
];
var verbe = verbes[Math.floor(Math.random() * verbes.length)];
var adverbe = adverbes[Math.floor(Math.random() * adverbes.length)];
var verbadv = verbe + " " + adverbe;
console.log(verbadv);
socket.emit("verbadverbe");
socket.emit("verbadv", verbadv);
var div = $("<div />", {
"class": "document"
})
.css({
"left": b.pageX + 'px',
"top": b.pageY + 'px'
})
.append($("<p>" + verbadv + "</p>"))
.appendTo(column);
});
$(document.body).contextmenu(function (rc) {
var div = $("<div />", {
"class": "document"
})
.css({
"left": rc.pageX + 'px',
"top": rc.pageY + 'px'
})
.append($("<p>recule</p>"))
.appendTo(column);
});
var direction = "";
var oldx = 0;
var oldy = 0;
mousemovemethod = function (e) {
if (e.pageX > oldx && e.pageY == oldy) {
direction = "gauche";
}
else if (e.pageX == oldx && e.pageY > oldy) {
direction = "bas";
}
else if (e.pageX == oldx && e.pageY < oldy) {
direction = "haut";
}
else if (e.pageX < oldx && e.pageY == oldy) {
direction = "droite";
}
$(gdhb).append($("<p class='direction' id='direction'>" + direction + "</p>"))
$(".direction").prev().remove();
oldx = e.pageX;
oldy = e.pageY;
}
document.addEventListener('mousemove', mousemovemethod);
socket.on("columnUser", function (column) {
socket.on("nomUser", function (username) {
$(column).append($("<p class='username'>" + username + "</p>"));
socket.on("verbadv", function (verbadv) {
var div = $("<div />", {
"class": "document"
})
.append($("<p>" + verbadv + "</p>"))
.appendTo(column);
});
});
});
});
and the index.js :
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('Nouvel utilisateur')
socket.on("nomUser", (username) => {
console.log(username);
io.emit("nomUser", username);
});
socket.on("verbadv", (verbadv) => {
console.log(verbadv);
io.emit("verbadv", verbadv);
});
socket.on("columnUser", (column) => {
console.log(column);
io.emit("columnUser", column);
});
});
server.listen(3000, () => {
console.log('listen on 3000');
})
Also if it's needed to understand better, here is the css
body {
font-family: sans-serif;
font-size: 1.3rem;
margin: 0;
background-color: DarkSlateGray;
}
.wrapper {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 0px;
grid-auto-rows: minmax(100vh, auto);
height: 100vh;
}
.one,
.two,
.three,
.four {
-ms-overflow-style: none; /* Internet Explorer 10+ */
scrollbar-width: none; /* Firefox */
position: relative;
overflow: scroll;
height: 100%;
background-color: tan;
}
.one {
grid-column: 1 / 2;
}
.two {
grid-column: 2 / 3;
}
.three {
grid-column: 3 / 4;
}
.four {
grid-column: 4 / 4;
}
.one::-webkit-scrollbar,
.two::-webkit-scrollbar,
.three::-webkit-scrollbar,
.four::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
.note {
text-align: center;
width: 100px;
height: 30px;
}
.note p{
filter: drop-shadow(0 0 0.75rem black);
}
.document{
text-align: center;
}
.document p{
padding: 0;
margin: 0;
}
.username{
text-align: center;
padding: 0;
margin: 0;
}
.direction{
position: fixed;
bottom : 0;
width: 25vw;
text-align: center;
}
Thanks a lot for the precious help.
i've solved your problem with sockets. See at my solution.
client.js
function columnIndexIsValid(index, columnsQuantity) {
return index >= 0 && index <= columnsQuantity;
}
function fullNameIsValid(fullName) {
return typeof fullName === 'string' && fullName.length > 2;
}
function reloadPage() {
window.location.reload();
}
function rand(min, max) {
return Math.floor(min + Math.random() * (max - 1 - min));
}
function getRandomColour(colours = []) {
const colour = colours[rand(0, colours.length)];
return `#${colour}`;
}
function getUserHtml(user) {
return `<div class="column__users-list__item" data-item-id="${user.id}">${user.fullName}</div>`;
}
function getDrawnUsersNodes() {
return $('.column__item');
}
function canIRenderUsers(usersQuantity) {
const $renderedUsersQuantity = getDrawnUsersNodes().length;
return $renderedUsersQuantity < usersQuantity;
}
function renderUserHtmlToNode($node, html) {
$node.html($node.html() + html);
}
function getColumnUsersList(columnNode) {
const $column = $(columnNode);
return $column.find('.column__users-list');
}
function removeDrawnUserById(userId) {
$(`[data-item-id=${userId}]`).remove();
}
class DrawnUsers {
constructor() {
this.users = new Map();
}
getUserById(id) {
return this.users.get(id);
}
add(id, state) {
this.users.set(id, state);
}
removeById(id) {
this.users.delete(id);
}
exists(id) {
return this.users.has(id);
}
}
class Storage {
static setItem(key, value) {
localStorage.setItem(key, value);
}
static getItem(key) {
return localStorage.getItem(key) || null;
}
}
function generateUserId() {
return `user-${rand(rand(0, 10000), rand(20000, 50000))}`;
}
class UserState {
constructor() {
this.state = {};
}
get() {
return {
data: this.state,
};
}
set fullName(fullName) {
this.state.fullName = fullName;
}
get fullName() {
return this.state.fullName;
}
set id(id) {
this.state.id = id;
}
get id() {
return this.state.id;
}
set columnIndex(columnIndex) {
this.state.columnIndex = columnIndex - 1;
}
get columnIndex() {
return this.state.columnIndex;
}
}
$(document).ready(function () {
const drawnUsers = new DrawnUsers();
const colours = ['F2994A', 'F2C94C', '6FCF97', '2F80ED', '56CCF2', 'DFA2F5'];
const $columns = $('.column');
const $container = $('.container');
const userState = new UserState();
$columns.each(function () {
const $self = $(this);
$self.css({ 'background-color': getRandomColour(colours) });
});
userState.fullName = prompt('Type your fullName');
userState.columnIndex = +prompt('Type your column number');
if (
!fullNameIsValid(userState.fullName) ||
!columnIndexIsValid(userState.columnIndex, $columns.length)
) {
return reloadPage();
}
$container.addClass('active');
const socket = io('ws://localhost:3000');
socket.on('connect', () => {
const generatedUserId = generateUserId();
userState.id = Storage.getItem('userId') || generatedUserId;
Storage.setItem('userId', userState.id);
socket.emit('connected', userState.get());
socket.emit('addUser', userState.get());
socket.on('updateCurrentUsers', ({ data }) => {
const { users } = data;
if (!users || !canIRenderUsers(users.length)) {
return;
}
users.forEach((user) => {
const $column = $columns[user.columnIndex];
if ($column) {
if (!drawnUsers.exists(user.id)) {
drawnUsers.add(user.id);
renderUserHtmlToNode(
getColumnUsersList($column),
getUserHtml(user)
);
}
}
});
});
socket.on('newUser', ({ data }) => {
console.log('[debug] newUser: ', data);
const $column = $columns[data.columnIndex];
if (!$column) {
return;
}
if (drawnUsers.exists(data.id)) {
drawnUsers.removeById(data.id);
removeDrawnUserById(data.id);
} else {
drawnUsers.add(data.id);
renderUserHtmlToNode(getColumnUsersList($column), getUserHtml(data));
}
});
socket.on('disconnect', () => {
socket.open();
});
});
});
server.js
const path = require('path');
const http = require('http');
const express = require('express');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('[debug] Client was connected successfully to server');
socket.on('connected', (user) => {
console.log('connected user data', user.data);
socket.data = user.data;
const users = Array.from(io.sockets.sockets.values()).map(
({ data }) => data
);
console.log('users', users);
socket.emit('updateCurrentUsers', {
data: {
users,
},
});
});
socket.on('addUser', ({ data }) => {
socket.data.columnIndex = data.columnIndex;
socket.broadcast.emit('newUser', {
data,
});
const users = Array.from(io.sockets.sockets.values()).map(
({ data }) => data
);
socket.broadcast.emit('updateCurrentUsers', {
data: {
users,
},
});
});
});
server.listen(3000, () => {
console.log('listen on 3000');
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./index.css">
<title>Users Columns</title>
</head>
<body>
<div class="container">
<div class="column">
<span class="column__index">#1</span>
<div class="column__users-list"></div>
</div>
<div class="column">
<span class="column__index">#2</span>
<div class="column__users-list"></div>
</div>
<div class="column">
<span class="column__index">#3</span>
<div class="column__users-list"></div>
</div>
<div class="column">
<span class="column__index">#4</span>
<div class="column__users-list"></div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.1/socket.io.js"
integrity="sha512-vGcPDqyonHb0c11UofnOKdSAt5zYRpKI4ow+v6hat4i96b7nHSn8PQyk0sT5L9RECyksp+SztCPP6bqeeGaRKg=="
crossorigin="anonymous"></script>
<script src="./client.js"></script>
</body>
</html>
index.css
html, body {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
}
.container {
display: none;
}
.container.active {
display: flex;
flex-direction: row;
height: 100vh;
}
.container .column {
width: calc(100% / 4);
text-align: center;
padding: 20px 0;
}
.container .column .column__users-list {
display: flex;
flex-direction: column;
}
.container .column .column__index {
color: #FFF;
font-size: 36px;
letter-spacing: 8px;
}
hey) Let's look on that case more attentive, you have created a variable what contains a column index. right? This variable does store inside var variable. That is global variable for your script. I think you need to store each user column info inside each socket. If you don't know, each socket contains some info inside itself like id and other what can be used in your project if you'd like. But for this case you need to do so:
Ask new user what column he would like to choose.
Write to his socket data/info his column index.
When you do broadcast (It's when you send an object of data to each socket in room all each socket at all) just take this column index and draw this user in correct position. But make sure what your var column has a correct value. I can advice you to use const/let in javascript :)