1660713240
NProgress
Minimalist progress bar
Slim progress bars for Ajax'y applications. Inspired by Google, YouTube, and Medium.
Add nprogress.js and nprogress.css to your project.
<script src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>
NProgress is available via bower and npm.
$ npm install --save nprogress
Also available via unpkg CDN:
Simply call start()
and done()
to control the progress bar.
NProgress.start();
NProgress.done();
Ensure you're using Turbolinks 5+, and use this: (explained here)
$(document).on('turbolinks:click', function() {
NProgress.start();
});
$(document).on('turbolinks:render', function() {
NProgress.done();
NProgress.remove();
});
Ensure you're using Turbolinks 1.3.0+, and use this: (explained here)
$(document).on('page:fetch', function() { NProgress.start(); });
$(document).on('page:change', function() { NProgress.done(); });
$(document).on('page:restore', function() { NProgress.remove(); });
Try this: (explained here)
$(document).on('pjax:start', function() { NProgress.start(); });
$(document).on('pjax:end', function() { NProgress.done(); });
Add progress to your Ajax calls! Bind it to the jQuery ajaxStart
and ajaxStop
events.
Make a fancy loading bar even without Turbolinks/Pjax! Bind it to $(document).ready
and $(window).load
.
Percentages: To set a progress percentage, call .set(n)
, where n is a number between 0..1
.
NProgress.set(0.0); // Sorta same as .start()
NProgress.set(0.4);
NProgress.set(1.0); // Sorta same as .done()
Incrementing: To increment the progress bar, just use .inc()
. This increments it with a random amount. This will never get to 100%: use it for every image load (or similar).
NProgress.inc();
If you want to increment by a specific value, you can pass that as a parameter:
NProgress.inc(0.2); // This will get the current status value and adds 0.2 until status is 0.994
Force-done: By passing true
to done()
, it will show the progress bar even if it's not being shown. (The default behavior is that .done() will not do anything if .start() isn't called)
NProgress.done(true);
Get the status value: To get the status value, use .status
minimum
Changes the minimum percentage used upon starting. (default: 0.08
)
NProgress.configure({ minimum: 0.1 });
template
You can change the markup using template
. To keep the progress bar working, keep an element with role='bar'
in there. See the default template for reference.
NProgress.configure({
template: "<div class='....'>...</div>"
});
easing
and speed
Adjust animation settings using easing (a CSS easing string) and speed (in ms). (default: ease
and 200
)
NProgress.configure({ easing: 'ease', speed: 500 });
trickle
Turn off the automatic incrementing behavior by setting this to false
. (default: true
)
NProgress.configure({ trickle: false });
trickleSpeed
Adjust how often to trickle/increment, in ms.
NProgress.configure({ trickleSpeed: 200 });
showSpinner
Turn off loading spinner by setting it to false. (default: true
)
NProgress.configure({ showSpinner: false });
parent
specify this to change the parent container. (default: body
)
NProgress.configure({ parent: '#container' });
Just edit nprogress.css
to your liking. Tip: you probably only want to find and replace occurrences of #29d
.
The included CSS file is pretty minimal... in fact, feel free to scrap it and make your own!
Bugs and requests: submit them through the project's issues tracker.
Questions: ask them at StackOverflow with the tag nprogress.
Chat: join us at gitter.im.
NProgress © 2013-2017, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors.
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz
Author: rstacruz
Source Code: https://github.com/rstacruz/nprogress
License: MIT license
#javascript #progress #youtube #medium
1674813120
In this article, we will see how to validate multi step form wizard using jquery. Here, we will learn to validate the multi step form using jquery. First, we create the multi step form using bootstrap. Also, in this example, we are not using any jquery plugin for multi step form wizard.
So, let's see jquery multi step form with validation, how to create multi step form, multi step form wizard with jquery validation, bootstrap 4 multi step form wizard with validation, multi step form bootstrap 5, and jQuery multi step form with validation and next previous navigation.
Add HTML:
<html lang="en">
</head>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
</head>
<body>
<div class="main">
<h3>How To Validate Multi Step Form Using jQuery - Websolutionstuff</h3>
<form id="multistep_form">
<!-- progressbar -->
<ul id="progress_header">
<li class="active"></li>
<li></li>
<li></li>
</ul>
<!-- Step 01 -->
<div class="multistep-box">
<div class="title-box">
<h2>Create your account</h2>
</div>
<p>
<input type="text" name="email" placeholder="Email" id="email">
<span id="error-email"></span>
</p>
<p>
<input type="password" name="pass" placeholder="Password" id="pass">
<span id="error-pass"></span>
</p>
<p>
<input type="password" name="cpass" placeholder="Confirm Password" id="cpass">
<span id="error-cpass"></span>
</p>
<p class="nxt-prev-button"><input type="button" name="next" class="fs_next_btn action-button" value="Next" /></p>
</div>
<!-- Step 02 -->
<div class="multistep-box">
<div class="title-box">
<h2>Social Profiles</h2>
</div>
<p>
<input type="text" name="twitter" placeholder="Twitter" id="twitter">
<span id="error-twitter"></span>
</p>
<p>
<input type="text" name="facebook" placeholder="Facebook" id="facebook">
<span id="error-facebook"></span>
</p>
<p>
<input type="text" name="linkedin" placeholder="Linkedin" id="linkedin">
<span id="error-linkedin"></span>
</p>
<p class="nxt-prev-button">
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="button" name="next" class="ss_next_btn action-button" value="Next" />
</p>
</div>
<!-- Step 03 -->
<div class="multistep-box">
<div class="title-box">
<h2>Personal Details</h2>
</div>
<p>
<input type="text" name="fname" placeholder="First Name" id="fname">
<span id="error-fname"></span>
</p>
<p>
<input type="text" name="lname" placeholder="Last Name" id="lname">
<span id="error-lname"></span>
</p>
<p>
<input type="text" name="phone" placeholder="Phone" id="phone">
<span id="error-phone"></span>
</p>
<p>
<textarea name="address" placeholder="Address" id="address"></textarea>
<span id="error-address"></span>
</p>
<p class="nxt-prev-button"><input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit_btn ts_next_btn action-button" value="Submit" />
</p>
</div>
</form>
<h1>You are successfully logged in</h1>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.0/jquery.easing.js" type="text/javascript"></script>
</body>
</html>
Add CSS:
body {
display: inline-block;
width: 100%;
height: 100vh;
overflow: hidden;
background-image: url("https://img1.akspic.com/image/80377-gadget-numeric_keypad-input_device-electronic_device-space_bar-3840x2160.jpg");
background-repeat: no-repeat;
background-size: cover;
position: relative;
margin: 0;
font-weight: 400;
font-family: 'Roboto', sans-serif;
}
body:before {
content: "";
display: block;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.main {
position: absolute;
left: 0;
right: 0;
top: 30px;
margin: 0 auto;
height: 515px;
}
input:-internal-autofill-selected {
background-color: #fff !important;
}
#multistep_form {
width: 550px;
margin: 0 auto;
text-align: center;
position: relative;
height: 100%;
z-index: 999;
opacity: 1;
visibility: visible;
}
/*progress header*/
#progress_header {
overflow: hidden;
margin: 0 auto 30px;
padding: 0;
}
#progress_header li {
list-style-type: none;
width: 33.33%;
float: left;
position: relative;
font-size: 16px;
font-weight: bold;
font-family: monospace;
color: #fff;
text-transform: uppercase;
}
#progress_header li:after {
width: 35px;
line-height: 35px;
display: block;
font-size: 22px;
color: #888;
font-family: monospace;
background-color: #fff;
border-radius: 100px;
margin: 0 auto;
background-repeat: no-repeat;
font-family: 'Roboto', sans-serif;
}
#progress_header li:nth-child(1):after {
content: "1";
}
#progress_header li:nth-child(2):after {
content: "2";
}
#progress_header li:nth-child(3):after {
content: "3";
}
#progress_header li:before {
content: '';
width: 100%;
height: 5px;
background: #fff;
position: absolute;
left: -50%;
top: 50%;
z-index: -1;
}
#progress_header li:first-child:before {
content: none;
}
#progress_header li.active:before,
#progress_header li.active:after {
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b) !important;
color: #fff !important;
transition: all 0.5s;
}
/*title*/
.title-box {
width: 100%;
margin: 0 0 30px 0;
}
.title-box h2 {
font-size: 22px;
text-transform: uppercase;
color: #2C3E50;
margin: 0;
font-family: cursive;
display: inline-block;
position: relative;
padding: 0 0 10px 0;
font-family: 'Roboto', sans-serif;
}
.title-box h2:before {
content: "";
background: #6ddc8b;
width: 70px;
height: 2px;
position: absolute;
bottom: 0;
left: 0;
right: 0;
margin: 0 auto;
display: block;
}
.title-box h2:after {
content: "";
background: #6ddc8b;
width: 50px;
height: 2px;
position: absolute;
bottom: -5px;
left: 0;
right: 0;
margin: 0 auto;
display: block;
}
/*Input and Button*/
.multistep-box {
background: white;
border: 0 none;
border-radius: 3px;
box-shadow: 1px 1px 55px 3px rgba(255, 255, 255, 0.4);
padding: 30px 30px;
box-sizing: border-box;
width: 80%;
margin: 0 10%;
position: absolute;
}
.multistep-box:not(:first-of-type) {
display: none;
}
.multistep-box p {
margin: 0 0 12px 0;
text-align: left;
}
.multistep-box span {
font-size: 12px;
color: #FF0000;
}
input, textarea {
padding: 15px;
border: 1px solid #ccc;
border-radius: 3px;
margin: 0;
width: 100%;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
color: #2C3E50;
font-size: 13px;
transition: all 0.5s;
outline: none;
}
input:focus, textarea:focus {
box-shadow: inset 0px 0px 50px 2px rgb(0,0,0,0.1);
}
input.box_error, textarea.box_error {
border-color: #FF0000;
box-shadow: inset 0px 0px 50px 2px rgb(255,0,0,0.1);
}
input.box_error:focus, textarea.box_error:focus {
box-shadow: inset 0px 0px 50px 2px rgb(255,0,0,0.1);
}
p.nxt-prev-button {
margin: 25px 0 0 0;
text-align: center;
}
.action-button {
width: 100px;
font-weight: bold;
color: white;
border: 0 none;
border-radius: 1px;
cursor: pointer;
padding: 10px 5px;
margin: 0 5px;
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b);
transition: all 0.5s;
}
.action-button:hover,
.action-button:focus {
box-shadow: 0 0 0 2px white, 0 0 0 3px #6ce199;
}
.form_submited #multistep_form {
opacity: 0;
visibility: hidden;
}
.form_submited h1 {
-webkit-background-clip: text;
transform: translate(0%, 0%);
-webkit-transform: translate(0%, 0%);
transition: all 0.3s ease;
opacity: 1;
visibility: visible;
}
h1 {
margin: 0;
text-align: center;
font-size: 90px;
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b) !important;
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b) !important;
color: transparent;
-webkit-background-clip: text;
-webkit-background-clip: text;
transform: translate(0%, -80%);
-webkit-transform: translate(0%, -80%);
transition: all 0.3s ease;
opacity: 0;
visibility: hidden;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
text-align: center;
top: 50%;
}
h3{
color:#fff;
text-align:center;
margin-bottom:20px;
}
Add jQuery:
var current_slide, next_slide, previous_slide;
var left, opacity, scale;
var animation;
var error = false;
// email validation
$("#email").keyup(function() {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($("#email").val())) {
$("#error-email").text('Please enter an Email addres.');
$("#email").addClass("box_error");
error = true;
} else {
$("#error-email").text('');
error = false;
$("#email").removeClass("box_error");
}
});
// password validation
$("#pass").keyup(function() {
var pass = $("#pass").val();
var cpass = $("#cpass").val();
if (pass != '') {
$("#error-pass").text('');
error = false;
$("#pass").removeClass("box_error");
}
if (pass != cpass && cpass != '') {
$("#error-cpass").text('Password and Confirm Password is not matched.');
error = true;
} else {
$("#error-cpass").text('');
error = false;
}
});
// confirm password validation
$("#cpass").keyup(function() {
var pass = $("#pass").val();
var cpass = $("#cpass").val();
if (pass != cpass) {
$("#error-cpass").text('Please enter the same Password as above.');
$("#cpass").addClass("box_error");
error = true;
} else {
$("#error-cpass").text('');
error = false;
$("#cpass").removeClass("box_error");
}
});
// twitter
$("#twitter").keyup(function() {
var twitterReg = /https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/;
if (!twitterReg.test($("#twitter").val())) {
$("#error-twitter").text('Twitter link is not valid.');
$("#twitter").addClass("box_error");
error = true;
} else {
$("#error-twitter").text('');
error = false;
$("#twitter").removeClass("box_error");
}
});
// facebook
$("#facebook").keyup(function() {
var facebookReg = /^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/;
if (!facebookReg.test($("#facebook").val())) {
$("#error-facebook").text('Facebook link is not valid.');
$("#facebook").addClass("box_error");
error = true;
} else {
$("#error-facebook").text('');
error = false;
$("#facebook").removeClass("box_error");
}
});
// linkedin
$("#linkedin").keyup(function() {
var linkedinReg = /(ftp|http|https):\/\/?(?:www\.)?linkedin.com(\w+:{0,1}\w*@)?(\S+)(:([0-9])+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (!linkedinReg.test($("#linkedin").val())) {
$("#error-linkedin").text('Linkedin link is not valid.');
$("#linkedin").addClass("box_error");
error = true;
} else {
$("#error-linkedin").text('');
error = false;
$("#linkedin").removeClass("box_error");
}
});
// first name
$("#fname").keyup(function() {
var fname = $("#fname").val();
if (fname == '') {
$("#error-fname").text('Enter your First name.');
$("#fname").addClass("box_error");
error = true;
} else {
$("#error-fname").text('');
error = false;
}
if ((fname.length <= 2) || (fname.length > 20)) {
$("#error-fname").text("User length must be between 2 and 20 Characters.");
$("#fname").addClass("box_error");
error = true;
}
if (!isNaN(fname)) {
$("#error-fname").text("Only Characters are allowed.");
$("#fname").addClass("box_error");
error = true;
} else {
$("#fname").removeClass("box_error");
}
});
// last name
$("#lname").keyup(function() {
var lname = $("#lname").val();
if (lname != lname) {
$("#error-lname").text('Enter your Last name.');
$("#lname").addClass("box_error");
error = true;
} else {
$("#error-lname").text('');
error = false;
}
if ((lname.length <= 2) || (lname.length > 20)) {
$("#error-lname").text("User length must be between 2 and 20 Characters.");
$("#lname").addClass("box_error");
error = true;
}
if (!isNaN(lname)) {
$("#error-lname").text("Only Characters are allowed.");
$("#lname").addClass("box_error");
error = true;
} else {
$("#lname").removeClass("box_error");
}
});
// phone
$("#phone").keyup(function() {
var phone = $("#phone").val();
if (phone != phone) {
$("#error-phone").text('Enter your Phone number.');
$("#phone").addClass("box_error");
error = true;
} else {
$("#error-phone").text('');
error = false;
}
if (phone.length != 10) {
$("#error-phone").text("Mobile number must be of 10 Digits only.");
$("#phone").addClass("box_error");
error = true;
} else {
$("#phone").removeClass("box_error");
}
});
// address
$("#address").keyup(function() {
var address = $("#address").val();
if (address != address) {
$("#error-address").text('Enter your Address.');
$("#address").addClass("box_error");
error = true;
} else {
$("#error-address").text('');
error = false;
$("#address").removeClass("box_error");
}
});
// first step validation
$(".fs_next_btn").click(function() {
// email
if ($("#email").val() == '') {
$("#error-email").text('Please enter an email address.');
$("#email").addClass("box_error");
error = true;
} else {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($("#email").val())) {
$("#error-email").text('Please insert a valid email address.');
error = true;
} else {
$("#error-email").text('');
$("#email").removeClass("box_error");
}
}
// password
if ($("#pass").val() == '') {
$("#error-pass").text('Please enter a password.');
$("#pass").addClass("box_error");
error = true;
}
if ($("#cpass").val() == '') {
$("#error-cpass").text('Please enter a Confirm password.');
$("#cpass").addClass("box_error");
error = true;
} else {
var pass = $("#pass").val();
var cpass = $("#cpass").val();
if (pass != cpass) {
$("#error-cpass").text('Please enter the same password as above.');
error = true;
} else {
$("#error-cpass").text('');
$("#pass").removeClass("box_error");
$("#cpass").removeClass("box_error");
}
}
// animation
if (!error) {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
next_slide = $(this).parent().parent().next();
$("#progress_header li").eq($(".multistep-box").index(next_slide)).addClass("active");
next_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 1 - (1 - now) * 0.2;
left = (now * 50) + "%";
opacity = 1 - now;
current_slide.css({
'transform': 'scale(' + scale + ')'
});
next_slide.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
}
});
// second step validation
$(".ss_next_btn").click(function() {
// twitter
if ($("#twitter").val() == '') {
$("#error-twitter").text('twitter link is required.');
$("#twitter").addClass("box_error");
error = true;
} else {
var twitterReg = /https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/;
if (!twitterReg.test($("#twitter").val())) {
$("#error-twitter").text('Twitter link is not valid.');
error = true;
} else {
$("#error-twitter").text('');
$("#twitter").removeClass("box_error");
}
}
// facebook
if ($("#facebook").val() == '') {
$("#error-facebook").text('Facebook link is required.');
$("#facebook").addClass("box_error");
error = true;
} else {
var facebookReg = /^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/;
if (!facebookReg.test($("#facebook").val())) {
$("#error-facebook").text('Facebook link is not valid.');
error = true;
$("#facebook").addClass("box_error");
} else {
$("#error-facebook").text('');
}
}
// linkedin
if ($("#linkedin").val() == '') {
$("#error-linkedin").text('Linkedin link is required.');
$("#linkedin").addClass("box_error");
error = true;
} else {
var linkedinReg = /(ftp|http|https):\/\/?(?:www\.)?linkedin.com(\w+:{0,1}\w*@)?(\S+)(:([0-9])+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (!linkedinReg.test($("#linkedin").val())) {
$("#error-linkedin").text('Linkedin link is not valid.');
error = true;
} else {
$("#error-linkedin").text('');
$("#linkedin").removeClass("box_error");
}
}
if (!error) {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
next_slide = $(this).parent().parent().next();
$("#progress_header li").eq($(".multistep-box").index(next_slide)).addClass("active");
next_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 1 - (1 - now) * 0.2;
left = (now * 50) + "%";
opacity = 1 - now;
current_slide.css({
'transform': 'scale(' + scale + ')'
});
next_slide.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
}
});
// third step validation
$(".ts_next_btn").click(function() {
// first name
if ($("#fname").val() == '') {
$("#error-fname").text('Enter your First name.');
$("#fname").addClass("box_error");
error = true;
} else {
var fname = $("#fname").val();
if (fname != fname) {
$("#error-fname").text('First name is required.');
error = true;
} else {
$("#error-fname").text('');
error = false;
$("#fname").removeClass("box_error");
}
if ((fname.length <= 2) || (fname.length > 20)) {
$("#error-fname").text("User length must be between 2 and 20 Characters.");
error = true;
}
if (!isNaN(fname)) {
$("#error-fname").text("Only Characters are allowed.");
error = true;
} else {
$("#fname").removeClass("box_error");
}
}
// last name
if ($("#lname").val() == '') {
$("#error-lname").text('Enter your Last name.');
$("#lname").addClass("box_error");
error = true;
} else {
var lname = $("#lname").val();
if (lname != lname) {
$("#error-lname").text('Last name is required.');
error = true;
} else {
$("#error-lname").text('');
error = false;
}
if ((lname.length <= 2) || (lname.length > 20)) {
$("#error-lname").text("User length must be between 2 and 20 Characters.");
error = true;
}
if (!isNaN(lname)) {
$("#error-lname").text("Only Characters are allowed.");
error = true;
} else {
$("#lname").removeClass("box_error");
}
}
// phone
if ($("#phone").val() == '') {
$("#error-phone").text('Enter your Phone number.');
$("#phone").addClass("box_error");
error = true;
} else {
var phone = $("#phone").val();
if (phone != phone) {
$("#error-phone").text('Phone number is required.');
error = true;
} else {
$("#error-phone").text('');
error = false;
}
if (phone.length != 10) {
$("#error-phone").text("Mobile number must be of 10 Digits only.");
error = true;
} else {
$("#phone").removeClass("box_error");
}
}
// address
if ($("#address").val() == '') {
$("#error-address").text('Enter your Address.');
$("#address").addClass("box_error");
error = true;
} else {
var address = $("#address").val();
if (address != address) {
$("#error-address").text('Address is required.');
error = true;
} else {
$("#error-address").text('');
$("#address").removeClass("box_error");
error = false;
}
}
if (!error) {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
next_slide = $(this).parent().parent().next();
$("#progress_header li").eq($(".multistep-box").index(next_slide)).addClass("active");
next_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 1 - (1 - now) * 0.2;
left = (now * 50) + "%";
opacity = 1 - now;
current_slide.css({
'transform': 'scale(' + scale + ')'
});
next_slide.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
}
});
// previous
$(".previous").click(function() {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
previous_slide = $(this).parent().parent().prev();
$("#progress_header li").eq($(".multistep-box").index(current_slide)).removeClass("active");
previous_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 0.8 + (1 - now) * 0.2;
left = ((1 - now) * 50) + "%";
opacity = 1 - now;
current_slide.css({
'left': left
});
previous_slide.css({
'transform': 'scale(' + scale + ')',
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
});
$(".submit_btn").click(function() {
if (!error){
$(".main").addClass("form_submited");
}
return false;
})
Output:
Original article source at: https://websolutionstuff.com/
1660926960
Next.js is a server-side framework with an emphasis on performance. It is also of the most widely used JavaScript frameworks (beneath React) worldwide. The server-side rendering for React apps is then done by Next.js.
Sometimes, switching from one route to another requires a little extra time for various reasons. It can be making an API request or rendering a complicated page component in the background. When this happens, the app briefly appears to have stopped responding before abruptly switching to the next route. For example, the image below shows a client switching from one page to another.
Without a loading indicator, the user may believe that nothing happened or that the page is malfunctioning, even if all that is happening is that the page is simply fetching content. If you look closely, you will notice this. This can make users highly confused and have a bad effect on the website and user encounter with such application.
The solution for this problem is to show a top progress bar on the Next.js website until the data from the server is loaded into the website, which is to say that the progress bar gives the user the impression that the page is loading and also how far the page has gone in terms of loading completely. Take, for instance, this page below, which has a progress bar indicator.
Let’s see how we can build this nice progress bar indicator for our Next.js Application.
Progress Bar Indicators could be determinate or indeterminate:
An indicator is determinate when it indicates how long an operation will take when the percentage complete is detectable.
An indicator is indeterminate when it requests that the user waits while something finishes, when it’s not necessary to indicate how long it will take.
In a general-purpose progress bar indicator, there are many features to cover to archive a user-friendly Progress Bar Indicator.
Let’s quickly move to our terminal and run the following command to create a Next.js project.
npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app
You’ll be prompted to give a name to your project.
I am creating a new file in the pages folder first. This will provide you with a new route. We’ll give it a name about.js
: just an h1
tag and a button
that directs to the home page.
//about.js//
import Link from 'next/link'
function about() {
return (
<div><><h1>Next.Js Progress Bar Indicator</h1><ul>
<div className='flex'>
<Link href="/">
<a>Home</a>
</Link>
<Link href="/about">
<a>About Us</a>
</Link>
<Link href="/blog">
<a>Blog Post</a>
</Link>
<Link href="/contact">
<a>Contact Us</a>
</Link>
</div>
<h3>About Us</h3>
</ul></></div>
)
}
export default about
We’ll also create other files to make our app flexible. We’ll create blog post
and contact us
files, and routes/links them back to the home
file.
nprogress
is a package that offers a progress bar that moves. Install it using one of the commands below.
npm i nprogress
# or
yarn add nprogress
After client-side navigation begins, the nprogress
animation will automatically start, and stop when navigation is complete. We can use the built-in Router
events in Next.js to bind them, and we’ll bind the events in a unique component to keep the code tidy.
// _app.js
import Router from 'next/router';
import NProgress from 'nprogress'; //nprogress module
import 'nprogress/nprogress.css'; //styles of nprogress
//Route Events.
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp;
We ensure that the event handler binds outside of components to avoid binding multiple handlers. Also, the loading spinner that comes as default can be removed depending on our use case.
NProgress.configure({ showSpinner: false })
The code has been completed. Let’s look at how our progress bar will seem with our Next.js App.
You can add change props of nProgress
like color, height, key, ref, startPosition, and many more. I mostly just change the color and height because I like the other stylings the way they are. Here is how you can change the color and height.
By default, nprogress shows a blue progress bar on top of the page. That may not match the website’s look and feel. To customize:
Nprogress.css
in the styles directory.--primary-color: #29d
to whichever color you want/* Make clicks pass-through */
#nprogress {
--primary-color: #ff0000; //changing mine to red
pointer-events: none;
}
#nprogress .bar {
background: var(--primary-color);
position: fixed;
z-index: 1031;
top: 0;
left: 0;
width: 100%;
height: 10px; //Also increasing my bar size to 10px just for illustration purpose
}
/* Fancy blur effect */
#nprogress .peg {
display: block;
position: absolute;
right: 0px;
width: 100px;
height: 100%;
box-shadow: 0 0 10px var(--primary-color), 0 0 5px var(--primary-color);
opacity: 1.0;
-webkit-transform: rotate(3deg) translate(0px, -4px);
-ms-transform: rotate(3deg) translate(0px, -4px);
transform: rotate(3deg) translate(0px, -4px);
}
/* Remove these to get rid of the spinner */
#nprogress .spinner {
display: block;
position: fixed;
z-index: 1031;
top: 15px;
right: 15px;
}
#nprogress .spinner-icon {
width: 18px;
height: 18px;
box-sizing: border-box;
border: solid 2px transparent;
border-top-color: var(--primary-color);
border-left-color: var(--primary-color);
border-radius: 50%;
-webkit-animation: nprogress-spinner 400ms linear infinite;
animation: nprogress-spinner 400ms linear infinite;
}
.nprogress-custom-parent {
overflow: hidden;
position: relative;
}
.nprogress-custom-parent #nprogress .spinner,
.nprogress-custom-parent #nprogress .bar {
position: absolute;
}
@-webkit-keyframes nprogress-spinner {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes nprogress-spinner {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
*import*
”../styles/Nprogress.css”Progress Bar Indicators are mainly used by online applications. For example, online stores use them to increase conversion rates; progress bar indicators make users pass the required procedures necessary to complete the purchase.
Link: https://blog.openreplay.com/how-to-build-a-progress-bar-indicator-for-next-js
#nextjs #react
1660826460
Next.js est un framework côté serveur mettant l'accent sur les performances. C'est également l'un des frameworks JavaScript les plus utilisés (après React) dans le monde. Le rendu côté serveur pour les applications React est ensuite effectué par Next.js.
Parfois, passer d'un itinéraire à un autre nécessite un peu de temps supplémentaire pour diverses raisons. Il peut s'agir de faire une requête API ou de rendre un composant de page compliqué en arrière-plan. Lorsque cela se produit, l'application semble brièvement avoir cessé de répondre avant de passer brusquement à l'itinéraire suivant. Par exemple, l'image ci-dessous montre un client passant d'une page à une autre.
Sans indicateur de chargement, l'utilisateur peut croire que rien ne s'est passé ou que la page fonctionne mal, même si tout ce qui se passe est que la page ne fait que récupérer du contenu. Si vous regardez attentivement, vous remarquerez cela. Cela peut rendre les utilisateurs très confus et avoir un effet néfaste sur le site Web et la rencontre des utilisateurs avec une telle application.
La solution à ce problème est d'afficher une barre de progression supérieure sur le site Web Next.js jusqu'à ce que les données du serveur soient chargées sur le site Web, c'est-à-dire que la barre de progression donne à l'utilisateur l'impression que la page se charge et aussi jusqu'où la page est allée en termes de chargement complet. Prenez, par exemple, cette page ci-dessous, qui a un indicateur de barre de progression.
Voyons comment nous pouvons créer ce bel indicateur de barre de progression pour notre application Next.js.
Les indicateurs de barre de progression peuvent être déterminés ou indéterminés :
Un indicateur est déterminé lorsqu'il indique la durée d'une opération lorsque le pourcentage d'achèvement est détectable.
Un indicateur est indéterminé lorsqu'il demande à l'utilisateur d'attendre que quelque chose se termine, alors qu'il n'est pas nécessaire d'indiquer combien de temps cela prendra.
Dans un indicateur de barre de progression à usage général, il existe de nombreuses fonctionnalités à couvrir pour archiver un indicateur de barre de progression convivial.
Passons rapidement à notre terminal et exécutons la commande suivante pour créer un projet Next.js.
npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app
Vous serez invité à donner un nom à votre projet.
Je crée d'abord un nouveau fichier dans le dossier pages. Cela vous fournira un nouvel itinéraire. Nous allons lui donner un nom about.js
: juste une h1
balise et un button
qui dirige vers la page d'accueil.
//about.js//
import Link from 'next/link'
function about() {
return (
<div><><h1>Next.Js Progress Bar Indicator</h1><ul>
<div className='flex'>
<Link href="/">
<a>Home</a>
</Link>
<Link href="/about">
<a>About Us</a>
</Link>
<Link href="/blog">
<a>Blog Post</a>
</Link>
<Link href="/contact">
<a>Contact Us</a>
</Link>
</div>
<h3>About Us</h3>
</ul></></div>
)
}
export default about
Nous allons également créer d'autres fichiers pour rendre notre application flexible. Nous allons créer des fichiers blog post
et contact us
les acheminer/lier vers le home
fichier.
nprogress
est un package qui propose une barre de progression qui bouge. Installez-le en utilisant l'une des commandes ci-dessous.
npm i nprogress
# or
yarn add nprogress
Après le début de la navigation côté client, l' nprogress
animation démarre automatiquement et s'arrête une fois la navigation terminée. Nous pouvons utiliser les Router
événements intégrés dans Next.js pour les lier, et nous lierons les événements dans un composant unique pour garder le code bien rangé.
// _app.js
import Router from 'next/router';
import NProgress from 'nprogress'; //nprogress module
import 'nprogress/nprogress.css'; //styles of nprogress
//Route Events.
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp;
Nous nous assurons que le gestionnaire d'événements se lie en dehors des composants pour éviter de lier plusieurs gestionnaires. De plus, le spinner de chargement fourni par défaut peut être supprimé en fonction de notre cas d'utilisation.
NProgress.configure({ showSpinner: false })
Le code a été complété. Regardons à quoi ressemblera notre barre de progression avec notre application Next.js.
Vous pouvez ajouter des accessoires de changement nProgress
tels que la couleur, la hauteur, la clé, la référence, la position de départ et bien d'autres. Je change surtout la couleur et la hauteur parce que j'aime les autres styles tels qu'ils sont. Voici comment vous pouvez changer la couleur et la hauteur.
Par défaut, nprogress affiche une barre de progression bleue en haut de la page. Cela peut ne pas correspondre à l'apparence du site Web. Customiser:
Nprogress.css
dans le répertoire styles.--primary-color: #29d
passez à la couleur de votre choix/* Make clicks pass-through */
#nprogress {
--primary-color: #ff0000; //changing mine to red
pointer-events: none;
}
#nprogress .bar {
background: var(--primary-color);
position: fixed;
z-index: 1031;
top: 0;
left: 0;
width: 100%;
height: 10px; //Also increasing my bar size to 10px just for illustration purpose
}
/* Fancy blur effect */
#nprogress .peg {
display: block;
position: absolute;
right: 0px;
width: 100px;
height: 100%;
box-shadow: 0 0 10px var(--primary-color), 0 0 5px var(--primary-color);
opacity: 1.0;
-webkit-transform: rotate(3deg) translate(0px, -4px);
-ms-transform: rotate(3deg) translate(0px, -4px);
transform: rotate(3deg) translate(0px, -4px);
}
/* Remove these to get rid of the spinner */
#nprogress .spinner {
display: block;
position: fixed;
z-index: 1031;
top: 15px;
right: 15px;
}
#nprogress .spinner-icon {
width: 18px;
height: 18px;
box-sizing: border-box;
border: solid 2px transparent;
border-top-color: var(--primary-color);
border-left-color: var(--primary-color);
border-radius: 50%;
-webkit-animation: nprogress-spinner 400ms linear infinite;
animation: nprogress-spinner 400ms linear infinite;
}
.nprogress-custom-parent {
overflow: hidden;
position: relative;
}
.nprogress-custom-parent #nprogress .spinner,
.nprogress-custom-parent #nprogress .bar {
position: absolute;
}
@-webkit-keyframes nprogress-spinner {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes nprogress-spinner {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
*import*
"../styles/Nprogress.css"Les indicateurs de barre de progression sont principalement utilisés par les applications en ligne. Par exemple, les boutiques en ligne les utilisent pour augmenter les taux de conversion ; les indicateurs de barre de progression permettent aux utilisateurs de passer les procédures requises nécessaires pour terminer l'achat.
Lien : https://blog.openreplay.com/how-to-build-a-progress-bar-indicator-for-next-js
#nextjs #react
1660713240
NProgress
Minimalist progress bar
Slim progress bars for Ajax'y applications. Inspired by Google, YouTube, and Medium.
Add nprogress.js and nprogress.css to your project.
<script src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>
NProgress is available via bower and npm.
$ npm install --save nprogress
Also available via unpkg CDN:
Simply call start()
and done()
to control the progress bar.
NProgress.start();
NProgress.done();
Ensure you're using Turbolinks 5+, and use this: (explained here)
$(document).on('turbolinks:click', function() {
NProgress.start();
});
$(document).on('turbolinks:render', function() {
NProgress.done();
NProgress.remove();
});
Ensure you're using Turbolinks 1.3.0+, and use this: (explained here)
$(document).on('page:fetch', function() { NProgress.start(); });
$(document).on('page:change', function() { NProgress.done(); });
$(document).on('page:restore', function() { NProgress.remove(); });
Try this: (explained here)
$(document).on('pjax:start', function() { NProgress.start(); });
$(document).on('pjax:end', function() { NProgress.done(); });
Add progress to your Ajax calls! Bind it to the jQuery ajaxStart
and ajaxStop
events.
Make a fancy loading bar even without Turbolinks/Pjax! Bind it to $(document).ready
and $(window).load
.
Percentages: To set a progress percentage, call .set(n)
, where n is a number between 0..1
.
NProgress.set(0.0); // Sorta same as .start()
NProgress.set(0.4);
NProgress.set(1.0); // Sorta same as .done()
Incrementing: To increment the progress bar, just use .inc()
. This increments it with a random amount. This will never get to 100%: use it for every image load (or similar).
NProgress.inc();
If you want to increment by a specific value, you can pass that as a parameter:
NProgress.inc(0.2); // This will get the current status value and adds 0.2 until status is 0.994
Force-done: By passing true
to done()
, it will show the progress bar even if it's not being shown. (The default behavior is that .done() will not do anything if .start() isn't called)
NProgress.done(true);
Get the status value: To get the status value, use .status
minimum
Changes the minimum percentage used upon starting. (default: 0.08
)
NProgress.configure({ minimum: 0.1 });
template
You can change the markup using template
. To keep the progress bar working, keep an element with role='bar'
in there. See the default template for reference.
NProgress.configure({
template: "<div class='....'>...</div>"
});
easing
and speed
Adjust animation settings using easing (a CSS easing string) and speed (in ms). (default: ease
and 200
)
NProgress.configure({ easing: 'ease', speed: 500 });
trickle
Turn off the automatic incrementing behavior by setting this to false
. (default: true
)
NProgress.configure({ trickle: false });
trickleSpeed
Adjust how often to trickle/increment, in ms.
NProgress.configure({ trickleSpeed: 200 });
showSpinner
Turn off loading spinner by setting it to false. (default: true
)
NProgress.configure({ showSpinner: false });
parent
specify this to change the parent container. (default: body
)
NProgress.configure({ parent: '#container' });
Just edit nprogress.css
to your liking. Tip: you probably only want to find and replace occurrences of #29d
.
The included CSS file is pretty minimal... in fact, feel free to scrap it and make your own!
Bugs and requests: submit them through the project's issues tracker.
Questions: ask them at StackOverflow with the tag nprogress.
Chat: join us at gitter.im.
NProgress © 2013-2017, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors.
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz
Author: rstacruz
Source Code: https://github.com/rstacruz/nprogress
License: MIT license
1660819145
Next.js — это серверная среда с упором на производительность. Он также является одним из наиболее широко используемых фреймворков JavaScript (после React) во всем мире. Затем Next.js выполняет рендеринг на стороне сервера для приложений React.
Иногда переход с одного маршрута на другой требует немного дополнительного времени по разным причинам. Это может быть запрос API или отрисовка сложного компонента страницы в фоновом режиме. Когда это происходит, приложение ненадолго перестает отвечать на запросы, а затем резко переключается на следующий маршрут. Например, на изображении ниже показано, как клиент переключается с одной страницы на другую.
Без индикатора загрузки пользователь может решить, что ничего не произошло или что страница работает со сбоями, даже если все, что происходит, — это просто получение содержимого страницы. Если вы внимательно посмотрите, то заметите это. Это может сильно запутать пользователей и плохо повлиять на веб-сайт и взаимодействие пользователя с таким приложением.
Решение этой проблемы состоит в том, чтобы показывать верхний индикатор выполнения на веб-сайте Next.js до тех пор, пока данные с сервера не будут загружены на веб-сайт, то есть индикатор выполнения создает у пользователя впечатление, что страница загружается, а также как далеко зашла страница с точки зрения полной загрузки. Возьмем, к примеру, эту страницу ниже, на которой есть индикатор выполнения.
Давайте посмотрим, как мы можем создать этот хороший индикатор выполнения для нашего приложения Next.js.
Индикаторы Progress Bar могут быть определенными или неопределенными:
Индикатор является детерминированным, когда он указывает, сколько времени займет операция, когда можно определить процент завершения.
Индикатор является неопределенным, когда он требует, чтобы пользователь подождал, пока что-то завершится, когда нет необходимости указывать, сколько времени это займет.
В индикаторе прогресс-бара общего назначения есть много функций, которые нужно охватить, чтобы создать удобный для пользователя индикатор прогресс-бара.
Давайте быстро перейдем к нашему терминалу и выполним следующую команду, чтобы создать проект Next.js.
npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app
Вам будет предложено дать имя вашему проекту.
Сначала я создаю новый файл в папке страниц. Это даст вам новый маршрут. Мы дадим ему имя about.js
: просто h1
тег и a button
, который ведет на домашнюю страницу.
//about.js//
import Link from 'next/link'
function about() {
return (
<div><><h1>Next.Js Progress Bar Indicator</h1><ul>
<div className='flex'>
<Link href="/">
<a>Home</a>
</Link>
<Link href="/about">
<a>About Us</a>
</Link>
<Link href="/blog">
<a>Blog Post</a>
</Link>
<Link href="/contact">
<a>Contact Us</a>
</Link>
</div>
<h3>About Us</h3>
</ul></></div>
)
}
export default about
Мы также создадим другие файлы, чтобы сделать наше приложение гибким. Мы создадим файлы blog post
и contact us
направим/свяжем их обратно с home
файлом.
nprogress
это пакет, который предлагает движущийся индикатор выполнения. Установите его с помощью одной из команд ниже.
npm i nprogress
# or
yarn add nprogress
После того, как начнется навигация на стороне клиента, nprogress
анимация запустится автоматически и остановится, когда навигация будет завершена. Мы можем использовать встроенные Router
события в Next.js, чтобы связать их, и мы свяжем события в уникальном компоненте, чтобы сохранить порядок в коде.
// _app.js
import Router from 'next/router';
import NProgress from 'nprogress'; //nprogress module
import 'nprogress/nprogress.css'; //styles of nprogress
//Route Events.
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp;
Мы гарантируем, что обработчик событий привязывается за пределами компонентов, чтобы избежать привязки нескольких обработчиков. Кроме того, счетчик загрузки, который используется по умолчанию, может быть удален в зависимости от нашего варианта использования.
NProgress.configure({ showSpinner: false })
Код завершен. Давайте посмотрим, как будет выглядеть наш индикатор выполнения с нашим приложением Next.js.
Вы можете добавить параметры изменения, nProgress
такие как цвет, высота, ключ, ссылка, startPosition и многое другое. В основном я просто меняю цвет и высоту, потому что мне нравятся другие стили такими, какие они есть. Вот как вы можете изменить цвет и высоту.
По умолчанию nprogress показывает синий индикатор выполнения в верхней части страницы. Это может не соответствовать внешнему виду веб-сайта. Чтобы настроить:
Nprogress.css
в каталоге стилей.--primary-color: #29d
на любой цвет, который вы хотите/* Make clicks pass-through */
#nprogress {
--primary-color: #ff0000; //changing mine to red
pointer-events: none;
}
#nprogress .bar {
background: var(--primary-color);
position: fixed;
z-index: 1031;
top: 0;
left: 0;
width: 100%;
height: 10px; //Also increasing my bar size to 10px just for illustration purpose
}
/* Fancy blur effect */
#nprogress .peg {
display: block;
position: absolute;
right: 0px;
width: 100px;
height: 100%;
box-shadow: 0 0 10px var(--primary-color), 0 0 5px var(--primary-color);
opacity: 1.0;
-webkit-transform: rotate(3deg) translate(0px, -4px);
-ms-transform: rotate(3deg) translate(0px, -4px);
transform: rotate(3deg) translate(0px, -4px);
}
/* Remove these to get rid of the spinner */
#nprogress .spinner {
display: block;
position: fixed;
z-index: 1031;
top: 15px;
right: 15px;
}
#nprogress .spinner-icon {
width: 18px;
height: 18px;
box-sizing: border-box;
border: solid 2px transparent;
border-top-color: var(--primary-color);
border-left-color: var(--primary-color);
border-radius: 50%;
-webkit-animation: nprogress-spinner 400ms linear infinite;
animation: nprogress-spinner 400ms linear infinite;
}
.nprogress-custom-parent {
overflow: hidden;
position: relative;
}
.nprogress-custom-parent #nprogress .spinner,
.nprogress-custom-parent #nprogress .bar {
position: absolute;
}
@-webkit-keyframes nprogress-spinner {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes nprogress-spinner {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
*import*
«../styles/Nprogress.css»Индикаторы Progress Bar в основном используются онлайн-приложениями. Например, интернет-магазины используют их для повышения конверсии; индикаторы прогресса заставляют пользователей пройти необходимые процедуры, необходимые для завершения покупки.
Ссылка: https://blog.openreplay.com/how-to-build-a-progress-bar-indicator-for-next-js
#nextjs #react