How to use CSS Scroll Snap
Strategy

How to use CSS Scroll Snap



Nada Rifki

Nada is a JavaScript developer who likes to play with UI components to create interfaces with great UX. She specialises in Vue.js and loves sharing anything and everything that could help her fellow front-end web developers. Nada also dabbles in digital marketing, dance and Chinese.


2 min read
837

The idea of only needing CSS to customize your scroll instead of playing with JavaScript sounds great, doesn’t it?

Today, I’m going to show you how CSS Scroll Snap helps you do just that.

So what does CSS Scroll Snap do?

I bet you’ve used some libraries to control the scrolling behavior of your website. I have, and I had a terrible time with some of them.

Some of these libraries can drag your page’s performance and user experience way down.

Not to mention that it’s a real pain to deal with all the bugs they sometimes generate as you add more complexity with your new design updates.

That’s why I prefer to use this simple CSS feature that allows me to get a beautiful scroll through my page without having to rely on JavaScript libraries.

These properties also help me save a ton of time.

In simple terms, CSS Scroll Snap makes the scroll snap, locking the viewport at a specific point (that you indicate) with each scroll.

A linear scroll, on the other hand, moves according to the rate of the controller — whether that be a mouse, touch gesture, or arrow keys.

Now, let’s see how CSS Scroll Snap works.

If you want to go straight to a real-life example, head over to the third section where I’ve built the Instagram carousel with a few lines of CSS code.

Let’s get started.

 How CSS Scroll Snap works

CSS Scroll Snap works by applying two primary properties: scroll-snap-type and scroll-snap-align.

Here is what you need to know about each:

  • The first one, scroll-snap-type, is applied to the parent container. It accepts two arguments: the snap direction and the snap behavior:
.container {
 scroll-snap-type: [ x | y | block | inline | both ] [ mandatory | proximity ];
}

About the snap behavior arguments: choosing proximity makes the snap only appear at the nearest point to where the user stopped scrolling.

On the other hand, mandatory makes the snap happen at the specific position you choose when the user is scrolling.

  • The second one, scroll-snap-align, is applied to the container’s children.

This is where you specify the snap point for the x-axis and the y-axis:

.children {
 scroll-snap-align: [ none | start | end | center ]{1,2};
}

Before we continue, it’s important to note that none of this is going to work unless you specify the container’s overflow and give it a fixed height.

Additionally, you should never use mandatory if the content inside one of your child elements is longer than the parent container. If you do, the user won’t be able to see that content.

There are two more properties we need to familiarize ourselves with:

  1. scroll-padding (applied to the parent container) is pretty much like the CSS padding property and acts as the offset. You also have scroll-padding-top, scroll-padding-bottom, scroll-padding-left and scroll-padding-right.
  2. scroll-margin (applied to the container’s children) is also like the CSS margin property and serves as the outset. You also have scroll-margin-top, scroll-margin-bottom, scroll-margin-left and scroll-margin-right.

If you are interested in learning more about all scroll snap properties and future ones, the Mozilla documentation is always a good place to start.

How to use CSS Scroll Snap to create an Instagram-like carousel

To help you get a better grasp on this concept, I made a little Instagram-like carousel on codepen.

See the live demo here:

CSS Scroll Snap – Instagram-like Carousel

No Description

As you can see, it includes seven boxes with different sizes.

What amazes me is that we don’t have anything else to do other than add the CSS lines below to automatically make the scroll snap to each box.

<style>
.container {
    width: 60vw;
    height: 70vh;
    margin: 15vh auto;
    overflow-x: scroll;
    scroll-snap-type: x mandatory;
    color: white;
    background-color: oldlace;
    display: flex;
    align-items: center;
}

.child {
    margin-left: 0.5rem;
    height: 90%;
    scroll-snap-align: start;
    padding: 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.child:nth-child(1n) {
    background-color: darkorchid;
    flex: 0 0 80%;
}

.child:nth-child(2n) {
    background-color: indigo;
    flex: 0 0 60%;
}

.child:nth-child(3n) {
    background-color: navy;
    flex: 0 0 40%;
}

.child:nth-child(4n) {
    background-color: palegreen;
    flex: 0 0 50%;
}

.child:nth-child(5n) {
    background-color: yellow;
    flex: 0 0 80%;
}

.child:nth-child(6n) {
    background-color: orange;
    flex: 0 0 60%;
}

.child:nth-child(7n) {
    background-color: tomato;
    flex: 0 0 80%;
}
</style>

Solving this issue with only JavaScript would have required a lot of extra work.

Is CSS Scroll Snap supported cross-browser?

Okay, now let’s get to the million-dollar question: cross-browser support.

As you can see here, the CSS Scroll Snap functionality is well supported across modern browsers.

The only issue you’ll encounter is with Internet Explorer and Firefox, which require an older version of the specs that you can find here.

Also, I would advise you to add the property -webkit-overflow-scrolling: touch; to your container to support iOS devices.

Conclusion

That’s pretty much it!

It’s so simple, but there were times where this could have saved me hours of code. Try to implement a scroll snap using JavaScript and recalculate the snap point with each child element with different widths, and you’ll see what I mean.

If you have any questions or remarks, please feel free to let me know in the comments or to ping me on Twitter @RifkiNada. I always reply.

Is your frontend hogging your users’ CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web apps — .





Source link

Top 4 Gantt Chart Solutions for React
Strategy

Top 4 Gantt Chart Solutions for React


React has gained considerable popularity among both web enthusiasts and large enterprises that value high performance and reliable web applications. Currently, there’s no shortage of React components of different levels of complexity. Today, we’d like to shed some light on a specific kind of such tools — React Gantt charts. 

To make this article useful for the broadest possible public, we’ll focus on two types of Gantt charts. First of all, we’ll take a look at lightweight charts that provide basic functionality and can fit small companies. After that, we’ll consider those that offer dozens of features and can be a good choice for large companies. Such management tools suit well for complex projects and help to ensure that no detail will escape the attention of a project manager.

1. React Google Charts

React Google Charts is a wrapper that allows you to use a plethora of charts developed by Google. The Gantt Chart is rendered using SVG. The list of available features is pretty basic, but you’ll get everything you need to track the state of a project divided into subtasks. This tool from Google allows displaying task duration along with the start and end dates. Also, you can receive some additional info when you hover over a task. Depending on the chart configuration, this information may include the percentage of completion, duration, resource. Besides, the tooltip helps to define whether a particular task is on a critical path or not. 

Using arrows, you can show dependencies between different tasks. Alternatively, you can use the mode without any dependencies displayed. The grouping feature allows you to group similar tasks together. Critical path is a must-have feature for all modern Gantt charts. Google knows it well and provides you with the possibility to define the tasks that affect the project time the most. 

The style of Google Gantt Chart is adjustable, which allows you to change the appearance of arrows marking dependencies between tasks and tracks. Google Gantt chart provides you with pretty everything that you may need for creating a lightweight, neat and good-looking chart. If you plan to build a web application that uses a lot of different charts and keep it lightweight yet full-functioned, React Google Charts may be a pretty decent choice. 

2. Frappe Gantt React

Frappe Gantt React is a wrapper that allows you to use a Gantt chart from Frappe distributed under the MIT license. It’s a simple and lightweight open-source JavaScript Gantt with such features as drag-and-drop, resizing, dependencies creation, and time scales. You can create tasks and drag them across the timeline or resize to change the duration. By clicking a particular task, you can receive some additional info, such as duration and current progress.

The available view modes include Quarter Day, Half Day, Day, Week, and Month. Event listeners allow defining how your app will react to the user’s actions. Using custom HTML in popups, you can change the format of the information appearing in tooltips. At the moment, the list of features looks pretty humble. But still, if you do not expect much from a Gantt chart, this minimalist tool will work just fine for you. 

3. DHTMLX Gantt 

After the Gantt charts that provide basic functionality, let’s take a look at something that can satisfy the requirements of the most demanding users. DHTMLX Gantt is a full-featured Gantt chart for cross-browser and cross-platform applications. It’s a fully customizable chart, in which flexible API enables the configuration of each element. 

You can customize everything from taskbars to grid structure. Using the zooming feature, you can focus on a particular part of a project. You can switch between month, days, and hours. Baselines will be pretty helpful to ensure that you meet your deadlines. You can use them to mark the initial plan for your project and compare it with its current state. The auto-scheduling feature can free you from the need to make all the changes manually and apply the required changes to the schedule automatically. This feature allows updating the start date of the dependent task if the end date of the task depends on changes.

Resource allocation enables you to implement advanced management capabilities. Users can allocate resources to tasks and track the workload with the help of resource usage diagrams, histograms, and resource calendars:

The Critical Path method, which was mentioned earlier, allows significantly simplifying the work on projects. This method enables defining the sequence of tasks that determine the overall duration of the project. If you’re not happy with the amount of information provided by the Gantt chart, you can add some custom content. For example, an S-curve can show the project progress. Besides the possibility of using this Gantt chart in your React projects, you can also benefit from integration with Vue.js, Angular, jQuery, and such server-side technologies as Laravel, Node.js, ASP.NET, and other. 

DHTMLX Gantt is constantly evolving, and it’s hard to describe all available features in one article. If you want to learn more about its possibilities, you can visit the homepage of the project or try the demo on GitHub

4. React Gantt by Bryntum

Last but not least, React Gantt Chart made by Bryntum, a company that is well known for its high-quality plugins for the Ext JS framework. The scheduling engine is called Chronograph and was built from scratch to provide excellent performance. Asynchronous rescheduling can handle any number of tasks. After moving a task, the resulting changeset is animated into place so users can track how one change affects others more easily. 

Developers have implemented every feature that you may need for effective project management. Drag-and-drop support allows resizing and creating tasks using the mouse or touch devices. Programmatic validation of editing actions helps to avoid possible errors and ensure the accuracy of the provided information. Customizable tooltips allow using HTML to define which extra details on a specific task will be provided to users. 

A built-in customizable context menu helps to implement the functionality required by a specific business. You can filter the available tasks on any condition and change the scale. Critical path calculation is available as well. The use of leads and lags helps to make the project management process flexible. You can create various types of dependencies between tasks (FF/FS/SF/SS). 

All elements can be styled easily using just plain CSS. Row height is customizable and can be changed dynamically, and each timeline element can be rendered with your own custom template. Developers also implemented some server/database integration features that allow you to work with PHP, Java, ASP.NET, and other technologies.



Source link

Post image
Strategy

Making a webapp for Cotsworth/International Fixed Calendar. …


So, I’m trying to make a calendar webapp, currently only for personal use, since it’s in development. I’ve designed the calendar table without any problems. HTML and CSS is no problem.

I also have a tool on that site to convert from Gregorian to Cotsworth, which I grabbed from somewhere else.

However, I want the site to display today’s date automatically, and I’ve laid the ground work for that in PHP. I defined a variable which counts the days since January 1st, and have a lengthy ifelse list to get current month from the $dayofyear variable I defined, but to go further and actually get the date in IFC format is the thing I’ve not been able to. Any help on that would be greatly appreciated!

Here’s the code:

$now = time(); // or your date as well

$your_date = strtotime("2020-01-01"); //yyyy-

$dayofyear = $now - $your_date;

$day = round($dayofyear / (60 * 60 * 24));

$date = round($dayofyear / (7));

$year = date("Y");

if ($day > 0 && $day < 27) {

`echo 'Januar ', $year;`

}

elseif ($day > 28 && $day < 55) {

`echo 'Februar ', $year;`

}

elseif ($day > 56 && $day < 83) {

`echo 'Mars ', $year;`

}

elseif ($day > 84 && $day < 111) {

`echo 'April ', $year;`

}

elseif ($day > 112 && $day < 139) {

`echo 'Mai ', $year;`

}

elseif ($day > 140 && $day < 168) {

`echo 'Juni ', $year;`

}

elseif ($day > 169 && $day < 196) {

`echo 'Sol ', $year;`

}

elseif ($day > 197 && $day < 224) {

`echo 'Juli ', $year;`

}

elseif ($day > 225 && $day < 252) {

`echo 'August ', $year;`

}

elseif ($day > 253 && $day < 280) {

`echo 'September ', $year;`

}

elseif ($day > 281 && $day < 308) {

`echo 'Oktober ', $year;`

}

elseif ($day > 309 && $day < 336) {

`echo 'November ', $year;`

}

elseif ($day > 337 && $day < 365) {

`echo 'Desember ', $year;`

}

else {

`echo '<i>Feil i kildekode...</i></p>';`

}

If you’re unfamiliar with the Cotsworth Calendar (IFC), it’s divided the year into thirteen months with 28 days each, plus an extra day in December to add up to 365 total. Leap day is placed at the end of june. Those two extra days are not assigned to any weekday, but stands as their own separate days.

Post image

Heres what December looks like, with the holidays marked out. Nyttårsaften is New Years Eve, or Year Day as Cotsworth himself renamed it. (It also happens to be my birthday)



Source link

Creating an Editable Site with Google Sheets and Eleventy
Strategy

Creating an Editable Site with Google Sheets and Eleventy


Remember Tabletop.js? We just covered it a little bit ago in this same exact context: building editable websites. It’s a tool that turns a Google Sheet into an API, that you as a developer can hit for data when building a website. In that last article, we used that API on the client side, meaning JavaScript needed to run on every single page view, hit that URL for the data, and build the page. That might be OK in some circumstances, but let’s do it one better. Let’s hit the API during the build step so that the content is built into the HTML directly. This will be far faster and more resilient.

The situation

As a developer, you might have had to work with clients who keep bugging you with unending revisions on content, sometimes, even after months of building the site. That can be frustrating as it keeps pulling you back, preventing you from doing more productive work.

We’re going to give them the keys to updating content themselves using a tool they are probably already familiar with: Google Sheets.

A new tool

In the last article, we introduced the concept of using Google Sheets with Tabletop.js. Now let’s introduce a new tool to this party: Eleventy

We’ll be using Eleventy (a static site generator) because we want the site to be rendered as a pure static site without having to ship all of the under workings of the site in the client side JavaScript. We’ll be pulling the content from the API at build time and having Eleventy create a minified index.html that we’ll push to the server for the production website. By being static, this allows the page to load faster and is better for security reasons.

The spreadsheet

We’ll be using a demo I built, with its repo and Google Sheet to demonstrate how to replicate something similar in your own projects. First, we’ll need a Google Sheet which will be our data store.

Open a new spreadsheet and enter your own values in the columns just like mine. The first cell of each column is the reference that’ll be used later in our JavaScript, and the second cell is the actual content that gets displayed.

In the first column, “header” is the reference name and “Please edit me!” is the actual content in the first column.

Next up, we’ll publish the data to the web by clicking on File → Publish to the web in the menu bar.

A link will be provided, but it’s technically useless to us, so we can ignore it. The important thing is that the spreadsheet(and its data) is now publicly accessible so we can fetch it for our app.

Take note that we’ll need the unique ID of the sheet from its URL  as we go on.

Node is required to continue, so be sure that’s installed. If you want to cut through the process of installing all of thedependencies for this work, you can fork or download my repo and run:

npm install

Run this command next — I’ll explain why it’s important in a bit:

npm run seed

Then to run it locally:

npm run dev

Alright, let’s go into src/site/_data/prod/sheet.js. This is where we’re going to pull in data from the GoogleSheet, then turn it into an object we can easily use, and finally convert the JavaScript object back to JSON format. The JSON is stored locally for development so we don’t need to hit the API every time.

Here’s the code we want in there. Again, be sure to change the variable sheetID to the unique ID of your own sheet.


module.exports = () => {
  return new Promise((resolve, reject) => {
    console.log(`Requesting content from ${googleSheetUrl}`);
    axios.get(googleSheetUrl)
      .then(response => {
        // massage the data from the Google Sheets API into
        // a shape that will more convenient for us in our SSG.
        var data = {
          "content": []
        };
        response.data.feed.entry.forEach(item => {
          data.content.push({
            "header": item.gsx$header.$t,
            "header2": item.gsx$header2.$t,
            "body": item.gsx$body.$t,
            "body2": item.gsx$body2.$t,
            "body3":  item.gsx$body3.$t,
            "body4": item.gsx$body4.$t,
            "body5": item.gsx$body5.$t,
            "body6":  item.gsx$body6.$t,
            "body7": item.gsx$body7.$t,
            "body8": item.gsx$body8.$t,
            "body9":  item.gsx$body9.$t,
            "body10": item.gsx$body10.$t,
            "body11": item.gsx$body11.$t,
            "body12":  item.gsx$body12.$t,
            "body13": item.gsx$body13.$t,
            "body14": item.gsx$body14.$t,
            "body15":  item.gsx$body15.$t,
            "body16": item.gsx$body16.$t,
            "body17": item.gsx$body17.$t,
            
          })
        });
        // stash the data locally for developing without
        // needing to hit the API each time.
        seed(JSON.stringify(data), `${__dirname}/../dev/sheet.json`);
        // resolve the promise and return the data
        resolve(data);
      })
      // uh-oh. Handle any errrors we might encounter
      .catch(error => {
        console.log('Error :', error);
        reject(error);
      });
  })
}

In module.exports, there’s a promise that’ll resolve our data or throw errors when necessary. You’ll notice that I’m using a axios to fetch the data from the spreadsheet. I like the it handles status error codes by rejecting the promise automatically, unlike something like Fetch that requires monitoring error codes manually.

I created a data object in there with a content array in it. Feel free to change the structure of the object, depending on what the spreadsheet looks like.

We’re using the forEach() method to loop through each spreadsheet column while equating it with the corresponding name we want to allocate to it, while pushing all of these into the data object as content. 

Remember that seed command from earlier? We’re using seed to transform what’s in the data object to JSON by way of JSON.stringify, which is then sent to src/site/_data/dev/sheet.json

Yes! Now have data in a format we can use with any templating engine, like Nunjucks, to manipulate it. But, we’re focusing on content in this project, so we’ll be using the index.md template format to communicate the data stored in the project.

For example, here’s how it looks to pull item.header through a for loop statement:

<div class="listing">
{%- for item in sheet.content -%}
  <h1>{{ item.header }} </h1>
{%- endfor -%}
</div>

If you’re using Nunjucks, or any other templating engine, you’ll have to pull the data accordingly.

Finally, let’s build this out:

npm run build

Note that you’ll want a dist folder in the project where the build process can send the compiled assets.

But that’s not all! If we were to edit the Google Sheet, we won’t see anything update on our site. That’s where Zapier comes in. We can “zap” Google sheet and Netlify so that an update to the Google Sheet triggers a deployment from Netlify.

Assuming you have a Zapier account up and running, we can create the zap by granting permissions for Google and Netlify to talk to one another, then adding triggers.

The recipe we’re looking for? We’re connecting Google Sheets to Netlify so that when a “new or updated sheet row” takes place, Netlify starts a deploy. It’s truly a set-it-and-forget-it sort of deal.

Yay, there we go! We have a performant static site that takes its data from Google Sheets and deploys automatically when updates are made to the sheet.



Source link

Post image
Strategy

adding 3rd input field to thumbnails? : web_design


Hi all, if you know cargo then you know the thumbnail option is not as useful as it could be. Right now there’s two input fields: Title + Tags. I would somehow like to add a third input field for info on the links, but I’m struggling with working out the code. I asked cargo collective for help and they were like ‘naw ask a web developer.’ So. Here I am on reddit, hoping the Internet might be able to help me out more.

Screenshot of thumbnail on website with only first input shown (I use the tags to organize, so that’s not an option to utilize).

Post image

Full website if anyone is curious/quarantined: https://thedustmag.cargo.site



Source link