Permanent 301 Redirect with PHP

On 4/17/2017 Be the first to comment!

Hey! In today's post let's see how to do permanent 301 redirect with php. Redirection is a very common practice in websites and can be done at page or domain level. There are two types of redirect, one is temporary and other is permanent. The temporary redirect sends 302 http code with headers and indicates browsers and search engines that the page is moved temporarily. And permanent redirection sends 301 code and tells browsers and search engines that the page is moved permanently to different location.

You can do page redirects via htaccess file or within code. PHP has this header() function which lets you redirect users from one page to another. No doubt most of you have used it countless times. But do you know the redirect you do is just temporary? Because unless stated explicitly the headers are sent for 302 redirect. So let's see how to perform 301 redirect in php here.

301 redirect in php

Permanent 301 Redirect with PHP:

Sometimes you might have moved a resource to another place and want to redirect the page permanently. It's also good for SEO and 301 redirect will pass link juice to the new url.

Also Read:

In php you have to redirect to another url like this,

header("Location: example/page.php");

Just pass the destination page to header() and it will attach 302 code and do temporary redirect. But you can also make the function to perform 301. For that you must state the response code with headers like this.

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://example.com/sample/page/");
?>

The above code will redirect users to the new url attaching a 301 http response code to headers. That's instructs browsers and bots to take it as permanent redirect. (Learn how to get http status code from Headers in PHP.)

If you think two lines of code is too much then refine it into a single line like this.

<?php header("Location: http://example.com/sample/page/", true, 301); ?>

The above line will permanently redirects to the provided page.

Most of us use only one param with in header() but the function takes up to three parameters.

  • First parameter is obviously the page location.
  • Second param is a boolean value and is useful if you send multiple headers of same type. True will replace same type header and False will force to send multiple headers of similar type.
  • Third param is the 'http_response_code' and attach the headers with redirection code.

Permanent 301 Redirect via HTACCESS:

Redirecting page via htaccess is even easier and practiced by so many webmasters. To redirect a page permanently add this line to the htaccess file in server.

redirect 301 /old-file.php /new-file.php

The above code will permanently redirect old-file.php to new-file.php with in the same domain.

If you have to redirect a file to another domain then specify the entire url.
redirect 301 /old-file.php http://another-domain.com/another-file.php

Likewise you can perform permanent 301 redirect in php. Make sure to place headers before actual output starts in php file. Else you will get error. I hope you find this useful. Meet you in next tutorial:D

Add/Remove Key Value Pairs (Attributes) from JSON Data using JavaScript

On 4/10/2017 Be the first to comment!

Hi! Let's see how to add and remove key value pairs from json data using javascript. JSON is the string representation of java script object and cross-platform compatible. Using AJAX you can communicate with numerous web services and grab API data in JSON format. Considering the increased popularity of API's, it goes without saying that the ability to read, process and manipulate JSON is a must have skill for developers. In JSON, data is stored as key - value pairs and wrapped within quotes since it's a string. Sometimes the key-value pairs are also referred to as attributes, items or elements. Here I'm going to show you how to append or remove key value pairs from existing json data.

add remove key value pair from json javascript

JSON Attributes - Key Value Pairs:

JSON attributes are represented as key value pairs something similar to associative arrays. The key-value pairs look something like this,

{ "name": "Barbie" }

Here "name" is the key and "Barbie" is the value of that key.

Also Read:

Plus JSON comes in all sorts of representation - simple, nested or arrays. The simple format contains a set of attributes like this.

{
    "fruit": "apple",
    "color": "red"
}

And as for array of items it will look like this,

[
    {
        "name": "Fredie",
        "department": "Finance"
    },
    {
        "name": "Rolland",
        "department": "Sales"
    },
    {
        "name": "Gina",
        "department": "Customer Service"
    }
]

At times json data can be complicated with nested attributes.

{
    "empid": "ABC001X",
    "personal": {
        "name": "Paula Thompson",
        "gender": "Female",
        "age": "34",
        "address": {
            "streetaddress": "12 117th Street",
            "city": "New York",
            "state": "NY",
            "zipcode": "10038"
        }
    },
    "official": {
        "designation": "Vice President",
        "department": "Operations"
    }
}

However it is you can manipulate json easily with native java script. The same can be handled with jquery but unless necessary just the plain old javascript will do. By this way you can reduce server load.

Add Key Value Pair to JSON with JavaScript:

Adding key value pair to json will append the new attribute to the end of the json string. Following is the simplest way to add attributes to existing json data.

var data = {
    "id": "XYZ123",
    "name": "Greg",
    "gender": "Male"
};

data.country = "United States";
console.log(JSON.stringify(data));

// Produce Output
{
    "id":"XYZ123",
    "name":"Greg",
    "gender":"Male",
    "country":"United States"
}

If json has array of items, then you can add key value pairs to each subset like this,

var data = [
    {
        "name": "John Smith",
        "age": "45"
    },
    {
        "name": "Peter Jason",
        "age": "26"
    },
    {
        "name": "Alice Ray",
        "age": "34"
    }
];

for (var i=0; i<data.length; i++) {
    data[i].department = "Administration";
    data[i].company = "ABC Corp";
}
console.log(JSON.stringify(data));

// Produce Output
var data = [
    {
        "name":"John Smith",
        "age":"45",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Peter Jason",
        "age":"26",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Alice Ray",
        "age":"34",
        "department":"Administration",
        "company":"ABC Corp"
    }
];

You have to loop through the array of items and add attributes to each one of it.

Remove Key Value Pair from JSON:

Let's say you have the following JSON data,

var data = {
    "id":"XYZ123",
    "name":"Greg",
    "gender":"Male",
    "country":"United States"
};

In order to remove an attribute from json you have to use JS delete method. This will delete the json attribute with the specific key.

delete data.gender;
console.log(JSON.stringify(data));

// Produce Output
{
    "id":"XYZ123",
    "name":"Greg",
    "country":"United States"
}

Likewise you can remove the occurrence of particular attribute from json array.

var data = [
    {
        "name":"John Smith",
        "age":"45",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Peter Jason",
        "age":"26",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Alice Ray",
        "age":"34",
        "department":"Administration",
        "company":"ABC Corp"
    }
];

for (var i=0; i<data.length; i++) {
    delete data[i].age;
}
console.log(JSON.stringify(data));

// Produce Output
[
    {
        "name":"John Smith",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Peter Jason",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Alice Ray",
        "department":"Administration",
        "company":"ABC Corp"
    }
]

That explains about add and remove key value pairs in json using javascript. Please note that the json you use should be of valid one for the above methods to work. I hope you find this tutorial useful. Meet you in another interesting one.

Import CSV File into MySQL Database using PHP Script

On 4/04/2017 16 Comments so far

Hi, this time I have come up with another useful php script, which will show you How to Import CSV File Data into MySQL Database using PHP. CSV Files commonly known as comma separated values is one of the most preferred data storage methods. And as a developer often you might find you in situation to import those huge csv data into database system. Though sounding simple, it’s a nightmare in disguise. Here’s where php comes to the rescue. With few lines of code, you can insert several hundreds of records in flash.

PHP supports several data formats like csv, json etc. and provides dedicated functions to handle such data formats. Hence without any third party solutions, we can to parse and store csv records in database using core php alone.

php script import csv into mysql database
Read Also

Create Sample MySQL Database

As an example, let’s use our previous ‘library’ database for this tutorial. Just create a new database with name ‘library’ in mysql. Next you should create a table ‘books’ to store the details of the books in the library. For that run the below sql command.

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `library`
--
-- Table structure for table `books`
--
CREATE TABLE IF NOT EXISTS `books` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `author` varchar(30) NOT NULL,
  `isbn` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Sample CSV File

Below is the sample csv file containing the books data and we’ll import this csv file to the ‘books’ table.

books.csv
Learning PHP MySQL & JavaScript,Robin Nixon,ISBN-13: 978-1491918661
PHP and MySQL for Dynamic Web Sites,Larry Ullman,ISBN-13: 978-0321784070
PHP Cookbook,David Sklar,ISBN-13: 978-1449363758
Programming PHP,Kevin Tatroe,ISBN-13: 978-1449392772
Modern PHP New Features and Good Practices,Josh Lockhart,ISBN-13: 978-1491905012

Now it’s time to move on to the php script part.

PHP Script to Import CSV File Data into MySQL Database

The CSV import process goes like this. With PHP open the '.csv' file, parse through it one line at a time and insert into mysql db. Following is the step by step procedure for doing so.

Step-1: Set the Database Connection Variables

First let’s set the database connection variables and the right csv file path to import.

<?php
//set the connection variables
$hostname = "localhost";
$username = "username";
$password = "password";
$database = "library";
$filename = "books.csv";
?>

Step-2: Establish the MySQL Database Connection

Next we open the connection to mysql database using mysqli library.

<?php
//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));
?>

Step-3: Open and Parse the CSV File

Now we should open the csv file in ‘reading’ mode and parse the record one at a time and insert into mysql table ‘books’.

<?php
// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
    //insert csv data into mysql table
    $sql = "INSERT INTO tbl_books (name, author, isbn) VALUES('" . implode("','",$row) . "')";
    if(!mysqli_query($connection, $sql))
    {
        die('Error : ' . mysqli_error());
    }
}

fclose($fp);
?>

The line $fp = fopen($filename,"r"); will open the ‘books.csv’ file for reading and return the file handler to the $fp variable.

Next we loop through the entire file one record at a time. Using the line $row = fgetcsv($fp,"500",",") will fetch the complete row of the csv file one at a time, and "500" specifies the maximum length of the rows in the csv file and "," specifies the delimiter.

Finally we implode the fetched row and save it into mysql database using the INSERT query.

The line fclose($fp); closes the file handler after completely parsing through the entire file.

Step-4: Close the MySQL Database Connection

After inserting all the csv records into mysql, we finally close the database connection we established first.

<?php
//close the db connection
mysqli_close($connection);
?>

Here is the Complete PHP Script to Import CSV File into MySQL Database.

<?php
//set the connection variables
$hostname = "localhost";
$username = "username";
$password = "password";
$database = "library";
$filename = "books.csv";

//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));

// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
    //insert csv data into mysql table
    $sql = "INSERT INTO tbl_books (name, author, isbn) VALUES('" . implode("','",$row) . "')";
    if(!mysqli_query($connection, $sql))
    {
        die('Error : ' . mysqli_error());
    }
}

fclose($fp);

//close the db connection
mysqli_close($connection);
?>

Now go back to mysql and check the library database after running the php snippet. You will find the csv file records inserted into the ‘books’ table.

And that was all about importing csv file into mysql database using php. There's also the reverse process of exporting mysql database to csv file with php. You can check it out.

Integrate reCAPTCHA in Codeigniter Tutorial

On 3/27/2017 Be the first to comment!

Hi! Let's see How to integrate reCAPTCHA in Codeigniter Application. This will help protect your codeigniter websites from spam and bots. Google reCAPTCHA effectively blocks out bot access but the old recaptcha is not very user-friendly. It requires you to fill out a textbox with the characters you see on an image. Not to mention the captcha text is difficult to read even for humans. Later a new version of reCAPTCHA named 'I'm not a robot' has been released by Google. It is meant to be gentle on humans and hard on bots.

In this new recaptcha all you have to do is to tick a checkbox and be done. In fact it's much more effective in controlling spam and improves user-experience without compromise.

Also Read:

How to Integrate reCAPTCHA in CodeIgniter?

In order to integrate Google reCAPTCHA in your Codeigniter application, you have to first register the specific site with Google. After registration you will be provided with two keys namely Site & Secret key.

The 'Site Key' should be used for displaying recaptcha widget on your site and 'Secret Key' for captcha verification.

register website with recaptcha

For testing purpose Google let you to run recaptcha from localhost. I'll show you how to do this.

  1. Visit here and register the codeigniter site you wish to integrate recaptcha.
  2. You have to enter 'Label' and 'Domains' details in the registration form.
  3. Label is just for your understanding so you can simply provide site name here.
  4. In 'Domains' box enter the domain name. To test recaptcha from local machine enter 'localhost'.

Click on 'Register' and you will be provided with a set of keys. Save the keys in a text file. You will need them for implementing captcha code.

Adding reCAPTCHA to Form:

For using recaptcha in a form load the api library first.

<script src='https://www.google.com/recaptcha/api.js'></script>

Then add this snippet to display recaptcha widget wherever you want.

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

For better understanding let us create user feedback form in codeigniter and add recaptcha to it. You need a controller and view file for this.

The View ('recaptcha_demo_view.php'):

The view file contains a feedback form with recaptcha verification. The form will be processed only when user verifies captcha.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Recaptcha Demo</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <div class="container" style="margin-top: 20px;">
        <div class="col-xs-6 col-xs-offset-3 well" style="background:none;">
        <?php echo form_open("recaptcha_demo/index"); ?>
            <div class="form-group">
                <textarea name="feedback" placeholder="Your feedback..." class="form-control" rows="4"><?php echo set_value('feedback'); ?></textarea>
                <span class="text-danger"><?php echo form_error('feedback'); ?></span>
            </div>
            <div class="form-group">
                <div class="g-recaptcha" data-sitekey="your-site-key"></div>
                <span class="text-danger"><?php echo form_error('g-recaptcha-response'); ?></span>
            </div>
            <div class="form-group">
                <button type="submit" name="submit" class="btn btn-lg btn-danger">Send Feedback</button>
            </div>
        <?php echo form_close(); ?>
        <?php echo $this->session->flashdata('msg'); ?>
        </div>
    </div>
</body>
</html>

The Controller ('recaptcha_demo.php')

In controller we have an index() function to which the form is submitted and a custom callback to verify captcha input.

<?php
class recaptcha_demo extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('session', 'form_validation'));
    }
    
    function index()
    {
        $this->form_validation->set_rules('feedback', 'Feedback', 'required');
        $this->form_validation->set_rules('g-recaptcha-response', 'g-recaptcha-response', 'callback_captcha_validation');

        if ($this->form_validation->run() == FALSE)
        {
        
            $this->load->view('recaptcha_demo_view');
        }
        else
        {
            $this->session->set_flashdata('msg','<div class="alert alert-success text-center">Thanks for your Feedback! We got it!!!</div>');
            redirect('recaptcha_demo/index');
        }
    }
    
    function captcha_validation()
    {
        $secret_key = 'your-secret-key'; // change this to yours
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret_key . '&response='.$_POST['g-recaptcha-response'];
        $response = @file_get_contents($url);
        $data = json_decode($response, true);
        if($data['success'])
        {
            return true;
        }
        else
        {
            $this->form_validation->set_message('captcha_validation', 'Please confirm you are human');
            return false;
        }
    }
}

Done! Now run the file and you will see a nice user feedback form with recaptcha at the bottom.

integrate recaptcha in codeigniter

Fill-in your feedback, tick the recaptcha checkbox and click Send Feedback.

codeigniter recaptcha tutorial

If form validation goes right you will be shown with a success message like this.

how to use recaptcha in codeigniter

On the other hand if you don't confirm captcha and submit the form, you will be asked to confirm captcha like this.

codeigniter recaptcha form validation

You can also implement recaptcha in php form, just check the tutorial.

Also Read:

That's it! You have successfully integrated Google reCAPTCHA in CodeIgniter. Implement recaptcha in codeigniter applications you build and stop spammers bombarding your site. Please make sure to use site & secret key with yours for this to work. If you have any trouble using this code please let me know in comments section.

How to Disable Click Event in jQuery (Enable/Disable Button Click)

On 3/20/2017 Be the first to comment!

Hi! Let's see how to disable click event in jquery here. As a web developer you might have faced the problem of users submitting forms more than once especially ajax forms. Due to slow internet connection or hundred other reasons there is a lot of chance for users to click submit buttons again and again in a web form. To overcome this you can simply restrict users to click button more than once with the help of jquery. You can do this in two ways. One, you can disable the button which makes it to grey out and not respond to clicks. Or you can simply unbind click event from button. With this the button won't be disabled but just the click event alone. Here I'm going to show you how to disable click event for button.

jquery disable click event after click
Read Also:

How to Disable Click Event in jQuery?

Just like disabling click event you can enable it at any time with jquery. For that we need jquery's on() and off() methods and they are used to attach and remove event handlers from an element. The methods not only work for buttons but for other html elements too.

  • On() is used to attach event handlers to html elements
  • Off() is used to remove event handlers from html elements

First let's add a checkbox and button to html page. When the checkbox is ticked, button click event should be disabled and enabled when unchecked.

<input type="checkbox" id="chkbox" />Disable Click
<button id="submit">Click Me</button>

jQuery Script:

Let's write separate handler function for button click event so that you can use it in as many places as you want.

function clickButton() {
    alert('Button clicked!');
}

Next the event handler for button clicks.

$('#submit').on('click', clickButton);

Then disable the click event when checkbox is ticked.

$('document').ready(function() {
    $('#chkbox').on('change', function(){
        if($(this).prop('checked'))
            $('#submit').off('click');
        else
            $('#submit').on('click', clickButton);
    });
});

That will take care of enabling/disabling click event for button.

Complete Script:

<!DOCTYPE html>
<html>
    <head>
        <title>Enable and Disable Click Event in jQuery</title>
    </head>
    <body>
        <input type="checkbox" id="chkbox" />Disable Click
        <button id="submit">Click Me</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
        <script type="text/javascript">
        $('document').ready(function() {
            $('#chkbox').on('change', function(){
                if($(this).prop('checked'))
                    $('#submit').off('click');
                else
                    $('#submit').on('click', clickButton);
            });
            
            $('#submit').on('click', clickButton);
            
            function clickButton() {
                alert('Button clicked!');
            }
        });
        </script>
    </body>
</html>
Read Also:

That explains about how to enable and disable click event in jquery. I hope you find this jquery snippet useful. Meet you in another interesting tutorial.

Add Remove Textbox Dynamically using jQuery, PHP & Bootstrap

On 3/14/2017 1 Comment so far

Hi! In today's post let's see how to add remove textbox dynamically using jquery, php and bootstrap css. Letting users to dynamically add/remove form fields on fly and submitting form will give users a certain level of control over their input. The process is pretty straight forward and with little jquery script you can implement this dynamic feature in any php form or html form. The idea here is to create a textbox attached with a '+' (Plus) button/sign at the end. When user clicks on '+' button additional textboxes will be added to the form and the dynamically added textboxes will come attached with '-' sign/button to them. If user wants to remove a textbox then they have to click on '-' button and the specific textbox will be deleted on fly.

I have used bootstrap for designing form elements here but it's optional. You are free to go without it and the jquery script will work for non-bootstrap form too (of course with some minor tweaks).

dynamically add remove textbox using jquery php bootstrap
Also Read:

How to Add/Remove Textbox Dynamically using jQuery & PHP?

First you need to add a single textbox and a plus button probably within a form. And make the textbox input as array so that users can duplicate it on fly.

HTML Markup:

<div class="textbox-wrapper">
    <div class="input-group">
        <input type="text" name="text_arr[]" class="form-control" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-success add-textbox"><i class="glyphicon glyphicon-plus"></i></button>
        </span>
    </div>
</div>

Next you need to add jquery function to create duplicate textbox dynamically when user clicks on the Plus button.

jQuery Script:

$(document).ready(function() {
    var max = 10;
    var cnt = 1;
    $(".add-textbox").on("click", function(e){
        e.preventDefault();
        if(cnt < max){
            cnt++;
            $(".textbox-wrapper").append('<div class="input-group"><input type="text" name="text_arr[]" class="form-control" /><span class="input-group-btn"><button type="button" class="btn btn-danger remove-textbox"><i class="glyphicon glyphicon-minus"></i></button></span></div>');
        }
    });
});

The above function will limit the maximum number of text fields users can add to the form at any time. When it reaches the maximum the script will restrict users from adding any more textboxes.

Next is the textbox removal part. The following function will remove textbox from the form when user clicks on the Minus button.

$(".textbox-wrapper").on("click",".remove-textbox", function(e){
    e.preventDefault();
    $(this).parents(".input-group").remove();
    cnt--;
});

Done! Now we have both html and jquery code in place. Run the script and you will get a form with single textbox and a '+' button attached to it.

add remove input fields dynamically jquery php

Clicking on the plus button will add more textboxes on fly.

add textbox dynamically jquery php

On the other hand click on a minus button and the textbox will get removed from the form.

remove input field dynamically jquery php

Complete Script:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Remove Textbox Dynamically using jQuery, PHP & Bootstrap</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style type="text/css">
    .input-group {
        margin-top: 10px;
        margin-bottom: 10px;
    }
    </style>
</head>
<body>
    <div class="container" style="margin-top: 30px;">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="panel panel-success">
            <div class="panel-body">
                <form name="demo-form" method="post">
                <div class="textbox-wrapper">
                    <div class="input-group">
                        <input type="text" name="text_arr[]" class="form-control" />
                        <span class="input-group-btn">
                            <button type="button" class="btn btn-success add-textbox"><i class="glyphicon glyphicon-plus"></i></button>
                        </span>
                    </div>
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="Submit Form" class="btn btn-lg btn-block btn-success"/>
                </div>
                </form>
            </div>
        </div>
    </div>
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        var max = 10;
        var cnt = 1;
        $(".add-textbox").on("click", function(e){
            e.preventDefault();
            if(cnt < max){
                cnt++;
                $(".textbox-wrapper").append('<div class="input-group"><input type="text" name="text_arr[]" class="form-control" /><span class="input-group-btn"><button type="button" class="btn btn-danger remove-textbox"><i class="glyphicon glyphicon-minus"></i></button></span></div>');
            }
        });
       
        $(".textbox-wrapper").on("click",".remove-textbox", function(e){
            e.preventDefault();
            $(this).parents(".input-group").remove();
            cnt--;
        });
    });
    </script>
</body>
</html>

Handling POST Data in PHP:

Like I said before, the textbox field is an array. When user submits the form you can access the post data like this in php.

<?php
$myarray = $_POST['text_arr'];
foreach($myarray as $val){
    ...
    ...
}
?>
Also Read:

Likewise you can add or remove textbox dynamically using jquery and bootstrap. The same script will work for other input fields too. Just replace textbox with any other form inputs and the rest would be the same. I hope you like this script. Please don't forget to share it in your social circle.

Back To Top Button using HTML CSS and jQuery

On 3/08/2017 Be the first to comment!

Hi! Let's see how to implement back to top button using html, css and jquery. Good user experience means a lot for websites. If it fails, people will leave your site no matter how good and informative it is. Accessibility is the best way to ensure good user-experience. If people find a website easy to navigate through then they visit more pages and stay longer on the site.

Now a day's several websites uses infinite scroll technique and shows so much of content in a single page itself. Imagine how annoying it would be if user has to scroll back to the top of the page after going all the way down to read through long contents. In such case having a back-to-top button will help users to scroll back to the top of the page with just a single mouse click. And I'm going to show you how to add this back to top button with just css and jquery alone.

HTML Back To Top Button CSS jQuery
Also Read:

Implementing Back To Top Button using HTML, CSS & jQuery:

Even though we call it as a button, this Back to top button is a link that lets users to smoothly scroll back to the top of the page when clicked. It enhances user experience on long page websites. As for creating button, I'm going with pure css but you are free to use images in case you want a fancy one.

Come let's see how to implement back to top button on websites.

Step 1) Create Back To Top Button with HTML

First you need to create back to top button. This is the html markup for adding button to a web page.

<a href="#" class="back-to-top" title="Back To Top">&uarr;</a>

Step 2) Style Button with CSS

Next you need to add some styles to make sure the link look like an actual button. The following css will create a circle button with up arrow in it. And also position it at the bottom right corner of the page.

body {
    height: 5000px;
}

.back-to-top {
    position: fixed;
    bottom: 40px;
    right: 40px;
    color: #FFF;
    background: #41CAD4;
    line-height: 30px;
    text-align: center;
    text-decoration: none;
    width: 32px;
    height: 32px;
    border: 0;
    border-radius: 50%;
    display: none;
    cursor: pointer;
    z-index: 9999;
}

.back-to-top:hover {
    background: #2DB6C0;
}

Step 3) Scroll Back to Top with jQuery

Finally you need to add some jquery script for the button to work.

In the second step, we have positioned the button at the bottom-right corner of the page, but it will be kept hidden until user starts scrolling. The back-to-top button will only appear when the page is scrolled down a little. For that you need to add scroll event to the page and display the button when it cross over 100 pixels mark.

$(document).ready(function(){ 
    $(window).on('scroll', function() {
        if ($(this).scrollTop() > 100) {
            $('.back-to-top').fadeIn();
        } else {
            $('.back-to-top').fadeOut();
        }
    });
});

Then you have to ensure the page smoothly scrolls back to top of the window on button click. For that you have to use animate() function on button click event.

$('.back-to-top').on('click', function(e) {
    e.preventDefault();
    $('html,body').animate({scrollTop: 0}, 600);
});

Done! Now you have everything in place. Run the script and scroll down the page a little. Now a small round button will appear at the bottom right corner of the page and stay there as long as you go down. Click on the button at any time and it will take you back to the top of the page. Once you are at the top, the button will disappear.

Complete Script:

<!DOCTYPE html>
<html>
    <head>
        <title>Scroll Back To Top using HTML, CSS and jQuery</title>
        <style type="text/css">
        body {
            height: 5000px;
        }
        
        .back-to-top {
            position: fixed;
            bottom: 40px;
            right: 40px;
            color: #FFF;
            background: #41CAD4;
            line-height: 30px;
            text-align: center;
            text-decoration: none;
            width: 32px;
            height: 32px;
            border: 0;
            border-radius: 50%;
            display: none;
            cursor: pointer;
            z-index: 9999;
        }
        
        .back-to-top:hover {
            background: #2DB6C0;
        }
        </style>
    </head>
    <body>
        <!-- page content goes here -->
        <a href="#" class="back-to-top" title="Back To Top">&uarr;</a>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){ 
            $(window).on('scroll', function() {
                if ($(this).scrollTop() > 100) {
                    $('.back-to-top').fadeIn();
                } else {
                    $('.back-to-top').fadeOut();
                }
            });
            
            $('.back-to-top').on('click', function(e) {
                e.preventDefault();
                $('html,body').animate({scrollTop: 0}, 600);
            });
        });
        </script>
    </body>
</html>
Also Read:

Likewise you can create back to top button with html, css and jquery. As for this demo, I haven't added any content to the page, so I have set some height to the body section of the page. The step is not required while implementing it on actual website. I hope you find this script useful and don't forget to share it in social media.

Contact Form

Name

Email *

Message *