Code Snippets
Get class name from element
Get class name from element
A nice little script that will return the first class applied to an element. It's part of our internal slider code, but has lots of uses when other js libraries are involved.
<script>
function getFirstWord(element) {
// Get the class name of the element
let str = element.className;
// Trim any leading or trailing spaces from the string
str = str.trim();
// Find the first space in the string
const spaceIndex = str.indexOf(' ');
if (spaceIndex === -1) {
// If there are no spaces in the string, return the whole string
return str;
}
// If there is a space in the string, return the substring before the space
return str.substring(0, spaceIndex);
}
</script>
Similar Code Snippets
Calculate sizes in CSS
CSS's calc() function allows you to perform calculations to determine CSS property values. It's incredibly useful for responsive design, such as when you need to adjust sizes dynamically. For example, if you want a div to be 100% of the viewport width minus a certain margin, you can use calc():
Move elements at different breakpoints
A useful javascript snippet that lets you move elements to a new location at different breakpoints. Perfect if you can only have 1 instance of an element on the page but it needs to change position.
Custom Text Selection Colour
When users highlight text on your webpage, you have a unique opportunity to enhance the visual feedback with custom colors that match your brand. The ::selection pseudo-element allows you to style the background and text color of the selected text: