I have some code below which shows/hides an li element when I click on an image. The code below works as intended; however, the image I'm using fits the entire screen and currently when the li element is shown it displays on the very top left of the image. I want the li element to display exactly where I'm clicking but having difficulty figuring out how I can do that. Please advice.
GamePage.js
const GamePage = () => {
const [isShown, setIsShown] = useState(false);
const handleClick = () => {
setIsShown((current) => !current);
};
return (
<div className="gamepage" onClick={handleClick}>
{isShown && (
<ul className="menu">
<li className="menu-item">Waldo</li>
</ul>
)}
<GamePageImage />
</div>
);
};
GamePage.css
.gamepage {
position: relative;
}
.menu {
position: absolute;
text-align: center;
list-style-type: none;
margin: 5px;
padding: 0;
border: 1px solid #3e3e3e;
width: 100px;
}
.menu > li {
margin: 0;
color: white;
background-color: #3e3e3e;
}
.menu > li:hover {
cursor: pointer;
background-color: #252525;
}
The onClick fires an event, where you can get the x and y coordinates.
Save that position and use it on your ul element to place it where you want it.
I've added some CSS to ul which will place it exactly where you click.
const GamePage = () => {
const [isShown, setIsShown] = useState(false);
const [position, setPosition] = useState([0,0]) // State to save the position where you clicked
const handleClick = (event) => {
setIsShown(current => !current)
setPosition([event.pageX,event.pageY]) // Save the pos where you clicked
}
return (
<div className="gamepage" onClick={handleClick}>
{isShown && (
<ul className="menu" style={{
position: "absolute",
left: position[0],
top: position[1],
tranform: "translateX(-50%)",
transform: "translateY(-50%)",
}}>
<li className="menu-item">Waldo</li>
</ul>
)}
<GamePageImage />
</div>
);
};
I'm trying to add and remove active class when I click on different panels that triggers a transition, so if I click on different panels it works, as in it triggers the transition and then it ends it when other panel gets clicked, but if I want to click on a panel that was already opened and closed it won't trigger it again on the first click adn that's not good UX.
I'm writing it in React and I am a beginner so maybe I'm not doing something right.
You can see the code below, I hope I gave all the right information.
componentDidMount() {
ReactDom.findDOMNode(this).addEventListener("transitionend", (e) => {
if (
e.propertyName.includes("flex") &&
e.target.classList.contains("open")
) {
e.target.classList.add("open-active");
}
});
ReactDom.findDOMNode(this).addEventListener("click", (e) => {
const elems = document.querySelector(".open-active");
if (elems !== null) {
elems.classList.remove("open-active", "open", "opac");
}
e.target.className = "open-active";
console.log(e);
});
}
render() {
const { index, top, bottom, image, open, onClick } = this.props;
const style = {
backgroundImage: `url(${image})`,
};
const openValue = open ? "open opac" : "";
return (
<div
className={`panel ${openValue}`}
style={style}
onClick={() => {
onClick(index);
}}
>
</div>
And the CSS
.panel > * {
margin: 0;
width: 100%;
transition: transform 0.5s;
flex: 1 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.panel > *:first-child {
transform: translateY(-100%);
}
.panel.open-active > *:first-child {
transform: translateY(0);
}
.panel > *:last-child {
transform: translateY(100%);
}
.panel.open-active > *:last-child {
transform: translateY(0);
}
.panel p:nth-child(2) {
font-size: 4em;
}
.panel.open {
font-size: 16px;
flex: 5;
}
Hi you can follow this example:
import React, {useState} from "react";
import './styles/style.css'
export default function ShowHideExample() {
const [cssClass, setCssClass] = useState('hide');
return (
<div className="App">
<h2>Show or Hide div</h2>
<button onClick={() => {
(cssClass === 'hide')? setCssClass('show') : setCssClass('hide');
}}>Click me to show or hide the div
</button>
<div className={cssClass}>
<h1>This is dynamically shown</h1>
</div>
</div>
);
}
Here is the style.css file
.show{
display: block;
background: dodgerblue;
padding:20px;
}
.hide{
display: none;
}
I have been trying to make the links in my sticky nav bar highlight when on the corresponding section.
I have been able to get it to partially work using JavaScript with all links being highlighted when scrolling over the corresponding sections, however, the section 1 link is highlighted even if I'm on the landing page and have not scrolled at all. How can I make it so that section 1 isn't highlighted until I scroll to the section?
I've tried to use an if statement to set all links to not active if window.scrollY === 0, but this only works for the initial render and doesn't work after I have scrolled down and back.
Update
Adding another if statement at the start of the highlightNav function to check if window.scrollY === 0 has allowed me to remove the .active class from all the links, but ideally I want it to work when window.scrollY < 450 which doesn't seem to work.
My JavaScript is as follows:
const highlightNav = () => {
const links = document.querySelectorAll('.link');
const section = document.querySelectorAll('.section');
//updated if statement
//I tried using window.scrollY < 450 in the if statement below with no success
if (window.scrollY === 0) {
links.forEach((link) => link.classList.remove('active'));
};
if (window.scrollY !== 0) {
const changeLinkState = () => {
let index = section.length;
while(--index && window.scrollY + 450 < section[index].offsetTop) {};
links.forEach((link) => link.classList.remove('active'));
links[index].classList.add('active');
};
changeLinkState();
};
};
highlightNav();
window.addEventListener('scroll', highlightNav);
The HTML follows this structure:
<header>
<div class="nav-bar">
<nav>
About
Pricing
Contact
Sign in
</nav>
</div>
<section>
<!-- Landing Screen -->
</section>
</header>
<article>
<section id="about" class="section">
<!-- section 1 -->
</section>
<section id="price" class="section">
<!-- Section two -->
</section>
<section id="contact" class="section">
<!-- Section Three -->
</section>
</article>
css:
.nav-bar {
position: fixed;
top: 0px;
width: 100%;
height: 8vh;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #297094;
text-align: center;
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.3);
}
nav {
width: 25%;
height: 100%;
display: flex;
justify-content: flex-end;
align-items: center;
}
nav a {
padding: 0 10%;
border-left: 1px solid black;
height: 100%;
display: flex;
align-items: center;
font-size: 1.25rem;
color: white;
transition: background-color 600ms;
text-decoration: none;
white-space: nowrap;
}
nav a:hover {
background-color: #3B80A0;
cursor: pointer;
}
.active {
background-color: #3B80A0;
}
I'm very new to JavaScript so any help is welcome, thanks in advance.
Main issue:
Instead of mixing that 450 math into a while loop, define that amount as a constant with a descriptive name, then use it in your conditional.
A couple other notes:
The while loop in your posted code doesn't do anything, since there's nothing inside the {}
You call links.forEach((link) => link.classList.remove('active')); twice, so make that its own function (I've named it clearAllActive() here).
const highlightNav = () => {
const links = document.querySelectorAll('.link');
const sections = document.querySelectorAll('.section');
const clearAllActive = () => links.forEach(link => link.classList.remove('active'));
const highlightActive = () => {
// your highlighting code here
};
// don't start highlighting until we've scrolled at least this far
const minScrollBeforeHighlighting = 450;
if (window.scrollY < minScrollBeforeHighlighting) {
clearAllActive();
} else {
highlightActive();
};
};
highlightNav();
window.addEventListener('scroll', highlightNav);
I am building a carousel, very minimalist, using CSS snap points. It is important for me to have CSS only options, but I'm fine with enhancing a bit with javascript (no framework).
I am trying to add previous and next buttons to scroll programmatically to the next or previous element. If javascript is disabled, buttons will be hidden and carousel still functionnal.
My issue is about how to trigger the scroll to the next snap point ?
All items have different size, and most solution I found require pixel value (like scrollBy used in the exemple). A scrollBy 40px works for page 2, but not for others since they are too big (size based on viewport).
function goPrecious() {
document.getElementById('container').scrollBy({
top: -40,
behavior: 'smooth'
});
}
function goNext() {
document.getElementById('container').scrollBy({
top: 40,
behavior: 'smooth'
});
}
#container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
border: 2px solid var(--gs0);
border-radius: 8px;
height: 60vh;
}
#container div {
scroll-snap-align: start;
display: flex;
justify-content: center;
align-items: center;
font-size: 4rem;
}
#container div:nth-child(1) {
background: hotpink;
color: white;
height: 50vh;
}
#container div:nth-child(2) {
background: azure;
height: 40vh;
}
#container div:nth-child(3) {
background: blanchedalmond;
height: 60vh;
}
#container div:nth-child(4) {
background: lightcoral;
color: white;
height: 40vh;
}
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<button onClick="goPrecious()">previous</button>
<button onClick="goNext()">next</button>
Nice question! I took this as a challenge.
So, I increased JavaScript for it to work dynamically. Follow my detailed solution (in the end the complete code):
First, add position: relative to the .container, because it need to be reference for scroll and height checkings inside .container.
Then, let's create 3 global auxiliary variables:
1) One to get items scroll positions (top and bottom) as arrays into an array. Example: [[0, 125], [125, 280], [280, 360]] (3 items in this case).
3) One that stores half of .container height (it will be useful later).
2) Another one to store the item index for scroll position
var carouselPositions;
var halfContainer;
var currentItem;
Now, a function called getCarouselPositions that creates the array with items positions (stored in carouselPositions) and calculates the half of .container (stored in halfContainer):
function getCarouselPositions() {
carouselPositions = [];
document.querySelectorAll('#container div').forEach(function(div) {
carouselPositions.push([div.offsetTop, div.offsetTop + div.offsetHeight]); // add to array the positions information
})
halfContainer = document.querySelector('#container').offsetHeight/2;
}
getCarouselPositions(); // call it once
Let's replace the functions on buttons. Now, when you click on them, the same function will be called, but with "next" or "previous" argument:
<button onClick="goCarousel('previous')">previous</button>
<button onClick="goCarousel('next')">next</button>
Here is about the goCarousel function itself:
First, it creates 2 variables that store top scroll position and bottom scroll position of carousel.
Then, there are 2 conditionals to see if the current carousel position is on most top or most bottom.
If it's on top and clicked "next" button, it will go to the second item position. If it's on bottom and clicked "previous" button, it will go the previous one before the last item.
If both conditionals failed, it means the current item is not the first or the last one. So, it checks to see what is the current position, calculating using the half of the container in a loop with the array of positions to see what item is showing. Then, it combines with "previous" or "next" checking to set the correct next position for currentItem variable.
Finally, it goes to the correct position through scrollTo using currentItem new value.
Below, the complete code:
var carouselPositions;
var halfContainer;
var currentItem;
function getCarouselPositions() {
carouselPositions = [];
document.querySelectorAll('#container div').forEach(function(div) {
carouselPositions.push([div.offsetTop, div.offsetTop + div.offsetHeight]); // add to array the positions information
})
halfContainer = document.querySelector('#container').offsetHeight/2;
}
getCarouselPositions(); // call it once
function goCarousel(direction) {
var currentScrollTop = document.querySelector('#container').scrollTop;
var currentScrollBottom = currentScrollTop + document.querySelector('#container').offsetHeight;
if (currentScrollTop === 0 && direction === 'next') {
currentItem = 1;
} else if (currentScrollBottom === document.querySelector('#container').scrollHeight && direction === 'previous') {
console.log('here')
currentItem = carouselPositions.length - 2;
} else {
var currentMiddlePosition = currentScrollTop + halfContainer;
for (var i = 0; i < carouselPositions.length; i++) {
if (currentMiddlePosition > carouselPositions[i][0] && currentMiddlePosition < carouselPositions[i][1]) {
currentItem = i;
if (direction === 'next') {
currentItem++;
} else if (direction === 'previous') {
currentItem--
}
}
}
}
document.getElementById('container').scrollTo({
top: carouselPositions[currentItem][0],
behavior: 'smooth'
});
}
window.addEventListener('resize', getCarouselPositions);
#container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
border: 2px solid var(--gs0);
border-radius: 8px;
height: 60vh;
position: relative;
}
#container div {
scroll-snap-align: start;
display: flex;
justify-content: center;
align-items: center;
font-size: 4rem;
}
#container div:nth-child(1) {
background: hotpink;
color: white;
height: 50vh;
}
#container div:nth-child(2) {
background: azure;
height: 40vh;
}
#container div:nth-child(3) {
background: blanchedalmond;
height: 60vh;
}
#container div:nth-child(4) {
background: lightcoral;
color: white;
height: 40vh;
}
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<button onClick="goCarousel('previous')">previous</button>
<button onClick="goCarousel('next')">next</button>
Another good detail to add is to call getCarouselPositions function again if the window resizes:
window.addEventListener('resize', getCarouselPositions);
That's it.
That was cool to do. I hope it can help somehow.
I've just done something similar recently. The idea is to use IntersectionObserver to keep track of which item is in view currently and then hook up the previous/next buttons to event handler calling Element.scrollIntoView().
Anyway, Safari does not currently support scroll behavior options. So you might want to polyfill it on demand with polyfill.app service.
let activeIndex = 0;
const container = document.querySelector("#container");
const elements = [...document.querySelectorAll("#container div")];
function handleIntersect(entries){
const entry = entries.find(e => e.isIntersecting);
if (entry) {
const index = elements.findIndex(
e => e === entry.target
);
activeIndex = index;
}
}
const observer = new IntersectionObserver(handleIntersect, {
root: container,
rootMargin: "0px",
threshold: 0.75
});
elements.forEach(el => {
observer.observe(el);
});
function goPrevious() {
if(activeIndex > 0) {
elements[activeIndex - 1].scrollIntoView({
behavior: 'smooth'
})
}
}
function goNext() {
if(activeIndex < elements.length - 1) {
elements[activeIndex + 1].scrollIntoView({
behavior: 'smooth'
})
}
}
#container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
border: 2px solid var(--gs0);
border-radius: 8px;
height: 60vh;
}
#container div {
scroll-snap-align: start;
display: flex;
justify-content: center;
align-items: center;
font-size: 4rem;
}
#container div:nth-child(1) {
background: hotpink;
color: white;
height: 50vh;
}
#container div:nth-child(2) {
background: azure;
height: 40vh;
}
#container div:nth-child(3) {
background: blanchedalmond;
height: 60vh;
}
#container div:nth-child(4) {
background: lightcoral;
color: white;
height: 40vh;
}
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<button onClick="goPrevious()">previous</button>
<button onClick="goNext()">next</button>
An easier approach done with react.
export const AppCarousel = props => {
const containerRef = useRef(null);
const carouselRef = useRef(null);
const [state, setState] = useState({
scroller: null,
itemWidth: 0,
isPrevHidden: true,
isNextHidden: false
})
const next = () => {
state.scroller.scrollBy({left: state.itemWidth * 3, top: 0, behavior: 'smooth'});
// Hide if is the last item
setState({...state, isNextHidden: true, isPrevHidden: false});
}
const prev = () => {
state.scroller.scrollBy({left: -state.itemWidth * 3, top: 0, behavior: 'smooth'});
setState({...state, isNextHidden: false, isPrevHidden: true});
// Hide if is the last item
// Show remaining
}
useEffect(() => {
const items = containerRef.current.childNodes;
const scroller = containerRef.current;
const itemWidth = containerRef.current.firstElementChild?.clientWidth;
setState({...state, scroller, itemWidth});
return () => {
}
},[props.items])
return (<div className="app-carousel" ref={carouselRef}>
<div className="carousel-items shop-products products-swiper" ref={containerRef}>
{props.children}
</div>
<div className="app-carousel--navigation">
<button className="btn prev" onClick={e => prev()} hidden={state.isPrevHidden}><</button>
<button className="btn next" onClick={e => next()} hidden={state.isNextHidden}>></button>
</div>
</div>)
}
I was struggling with the too while working with a react project and came up with this solution. Here's a super basic example of the code using react and styled-components.
import React, { useState, useRef } from 'react';
import styled from 'styled-components';
const App = () => {
const ref = useRef();
const [scrollX, setScrollX] = useState(0);
const scrollSideways = (px) => {
ref.current.scrollTo({
top: 0,
left: scrollX + px,
behavior: 'smooth'
});
setScrollX(scrollX + px);
};
return (
<div>
<List ref={ref}>
<ListItem color="red">Card 1</ListItem>
<ListItem color="blue">Card 2</ListItem>
<ListItem color="green">Card 3</ListItem>
<ListItem color="yellow">Card 4</ListItem>
</List>
<button onClick={() => scrollSideways(-600)}> Left </button>
<button onClick={() => scrollSideways(600)}> Right </button>
</div>
);
};
const List = styled.ul`
display: flex;
overflow-x: auto;
padding-inline-start: 40px;
scroll-snap-type: x mandatory;
list-style: none;
padding: 40px;
width: 700px;
`;
const ListItem = styled.li`
display: flex;
flex-shrink: 0;
scroll-snap-align: start;
background: ${(p) => p.color};
width: 600px;
margin-left: 15px;
height: 200px;
`;
I want to show different data or hide component if it doesn't fit on screen.
I made a working example but i don't think it's a right/elegant way to do it.
Maybe someone can show me a better way?
This image of example that i made in codepen.
1. I want to hide first red block if it's doesn't fit in grey.
I don't want to do it on media queries of window-size because my red blocks maybe be different in size from user to user.
Codepen example (resize to hide block): https://codepen.io/bofemptiness/pen/YJRKGj
const styled = styled.default
const Component = React.Component;
const DivHat = styled.div`
position: fixed;
top: 0;
width: 100% ;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
background-color: blue;
`
const DivProfile = styled.div`
display: flex;
height: 100%;
cursor: pointer;
`
const ExpCooDiv = styled.div`
display: flex;
flex-direction: column;
font-size: 1rem;
`
class App extends Component {
constructor(props) {
super(props)
this.state = { showCookies: true, lvlRefLastSize: 0 }
this.statsRef = React.createRef()
this.cocRef = React.createRef()
this.lvlRef = React.createRef()
this.mediaStats = this.mediaStats.bind(this);
}
componentDidMount() {
// Add listner when window resizes
window.addEventListener('resize', this.mediaStats)
// Activate function at least one time on load
this.mediaStats()
}
componentWillUnmount() {
window.removeEventListener('resize', this.mediaStats)
}
// Show/hide first red block if summ of red blocks widths <= width of grey one
mediaStats = () => {
console.log(this.statsRef.current.scrollWidth)
if (this.lvlRef.current.scrollWidth != 0)
this.setState({ lvlRefLastSize: this.lvlRef.current.scrollWidth })
if (this.statsRef.current.scrollWidth <= this.state.lvlRefLastSize + this.cocRef.current.scrollWidth) {
this.setState({ showCookies: false })
} else {
this.setState({ showCookies: true })
}
}
render () {
return(
<DivHat>
<div>Menu</div>
<div id='test' ref={this.statsRef}>
<div ref={this.lvlRef} id='test2'>
{this.state.showCookies &&
<React.Fragment>
<span>DATA that i hide</span>
</React.Fragment>
}
</div>
<div ref={this.cocRef} id='test2'>
ANOTHER DATA
</div>
</div>
<DivProfile >
<div> Profile </div>
</DivProfile>
</DivHat>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))