Tag: Smart

Creating a Smart Navbar With Vanilla JavaScript

Sticky, or fixed, navigation is a popular design choice because it gives users persistent access to navigate the site. On the other hand, it takes up space on the page and sometimes covers content is a way that’s less than appealing.

A possible solution? Smart navigation.

Let’s define “smart navigation” as:

  1. Visible at the top of the page
  2. Visible when the user moves up the page (wherever they may have scrolled to)
  3. Hidden when the user moves down the page

Here’s an example of how that might work:

It‘s all the convenience of sticky positioning, with an added fullscreen benefit. This sort of smart navigation is already commonly (think of the URL bar in many mobile browsers), but is sometimes a hassle to implement without a library or plugin. So, in this article, we’ll discuss how to build one using CSS and vanilla JavaScript.

Side note: People have different definitions of what scrolling down a page means (imagine how some trackpad preferences scroll the page up when you move your fingers down). For the purposes of this article, scrolling down refers to moving towards the bottom of the page.

Let’s look at the code

Here’s some example HTML. Our smart navigation will be the <nav> which sits above the <main>:

<nav>   <div class="logo">     Logo   </div>   <div class="links">     <a href="#">Link 1</a>     <a href="#">Link 2</a>     <a href="#">Link 3</a>     <a href="#">Link 4</a>   </div> </nav> <main>   <!--Place the content of your page here--> </main>

It’s important to note that elements are only sticky relative to their parent container. The parent container of <nav> should be the body tag; it shouldn’t be placed within another tag on the page.

The CSS for our smart navigation looks like this:

nav {   position: sticky;   top: 0;   display: flex;   flex-wrap: wrap;   justify-content: space-between;   padding: 1.5rem 2rem;   background-color: #eaeaea; }

Now we need to detect when our user is scrolling the page and the direction of their scrolling. A user is scrolling down if the value of their last scroll position is less than the value of their current scroll position. Breaking the logic down, we’ll need to:

  1. Define a variable to store the previous scroll position
  2. Assign a variable to detect the current scroll position set to the scroll offset of the page

If the current scroll position is greater than the previous scroll position, then the user is scrolling downwards. Let’s call our function isScrollingDown:

let previousScrollPosition = 0;  const isScrollingDown = () => {   let currentScrolledPosition = window.scrollY || window.pageYOffset;   let scrollingDown;    if (currentScrolledPosition > previousScrollPosition) {     scrollingDown = true;   } else {     scrollingDown = false;   }   previousScrollPosition = currentScrolledPosition;   return scrollingDown; };

Here’s a visual representation of how this function works:

With this logic, we’re able to detect when the page is scrolling down so we can use this to toggle our nav styling:

const nav = document.querySelector('nav');  const handleNavScroll = () => {   if (isScrollingDown()) {     nav.classList.add('scroll-down');     nav.classList.remove('scroll-up')   } else {     nav.classList.add('scroll-up');     nav.classList.remove('scroll-down')   } }

If the user is scrolling down, we’ll assign a .scroll-down class that contains our styling method for when the page is moving downward. We can update our <nav> CSS to this:

nav {   /* default styling */   transition: top 500ms ease-in-out; }  nav.scroll-up {   top: 0; }  nav.scroll-down {   top: -100%; }

With this styling, the top property value of <nav> is set to -100% of the page height so it slides out of view. We could also choose to handle our styling with translate or by fading it out — whatever animation works best.


Whenever we’re working with scroll event listeners, performance is something that should immediately come to mind. Right now, we’re calling our function every time the user scrolls the page, but we don’t need to detect each pixel movement.

For this case, we can implement a throttle function instead. A throttle function is a higher order function that acts as a timer for the function passed into it. If we throttle a scroll event with a timer of 250ms, the event will only be called every 250ms while the user scrolls. It’s a great way to limit the number of times we call the function, helping with the performance of the page.

David Corbacho goes deeper into throttle implementations in this article.

A simple throttle implementation in JavaScript looks like this:

// initialize a throttleWait variable var throttleWait;  const throttle = (callback, time) => {   // if the variable is true, don't run the function   if (throttleWait) return;    // set the wait variable to true to pause the function   throttleWait = true;    // use setTimeout to run the function within the specified time   setTimeout(() => {     callback();      // set throttleWait to false once the timer is up to restart the throttle function     throttleWait = false;   }, time); }

Then we can include our handleNavScroll function inside a throttle:

window.addEventListener("scroll", () => {   throttle(handleNavScroll, 250) });

With this implementation, the handleNavScroll function is only called once every 250ms.


Whenever implementing a custom feature in JavaScript, we must always take accessibility into concern. One such issue is ensuring that <nav> is visible when it’s in focus. Browsers tend to scroll to the part of the page that currently has focus by default, but there can be certain complications when working with scroll events.

A way to ensure that <nav> is always visible is to update the CSS to account for focus. Now our CSS looks like this:

nav.scroll-up, nav:focus-within {   top: 0; }

Unfortunately, the focus-within selector isn’t fully supported across all browsers. We can include a JavaScript fallback for it:

const handleNavScroll = () => {   if (isScrollingDown() && !nav.contains(document.activeElement))) {     nav.classList.add('scroll-down');     nav.classList.remove('scroll-up')   } else {     nav.classList.add('scroll-up');     nav.classList.remove('scroll-down')   } }

In this updated function, we only apply the scroll-down class if the user is scrolling down the page and the <nav> doesn’t currently have any element with focus in it.

Another aspect of accessibility is the consideration that some users may not want to have any animation on the page. That’s something we can detect and respect with the prefers-reduced-motion CSS media query. We can update this method in JavaScript and prevent our function from running at all if a user prefers reduced motion:

const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");  window.addEventListener("scroll", () => {   if (mediaQuery && !mediaQuery.matches) {     throttle(handleNavScroll, 250)   } });

Wrapping up

So, there we have it: a smart navigation implementation with plain CSS and vanilla JavaScript. Now users have persistent access to navigate the site without losing real estate in a way that blocks content.

Plus, the benefit of a custom implementation like this is that we get a delightful user experience that isn’t over-engineered or sacrifices open performance or accessibility.

The post Creating a Smart Navbar With Vanilla JavaScript appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.


, , , ,

The Smart Ways to Correct Mistakes in Git

The world of software development offers an infinite amount of ways to mess up: deleting the wrong things, coding into dead ends, littering commit messages with typos, are a mere few of the plentitude.
​​Fortunately, however, we have a wonderful safety net under our feet in the form of Git when we’re working with version control. Not that you and I need a safety net, of course, because we never make mistakes, right? Sure, sure. But for the benefit of everyone else, let’s take a tour of some of the “undo” tools in Git that can save us from ourselves.

Fixing the last commit

​​Messing up a commit is all too easy. Classic case in point: making a typo in a commit message. Another? Forgetting to add a change to the staging area. And in many cases, we instantly realize our mistake — right after hitting the Enter key, naturally.
​​Luckily, Git makes it ridiculously easy to fix the very last commit. Let’s say we had just hit Enter on the following command:


git commit -m "Massage full of typohs"

​​And (as if this orthographic mess wasn’t bad enough) let’s say we also forgot to add another changed file to the staging area. We can correct both of our mistakes with the following two commands:

git add forgotten-changes.js ​​git commit --amend -m "A sensible message"

​​The magic ingredient is the --amend​ flag: when using it on a commit, Git will correct the very last commit — with any staged changes and the new message.
​​A short word of warning, though: only use --amend​ on commits that haven’t been pushed to a remote repository, yet. The reason is that Git replaces the original, bad commit with the amended version. Afterwards, it looks as if the original commit never happened. Yeah, that’s good for concealing mistakes, but only if we haven’t already published this mistake on the remote server.

Undoing local changes

​​Everyone’s had days like this: spend all morning hacking away, only to admit to yourself that the last few hours were a waste of time. Gotta start over and undo much (or all) of that work.
​​But this is one of the reasons for using Git in the first place — to be able to try out things without the fear that we might break something.
​​Let’s take stock in an example situation:

git status ​​  modified: about.html ​​  deleted:  imprint.html ​​  modified: index.html

​​Now, let’s assume that this is one of the wasted hacking days described above. We ought to have kept our hands off of about.html and not deleted imprint.html. What we now want is to discard our current changes in these files — while keeping the brilliant work done in index.html. ​​The git checkout​ command can help in this case. Instead, we’ve gotta get more specific with which files to check out, like this:


git checkout HEAD about.html imprint.html

​​This command restores both about.html and imprint.html to their last committed states. Phew, we got away from a black eye!
​​We could take this one step further and discard specific individual lines in a changed file instead of tossing out the entire thing! I’ll admit, it’s rather complicated to make it happen on the command line, but using a desktop Git client like Tower is a great way to go about it:

​​For those really bad days, we might want to bring out the big guns in the form of:

git reset --hard HEAD

​​While we only restored specific files with checkout​, this command resets our whole working copy. In other words, reset​ restores the complete project at its last committed state. ​​Similar to --amend​, there’s something to keep in mind when using checkout​ and reset​: discarding local changes with these commands cannot be undone! They have never been committed to the repository, so it’s only logical that they cannot be restored. Better be sure that you really want to get rid of them because there’s no turning back!

Undoing and reverting an older commit

​​In many cases, we only realize a mistake much later, after it has long been committed to the repository.

​​How can we get rid of that one bad commit? Well, the answer is that we shouldn’t… at least in most cases. Even when “undoing” things, Git normally doesn’t actually delete data. It corrects it by adding new data. Let’s see how this works using our “bad guy” example:

git revert 2b504bee

​​By using git revert​ on that bad commit, we haven’t deleted anything. Quite the contrary:

​​Git automatically created a new commit with changes that reverts the effects of the “bad” commit. So, really, if we started with three commits and were trying to correct the middle one, now we have four total commits, with a new one added that corrects the one we targeted with revert​.

Restoring a previous version of a project

​​A different use case is when we want to restore a previous version of our project. Instead of simply undoing or reverting a specific revision somewhere in our commit history, we might really want to turn back time and return to a specific revision.
​​In the following example scenario, we would declare all the commits that came after “C2” as unwanted. What we want is to return to the state of commit “C2” and forget everything that came after it in the process:

​​The command that’s necessary is already (at least partly) familiar to you based on what we’ve already covered:

git reset --hard 2b504bee

​​This tells git reset​ the SHA-1 hash of the commit we want to return to. Commits C3 and C4 then disappear from the project’s history.
​​If you’re working in a Git client, like Tower, both git revert​ and git reset are available from the contextual menu of a commit item:


​​Deleting commits, restoring deleted branches, dealing with conflicts, etc. etc. etc.

​​Of course, there are many other ways to mess up things in a software project. But luckily, Git also offers many more tools for undoing the mess.
​​Have a look at the “First Aid Kit for Git” project that I and other folks on the Tower team have created if you want to learn more about the scenarios we covered in this post, or about other topics, like how to move commits between branches, delete old commits, restore deleted branches or gracefully deal with merge conflicts. It’s a totally free guide that includes 17 videos and a handy cheat sheet you can download and keep next to your machine.

​​In the meantime, happy undoing!

The post The Smart Ways to Correct Mistakes in Git appeared first on CSS-Tricks.


, , ,

Create Smart WordPress Forms in Less Than 5 Minutes with WPForms

(This is a sponsored post.)

Most online form solutions are either too complex or too expensive.

We believe you shouldn’t have to spend hours creating online forms for your business. That’s why we built WPForms, a drag and drop WordPress form builder that’s both EASY and POWERFUL.

WPForms allows you to create beautiful contact forms, email subscription forms, payment forms, smart survey forms, and basically every other type of form for your website within minutes!

Since launching in 2016, WPForms has taken the market by surprise with it’s pre-built templates and smart workflows. Currently, WPForms is being used on over 1 million WordPress websites.

WPForms also maintains a 4.9 out of 5 star rating average on WordPress.org with over 3,000 five-star ratings.

WPForms Features

Here are the features that makes WPForms the most powerful and user-friendly WordPress form plugin in the market.

  • Drag & Drop Form Builder – create smart forms in minutes without writing any code.
    150+ Pre-Made Form Templates – start with our form templates to save time, and customize them as needed.
    Smart Conditional Logic – customize your forms based on user interaction to collect the most relevant information.
  • Entry Management – See all your leads right inside your WordPress dashboard with Geo-location data, and other powerful features.
  • Instant Form Notifications – Get email notifications when a user submits a form. You can smart routing to send the inquiry to the right person in your team.
  • Spam Protection – Our smart captcha and honeypot automatically prevents all spam submissions. You can also add custom CAPTCHA questions as well.
  • Email Marketing Integrations – Integrate with your email marketing service using our native integration for MailChimp, AWeber, Constant Contact, Drip, and countless others. You can use also use our Zapier integration to connect your forms to over 1000+ other apps.
  • Payment Forms – Create online payments using Stripe or PayPal. Recurring payment support is built-in as well.
  • Surveys & Polls – Easily create smart survey forms and analyze your data with our interactive reports. Our WordPress survey plugin is by far the best solution in the industry.
  • Form Abandonment – Unlock more leads by capturing partial form submissions.
  • Form Permissions – Lock your forms and manage access control with password, logged-in users, and other restrictions.
  • Signature – Allow users to sign your online forms with their mouse or touch screen.
  • Post Submission – Allow users to submit guest blog posts and other content directly to your WordPress site without logging into the dashboard. Great for user-submitted content.
  • User Registration – Create custom user registration and login forms for WordPress with just a few clicks. Also include advanced features like profile field mapping, spam registration protection, etc.
  • All Advanced Fields You Need – From radio button to file uploads to multi-page forms to Likert scale, we have all the fields you need.
  • Easy to Customize – Completely customize your WordPress forms with section dividers, HTML blocks, and custom CSS. WPForms also comes with hooks and filters for developers to extend and create custom functionality.

Smart business owners, designers, and developers love WPForms, and you will too!

Unlike other form solutions that charge a monthly subscription which increases as your business grows, WPForms allows you to create unlimited forms and get unlimited entries for a small yearly fee.

Get Started with WPForms Pro Today

Bonus: CSS Tricks users can get 50% off by using the coupon: SAVE50

Need more social proof? Read WPForms user reviews to see why over 1 million websites choose WPForms to build powerful WordPress forms.

If you’re just starting out and don’t need all the advanced features, then you can try our free WPForms Lite plugin for creating a simple contact form. You can simply download it from your WordPress site by searching for WPForms in the plugin search of your WordPress site.

Direct Link to ArticlePermalink

The post Create Smart WordPress Forms in Less Than 5 Minutes with WPForms appeared first on CSS-Tricks.


, , , , , , ,