HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<div id="app"></div>
html,
body,
#app {
height: 100%;
}
*,
*::after,
*::before {
box-sizing: border-box;
}
.container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background: linear-gradient(to left, #3182d5, #4e54c8);
h3 {
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
color: #ffffff;
font-size: 6vw;
@media (min-width: 768px) {
font-size: 5vw;
}
@media (min-width: 992px) {
font-size: 3vw;
}
}
.custom-style {
background-color: lighten(brown, 5%);
color: #ffffff;
}
.custom-menu-identifier {
color: #ffffff;
}
}
/*tooltip component styles*/
.tooltip {
cursor: pointer;
user-select: none;
&.is-disabled {
cursor: initial;
}
}
.tooltip-message {
content: attr(data-tool-tip);
position: absolute;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.6875rem;
max-width: 250px;
z-index: 500;
&.on-top {
transform: translateX(-50%);
background-color: var(--background-color);
&.is-indicator {
&::after {
content: '';
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 8px solid var(--background-color);
position: absolute;
bottom: -12px;
right: 50%;
transform: translate(50%, -50%);
}
}
}
&.on-right {
margin-left: 11px;
transform: translateY(-50%);
background-color: var(--background-color);
&.is-indicator {
&::after {
content: '';
border-top: 5px solid transparent;
border-right: 8px solid var(--background-color);
border-bottom: 5px solid transparent;
position: absolute;
top: 50%;
left: -8px;
transform: translateY(-50%);
}
}
}
&.on-bottom {
transform: translateX(-50%);
background-color: var(--background-color);
&.is-indicator {
&::after {
content: '';
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 8px solid var(--background-color);
position: absolute;
top: -8px;
right: 50%;
transform: translate(50%, 0%);
}
}
}
&.on-left {
transform: translateY(-50%);
background-color: var(--background-color);
&.is-indicator {
&::after {
content: '';
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
border-left: 8px solid var(--background-color);
position: absolute;
top: 50%;
right: -7px;
transform: translateY(-50%);
}
}
}
}
/*floating button component styles*/
.toggle-nav {
position: fixed;
z-index: 10;
width: 40px;
height: 40px;
display: flex;
justify-content: flex-end;
align-items: flex-end;
transition: all 0.2s ease;
button {
border-radius: 50%;
border: none;
outline: none;
cursor: pointer;
min-width: 40px;
min-height: 40px;
padding: 13px;
position: absolute;
opacity: 0.9;
&.main-button {
z-index: 20;
}
&.sub-button {
opacity: 0;
}
}
}
.menu-identifier {
position: fixed;
display: inline-flex;
align-items: center;
font-size: 20px;
}
//react
import React, {
useState,
useEffect,
useRef,
Fragment,
useMemo,
useCallback,
} from 'https://esm.sh/react@18.2.0';
//react dom
import { createRoot } from 'https://esm.sh/react-dom@18.2.0/client';
import ReactDOM from 'https://esm.sh/react-dom@18.2.0';
/****** helpers ******/
function createWrapperAndAppendToBody(wrapper, wrapperElementId) {
const wrapperElement = document.createElement(wrapper);
wrapperElement.setAttribute('id', wrapperElementId);
document.body.appendChild(wrapperElement);
return wrapperElement;
}
// get {top, left} of the required element
function getElementOffset(el) {
let _x = 0,
_y = 0;
while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
const regex = /(auto|scroll)/;
const style = (node, prop) => getComputedStyle(node, null).getPropertyValue(prop);
const scroll = (node) =>
regex.test(style(node, 'overflow') + style(node, 'overflow-y') + style(node, 'overflow-x'));
// get the first scrollable parent
const getScrollParent = (node) =>
!node || node === document.body
? document.body
: scroll(node)
? node
: getScrollParent(node.parentNode);
/****** custom hooks ******/
const useClickAway = (ref, onOutsideClickCallback) => {
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
onOutsideClickCallback(e);
}
};
useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
};
const useTouchScreenDetect = () => {
const isSSR = typeof window === 'undefined',
[isTouchScreen, setIsTouchScreen] = useState(false);
useEffect(() => {
if (!isSSR) {
setIsTouchScreen(
'ontouchstart' in document.documentElement ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0
);
}
}, [isTouchScreen, isSSR]);
return isTouchScreen;
};
/****** components ******/
const ConditionalWrapper = ({ initialWrapper, condition, wrapper, children }) =>
condition ? wrapper(children) : initialWrapper(children);
const ClickAwayWrapper = ({ children, onClickAwayCallback, className }) => {
const wrapperRef = useRef(null);
useClickAway(wrapperRef, onClickAwayCallback);
return (
<span className={className} ref={wrapperRef}>
{children}
</span>
);
};
const Portal = ({ children, wrapperElement, wrapperElementId }) => {
const [wrapper, setWrapper] = useState(null);
useEffect(() => {
let element = document.getElementById(wrapperElementId);
// if element is not found with wrapperElementId or wrapperElementId is not provided,
// create and append to body
if (!element) {
element = createWrapperAndAppendToBody(wrapperElement, wrapperElementId);
}
setWrapper(element);
}, [wrapperElementId, wrapperElement]);
// wrapper state will be null on the first render.
if (wrapper === null) return null;
return ReactDOM.createPortal(children, wrapper);
};
// Tooltip component
const Tooltip = ({
tooltipContent,
position = 'top',
color,
backgroundColor,
disabled,
isParentFixed,
customPosition,
isDisplayTooltipIndicator = true,
trigger = 'hover',
className = '',
children,
}) => {
const isHasTouch = useTouchScreenDetect(),
[show, setShow] = useState(false),
[styles, setStyles] = useState({}),
tooltipWrapperRef = useRef(null),
tooltipMessage = useRef(null),
newPosition = useRef(position),
space = 15,
[childrenWidth, setChildrenWidth] = useState(undefined),
[childrenHeight, setChildrenHeight] = useState(undefined),
[isTooltipVisible, setIsTooltipVisible] = useState(false),
[wrapperParentUpdated, setWrapperParentUpdated] = useState({
top: 0,
left: 0,
}),
availableTooltipPositions = useMemo(
() => ({
top: 'top',
right: 'right',
bottom: 'bottom',
left: 'left',
}),
[]
),
isHoverTrigger = useMemo(() => trigger === 'hover', [trigger]),
isClickTrigger = useMemo(() => trigger === 'click', [trigger]);
//set children width and height
useEffect(() => {
if (show && childrenWidth === undefined && childrenHeight === undefined) {
setChildrenHeight(tooltipMessage.current?.offsetHeight);
setChildrenWidth(tooltipMessage.current?.offsetWidth);
}
}, [show, childrenWidth, childrenHeight]);
//update tooltip visibility
useEffect(() => {
if (show && !isTooltipVisible && childrenWidth !== undefined && childrenHeight !== undefined) {
setIsTooltipVisible(true);
}
}, [show, isTooltipVisible, childrenWidth, childrenHeight]);
const showTooltip = () => {
if (!show) {
setShow(true);
setStyles(getStylesList());
}
};
const hideTooltip = () => {
if (show) {
setShow(false);
}
};
const getStylesList = useCallback(() => {
if (tooltipWrapperRef.current) {
const wrapperRect = tooltipWrapperRef.current.getBoundingClientRect(),
wrapperRef = tooltipWrapperRef.current,
scrollableParent = getScrollParent(wrapperRef),
style = {
left: 0,
top: 0,
},
centeredHorizontalPosition = Math.max(space, wrapperRect.left + wrapperRect.width / 2),
centeredVerticalPosition =
getElementOffset(tooltipWrapperRef.current).top + wrapperRect.height / 2;
let pos = position;
//if position is top and no room for tooltip => change position to bottom
if (
position === availableTooltipPositions.top &&
wrapperRect.top < (childrenHeight || 0) + space
) {
pos = availableTooltipPositions.bottom;
}
//if position is right and no room for tooltip => change position to left
else if (
position === availableTooltipPositions.right &&
wrapperRect.right + ((childrenWidth || 0) + space * 1.5) > window.innerWidth
) {
pos = availableTooltipPositions.left;
}
//if position is bottom and no room for tooltip => change position to top
else if (
position === availableTooltipPositions.bottom &&
wrapperRect.bottom + (childrenHeight || 0) + space > window.innerHeight
) {
pos = availableTooltipPositions.top;
}
//if position is left and no room for tooltip => change position to right
else if (
position === availableTooltipPositions.left &&
wrapperRect.left - ((childrenWidth || 0) + space * 1.5) < 0
) {
pos = availableTooltipPositions.right;
}
newPosition.current = pos;
if (pos === availableTooltipPositions.top) {
style.top = Math.max(
space,
getElementOffset(tooltipWrapperRef.current).top - (childrenHeight || 0) - space
);
style.left = centeredHorizontalPosition;
} else if (pos === availableTooltipPositions.right) {
style.top = centeredVerticalPosition;
style.left = Math.max(space, wrapperRect.right + space);
} else if (pos === availableTooltipPositions.bottom) {
style.top =
getElementOffset(tooltipWrapperRef.current).top +
wrapperRect.height +
(isDisplayTooltipIndicator ? space : space / 2);
style.left = centeredHorizontalPosition;
} else if (pos === availableTooltipPositions.left) {
style.top = centeredVerticalPosition;
style.left = Math.max(space, wrapperRect.left - ((childrenWidth || 0) + space));
}
if (!isParentFixed && scrollableParent && wrapperParentUpdated) {
style.top -= scrollableParent.scrollTop;
}
return style;
}
return {
top: 0,
left: 0,
};
}, [
position,
isParentFixed,
childrenWidth,
childrenHeight,
wrapperParentUpdated,
isDisplayTooltipIndicator,
availableTooltipPositions,
]);
useEffect(() => {
//required for the first render and on scroll
if (getStylesList().top !== styles.top || getStylesList().left !== styles.left) {
setStyles(getStylesList());
}
}, [getStylesList, styles.left, styles.top]);
const updateScrollableParentScroll = ({ target: { scrollTop, scrollLeft } }) => {
setWrapperParentUpdated({
top: scrollTop,
left: scrollLeft,
});
};
useEffect(() => {
if (tooltipWrapperRef.current) {
const wrapperRef = tooltipWrapperRef.current,
scrollableParent = getScrollParent(wrapperRef);
window.addEventListener('resize', updateScrollableParentScroll);
scrollableParent.addEventListener('scroll', updateScrollableParentScroll);
return () => {
window.removeEventListener('resize', updateScrollableParentScroll);
scrollableParent.removeEventListener('scroll', updateScrollableParentScroll);
};
}
}, []);
useEffect(() => {
const handleScroll = () => {
if (show && isClickTrigger) {
setShow(false);
}
};
if (tooltipWrapperRef.current) {
const wrapperRef = tooltipWrapperRef.current,
scrollableParent = getScrollParent(wrapperRef),
newScrollableParent = scrollableParent === document.body ? window : scrollableParent;
newScrollableParent.addEventListener('scroll', handleScroll);
window.addEventListener('resize', handleScroll);
return () => {
newScrollableParent.removeEventListener('scroll', handleScroll);
window.removeEventListener('resize', handleScroll);
};
}
}, [show, isClickTrigger]);
return (
<ConditionalWrapper
condition={isClickTrigger}
initialWrapper={(children) => <>{children}</>}
wrapper={(children) => (
<ClickAwayWrapper onClickAwayCallback={hideTooltip}>{children}</ClickAwayWrapper>
)}
>
<span
className={`tooltip ${disabled ? 'is-disabled' : ''}`}
onMouseEnter={
isHoverTrigger ? (disabled ? undefined : isHasTouch ? undefined : showTooltip) : undefined
}
onMouseLeave={
isHoverTrigger ? (disabled ? undefined : isHasTouch ? undefined : hideTooltip) : undefined
}
onTouchStart={
isHoverTrigger ? (disabled ? undefined : isHasTouch ? showTooltip : undefined) : undefined
}
onTouchEnd={
isHoverTrigger ? (disabled ? undefined : isHasTouch ? hideTooltip : undefined) : undefined
}
onClick={
isClickTrigger ? (disabled ? undefined : showTooltip) : disabled ? undefined : hideTooltip
}
ref={tooltipWrapperRef}
>
<Portal wrapperElement="span" wrapperElementId="tooltip">
{show && tooltipContent && (
<span
ref={tooltipMessage}
className={`tooltip-message
${className}
on-${newPosition.current} ${isDisplayTooltipIndicator ? 'is-indicator' : ''}`}
dangerouslySetInnerHTML={{ __html: tooltipContent }}
style={{
color: color ? color : '#ffffff',
'--background-color': backgroundColor ? backgroundColor : 'rgba(97, 97, 97, 0.92)',
...(customPosition ? customPosition : styles),
...(newPosition.current === availableTooltipPositions.left ||
newPosition.current === availableTooltipPositions.top
? { visibility: isTooltipVisible ? 'visible' : 'hidden' }
: {}),
}}
/>
)}
</Portal>
{children}
</span>
</ConditionalWrapper>
);
};
const FloatingButton = ({
location,
buttons,
mainButtonIcon,
menuIdentifier,
isTooltip = true,
}) => {
const { enable = false, icon, label = 'Menu', className = '' } = menuIdentifier ?? {},
[isHover, setIsHover] = useState(false),
[isMenuIdentifier, setIsMenuIdentifier] = useState(true),
[isDisableTooltip, setIsDisableTooltip] = useState(true), // used to disable tooltip during menu animation
isHasTouch = useTouchScreenDetect(),
ref = useRef(null),
radius = 25,
buttonsLength = buttons.length,
navigatorDimensions = radius * buttonsLength * 1.6,
circleRadius = radius * buttonsLength,
availablePositions = useMemo(
() => ({
topLeft: 'top-left',
topRight: 'top-right',
bottomLeft: 'bottom-left',
bottomRight: 'bottom-right',
}),
[]
),
isOnLeft =
location === availablePositions.topLeft || location === availablePositions.bottomLeft,
buttonsRefs = useRef([]);
useEffect(() => {
let timer;
if (enable) {
if (isHover) {
setIsMenuIdentifier(false);
} else {
timer = setTimeout(
() => {
setIsMenuIdentifier(!isHover);
},
(buttons.length * 200) / 2
);
}
}
return () => {
if (enable) {
clearTimeout(timer);
}
};
}, [enable, isHover, buttons.length]);
useEffect(() => {
let timer;
if (isTooltip) {
if (isHover) {
timer = setTimeout(
() => {
setIsDisableTooltip(false);
},
(buttons.length * 200) / 2
);
} else {
setIsDisableTooltip(true);
}
}
return () => {
if (isTooltip) {
clearTimeout(timer);
}
};
}, [isTooltip, isHover, buttons.length]);
const showFloatingBtnMenu = () => {
setIsHover(true);
};
const hideFloatingBtnMenu = () => {
setIsHover(false);
};
const toggleFloatingBtnMenu = () => {
setIsHover((prev) => !prev);
};
const setNavigatorLocation = () => {
switch (location) {
case availablePositions.topLeft:
return {
container: {
top: 10,
right: 'auto',
bottom: 'auto',
left: 10,
},
mainButton: {
top: 0,
right: 'auto',
bottom: 'auto',
left: 0,
},
identifier: {
top: 20,
right: 'auto',
bottom: 'auto',
left: 55,
},
};
case availablePositions.topRight:
return {
container: {
top: 10,
right: 10,
bottom: 'auto',
left: 'auto',
},
mainButton: {
top: 0,
right: 0,
bottom: 'auto',
left: 'auto',
},
identifier: {
top: 20,
right: 55,
bottom: 'auto',
left: 'auto',
},
};
case availablePositions.bottomLeft:
return {
container: {
top: 'auto',
right: 'auto',
bottom: 10,
left: 10,
},
mainButton: {
top: 'auto',
right: 'auto',
bottom: 0,
left: 0,
},
identifier: {
top: 'auto',
right: 'auto',
bottom: 20,
left: 55,
},
};
default:
return {
container: {
top: 'auto',
right: 10,
bottom: 10,
left: 'auto',
},
mainButton: {
top: 'auto',
right: 0,
bottom: 0,
left: 'auto',
},
identifier: {
top: 'auto',
right: 55,
bottom: 20,
left: 'auto',
},
};
}
};
// (x, y) = (r * cos(θ), r * sin(θ))
const setButtonPosition = (index) => {
switch (location) {
case availablePositions.topLeft:
return {
top: Math.round(circleRadius * Math.sin((Math.PI / 2 / (buttonsLength - 1)) * index)),
right: 'auto',
bottom: 'auto',
left: Math.round(circleRadius * Math.cos((Math.PI / 2 / (buttonsLength - 1)) * index)),
};
case availablePositions.topRight:
return {
top: Math.round(circleRadius * Math.sin((Math.PI / 2 / (buttonsLength - 1)) * index)),
right: Math.round(circleRadius * Math.cos((Math.PI / 2 / (buttonsLength - 1)) * index)),
bottom: 'auto',
left: 'auto',
};
case availablePositions.bottomLeft:
return {
top: 'auto',
right: 'auto',
bottom: Math.round(circleRadius * Math.sin((Math.PI / 2 / (buttonsLength - 1)) * index)),
left: Math.round(circleRadius * Math.cos((Math.PI / 2 / (buttonsLength - 1)) * index)),
};
default:
return {
top: 'auto',
right: Math.round(circleRadius * Math.cos((Math.PI / 2 / (buttonsLength - 1)) * index)),
bottom: Math.round(circleRadius * Math.sin((Math.PI / 2 / (buttonsLength - 1)) * index)),
left: 'auto',
};
}
};
const mouseEnterHandler = () => {
showFloatingBtnMenu();
};
const mouseLeaveHandler = () => {
hideFloatingBtnMenu();
};
const clickHandler = (handler) => {
hideFloatingBtnMenu();
handler();
};
const { container, mainButton, identifier } = setNavigatorLocation();
const setTooltipPosition = (index) => {
const currentTop = setButtonPosition(index).top,
currentRight = setButtonPosition(index).right,
currentBottom = setButtonPosition(index).bottom,
currentLeft = setButtonPosition(index).left;
switch (location) {
case availablePositions.topLeft:
return {
top:
currentTop === 'auto'
? 'auto'
: currentTop +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetHeight + (index > 4 ? 14 : 0)
: 0),
right:
currentRight === 'auto'
? 'auto'
: currentRight -
(buttonsRefs.current ? buttonsRefs.current[index]?.offsetWidth / 1.7 : 0),
bottom:
currentBottom === 'auto'
? 'auto'
: currentBottom -
(buttonsRefs.current ? buttonsRefs.current[index]?.offsetHeight : 0),
left:
currentLeft === 'auto'
? 'auto'
: currentLeft +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetWidth - (index > 4 ? 5 : 0)
: 0),
};
case availablePositions.topRight:
return {
top:
currentTop === 'auto'
? 'auto'
: currentTop +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetHeight + (index > 4 ? 14 : 0)
: 0),
right:
currentRight === 'auto'
? 'auto'
: currentRight +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetWidth + (index > 4 ? 6 : 13)
: 0),
bottom:
currentBottom === 'auto'
? 'auto'
: currentBottom -
(buttonsRefs.current ? buttonsRefs.current[index]?.offsetHeight : 0),
left:
currentLeft === 'auto'
? 'auto'
: currentLeft + (buttonsRefs.current ? buttonsRefs.current[index]?.offsetWidth : 0),
};
case availablePositions.bottomLeft:
return {
top:
currentTop === 'auto'
? 'auto'
: currentTop - (buttonsRefs.current ? buttonsRefs.current[index]?.offsetHeight : 0),
right:
currentRight === 'auto'
? 'auto'
: currentRight - (buttonsRefs.current ? buttonsRefs.current[index]?.offsetWidth : 0),
bottom:
currentBottom === 'auto'
? 'auto'
: currentBottom +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetHeight -
(buttons.length > 5 && index === 0 ? 9 : 0)
: 0),
left:
currentLeft === 'auto'
? 'auto'
: currentLeft +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetWidth /
(buttons.length > 5 && index === 0 ? 1.1 : 1.7)
: 0),
};
case availablePositions.bottomRight:
return {
top:
currentTop === 'auto'
? 'auto'
: currentTop - (buttonsRefs.current ? buttonsRefs.current[index]?.offsetHeight : 0),
right:
currentRight === 'auto'
? 'auto'
: currentRight +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetWidth /
(buttons.length > 5 && index === 0 ? 0.9 : 1.1)
: 0),
bottom:
currentBottom === 'auto'
? 'auto'
: currentBottom +
(buttonsRefs.current
? buttonsRefs.current[index]?.offsetHeight -
(buttons.length > 5 && index === 0 ? 5 : 0)
: 0),
left:
currentLeft === 'auto'
? 'auto'
: currentLeft + (buttonsRefs.current ? buttonsRefs.current[index]?.offsetWidth : 0),
};
}
return {
top: 0,
right: 0,
bottom: 0,
left: 0,
};
};
return (
<ConditionalWrapper
condition={isHasTouch}
initialWrapper={(children) => <>{children}</>}
wrapper={(children) => (
<ClickAwayWrapper onClickAwayCallback={hideFloatingBtnMenu}>{children}</ClickAwayWrapper>
)}
>
{buttonsLength > 1 ? (
<>
<div
ref={ref}
onMouseEnter={!isHasTouch ? mouseEnterHandler : () => {}}
onMouseLeave={!isHasTouch ? mouseLeaveHandler : () => {}}
className="toggle-nav"
style={{
...container,
width: isHover ? navigatorDimensions : 40,
height: isHover ? navigatorDimensions : 40,
}}
>
<button
className="main-button"
style={{ ...mainButton }}
onClick={isHasTouch ? toggleFloatingBtnMenu : () => {}}
aria-label={`Main menu button ${location}`}
>
{mainButtonIcon}
</button>
{buttons.map((el, i) => (
<ConditionalWrapper
key={i}
condition={isTooltip}
initialWrapper={(children) => <>{children}</>}
wrapper={(children) => (
<Tooltip
position={
location === availablePositions.topLeft ||
location === availablePositions.bottomLeft
? 'right'
: 'left'
}
tooltipContent={el.tooltipLabel}
customPosition={setTooltipPosition(i)}
isDisplayTooltipIndicator={false}
disabled={isDisableTooltip}
>
{children}
</Tooltip>
)}
>
<button
className={`sub-button ${el.className ?? ''}`}
ref={(el) => (buttonsRefs.current[i] = el)}
style={{
opacity: isHover ? 0.9 : 0,
top: isHover
? setButtonPosition(i).top
: setButtonPosition(i).top === 'auto'
? 'auto'
: 0,
right: isHover
? setButtonPosition(i).right
: setButtonPosition(i).right === 'auto'
? 'auto'
: 0,
bottom: isHover
? setButtonPosition(i).bottom
: setButtonPosition(i).bottom === 'auto'
? 'auto'
: 0,
left: isHover
? setButtonPosition(i).left
: setButtonPosition(i).left === 'auto'
? 'auto'
: 0,
transition: `all 0.2s 0.${i + 1}s ease`,
}}
onClick={() => clickHandler(el.click)}
>
{el.icon}
</button>
</ConditionalWrapper>
))}
</div>
{enable && isMenuIdentifier && (
<div
className={`menu-identifier ${className}`}
style={{ ...identifier, flexDirection: isOnLeft ? 'row' : 'row-reverse' }}
>
{icon ? icon : <i className={`far fa-hand-point-${isOnLeft ? 'left' : 'right'}`} />}{' '}
<span style={{ paddingLeft: isOnLeft ? 5 : 0, paddingRight: !isOnLeft ? 5 : 0 }}>
{label}
</span>
</div>
)}
</>
) : (
<div
className="toggle-nav"
style={{
...container,
width: 150,
}}
>
Must be more than one button
</div>
)}
</ConditionalWrapper>
);
};
/****** demo ******/
const App = () => {
const buttons = [
{
icon: <i className="fas fa-home" />,
click: () => console.log('clicked'),
tooltipLabel: 'Home',
className: 'custom-style',
},
{
icon: <i className="fas fa-briefcase" />,
click: () => console.log('clicked'),
tooltipLabel: 'Projects',
className: 'custom-style',
},
{
icon: <i className="fas fa-phone" />,
click: () => console.log('clicked'),
tooltipLabel: 'Contact me',
className: 'custom-style',
},
];
return (
<div className="container">
<h3>Hover over the buttons!</h3>
{/*FloatingButton properties:
- location: floating button location. (default => (bottom-right)) (available locations => (top-left, top-right, bottom-left, bottom-right))
- mainButtonIcon: icon of the main button
- isTooltip: boolean to display button tooltip (default: true)
- buttons => array of: {
icon: button icon
click: button click handler
tooltipLabel: tooltip label
}
- menuIdentifier: used to tell the user that this is the menu
menuIdentifier: {
enable: boolean to enable it (default => false)
icon: React node (default => hand icon)
label: identifier label (default => Menu)
className: identifier className (default => '')
}
*/}
<FloatingButton
menuIdentifier={{ enable: true, className: 'custom-menu-identifier' }}
location="top-left"
buttons={buttons}
mainButtonIcon={<i className="fas fa-info" />}
/>
<FloatingButton
location="top-right"
buttons={buttons}
mainButtonIcon={<i className="fas fa-info" />}
/>
<FloatingButton
location="bottom-left"
buttons={buttons}
mainButtonIcon={<i className="fas fa-info" />}
/>
<FloatingButton
location="bottom-right"
buttons={buttons}
mainButtonIcon={<i className="fas fa-info" />}
isTooltip={false}
/>
</div>
);
};
const container = document.getElementById('app'),
root = createRoot(container);
root.render(<App />);
Also see: Tab Triggers