Category

Category: jQuery

PhotoSwipe – Loading slider to a container

An example code for dsiplaying PhotoSwipe slider inside a container rather than full screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/default-skin/default-skin.min.css">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>
    </head>
    <body>
        <div class="my-images" style="display: none;"> 
            <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" height="100" />
            <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" height="100" />
        </div>
   

        <div style="width: 300px; height: 400px; position: relative;">
            <!-- Root element of PhotoSwipe. Must have class pswp. -->
            <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

                <!-- Background of PhotoSwipe.
                    It's a separate element, as animating opacity is faster than rgba(). -->
                <div class="pswp__bg"></div>

                <!-- Slides wrapper with overflow:hidden. -->
                <div class="pswp__scroll-wrap">

                    <!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
                    <div class="pswp__container">
                        <!-- don't modify these 3 pswp__item elements, data is added later on -->
                        <div class="pswp__item"></div>
                        <div class="pswp__item"></div>
                        <div class="pswp__item"></div>
                    </div>

                    <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
                    <div class="pswp__ui pswp__ui--hidden">

                        <div class="pswp__top-bar">

                            <!--  Controls are self-explanatory. Order can be changed. -->

                            <div class="pswp__counter"></div>
                            <!--
                            <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                            <button class="pswp__button pswp__button--share" title="Share"></button>-->

                            <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                            <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                            <!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR -->
                            <!-- element will get class pswp__preloader--active when preloader is running -->
                            <div class="pswp__preloader">
                                <div class="pswp__preloader__icn">
                                <div class="pswp__preloader__cut">
                                    <div class="pswp__preloader__donut"></div>
                                </div>
                                </div>
                            </div>
                        </div>

                        <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                            <div class="pswp__share-tooltip"></div>
                        </div>

                        <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
                        </button>

                        <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
                        </button>

                        <div class="pswp__caption">
                            <div class="pswp__caption__center"></div>
                        </div>

                    </div>

                    </div>

            </div>
        </div>
        <script>

        function openPhotoSwipe(items) {
            var pswpElement = document.querySelectorAll('.pswp')[0];
           
            // define options (if needed)
            var options = {
                    // history & focus options are disabled on CodePen        
                history: false,
                focus: false,
                modal: false,

                showAnimationDuration: 0,
                hideAnimationDuration: 0,
                closeElClasses: ['caption', 'zoom-wrap', 'ui', 'top-bar'],
               
            };
           
            var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);

            gallery.listen('gettingData', (index, item) => {
                if (!item.w || !item.h) {
                    console.log(item);
                   
                    const img = new Image()
                    img.onload = function () {
                        item.w = this.width
                        item.h = this.height
                        gallery.updateSize(true)
                    }
                    img.src = item.src
                }
            });

            gallery.init();
        };

        $(document).ready(function(){
           
            var my_images = $('.my-images img');
            var my_images_object = [];
            if(my_images.length){
                $(my_images).each(function(){
                    my_images_object.push({
                        src: $(this).attr('src'),
                        w: 0,
                        h: 0
                    });
                });
            }
           
            openPhotoSwipe(my_images_object);
        });
       
        </script>
    </body>
</html>

Add Plugins to CKEditor CDN

Here’s a basic implementation of CKEditor CDN:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>CKEditor</title>
		<script src="https://cdn.ckeditor.com/4.9.2/standard/ckeditor.js"></script>
	</head>
	<body>
		<textarea name="editor1"></textarea>
		<script>
			CKEDITOR.replace( 'editor1' );
		</script>
	</body>
</html>

And for example we want to add the plugin “Youtube”, first download the plugin from here: https://ckeditor.com/cke4/addon/youtube then extract the contents to a directory that is easy to find, for example: MY_PROJECT/ckeditor/plugins/youtube/

Then we link the Youtube plugin into our CKEditor instance:

CKEDITOR.plugins.addExternal('youtube', '/ckeditor/plugins/youtube/plugin.js');
CKEDITOR.replace( 'editor1', {
	extraPlugins: 'youtube',
} );

If you need to add multiple plugins, you can do it like this:

extraPlugins: 'youtube,plugin_1,plugin_2,plugin_3'

CKEditor – Detect when typing stopped

I was trying to figure out a way to detect when the user typing in the editor has paused / stopped. The documentation of CKEditor and Stackoverflow do not have my answer, fortunately I was able to come up with a simple solution!

I first started with the basics – I played with a simple <textarea />  without CKEditor and the code bellow worked for me:

Type in the text box. it will time out and run the function when you stop for the time alotted.
<textarea id="editor"></textarea>
var timer = null;
$('#editor').keydown(function(){
       clearTimeout(timer); 
       timer = setTimeout(doStuff, 1000)
});

function doStuff() {
    alert('do stuff');
}

And next –  I applied the code above to a CKEditor instance.

CKEditor doesn’t have keyup  or keydown  events, but what they have is key

So I did the following using closures and it worked for me!

var timer = null;
CKEDITOR.instances['#editor'].on('key', function(){ 
	clearTimeout(timer); 
	timer = setTimeout(doStuff.bind(textarea, $('#editor')), 1000)
});

function doStuff(textarea) {
    alert(textarea.val());
}

How to make your Tables Responsive

Recently I was working on an HTML table with a lot of columns, I thought “How is this going to look on my mobile phone?”. So then I searched for “responsive tables” and found Stackable.JS. The purpose of Stackable.JS is to give you an easy way of converting wide tables to a format that will work better on small screens. It creates a copy of the table that is converted into a 2-column key/value format.

Demo


How does it work?

On the demo, I used the cardtable method. Card table breaks each row into its own table. The row tables function like cards. Any content left in tfoot is also broken into its own card, this allows for things like view all links or pagination to be easily used.

Original:

stackable-js-demo-full-width

When screen hits 768px and bellow:

stackable-js-demo-stacked-at-768px

The Code

Simply copy the entire code to a html file then run it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
    .stacktable { width: 100%; }
    .stacktable tr td, .stacktable tr th { border: 1px solid #dfdfdf; padding: 10px; }
    .st-head-row { padding-top: 1em; }
    .st-head-row.st-head-row-main { font-size: 1.5em; padding-top: 0; }
    .st-key { width: 49%; text-align: right; padding-right: 1%; font-weight: bold; }
    .st-val { width: 49%; padding-left: 1%; }
   
    .stacktable.large-only { display: table; }
    .stacktable.small-only { display: none; }

    @media (max-width: 768px) {
        .stacktable.large-only { display: none; }
        .stacktable.small-only { display: table; }
    }
    </style>
</head>
<body>
    <table id="make-responsive" class="table" width = "100%">
        <thead>
            <tr>
                <th width="30%">Name</th>
                <th width="30%">Phone</th>
                <th width="30%">Description</th>
                <th width="10%">Actions</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Carlo Fontanos</td>
                <td>514-343-2265</td>
                <td>Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium</td>
                <td><a href="#">Edit</a></td>
            </tr>
            <tr>
                <td>Brad Jaymond</td>
                <td>658-341-112</td>
                <td>Lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram</td>
                <td><a href="#">Edit</a></td>
            </tr>
            <tr>
                <td>John Garcia</td>
                <td>652-755-2322</td>
                <td>Anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima</td>
                <td><a href="#">Edit</a></td>
            </tr>
        </tbody>
    </table>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    <script src="https://files-stackablejs.netdna-ssl.com/stacktable.min.js" type="text/javascript"></script>

    <script>
        $('#make-responsive').cardtable();
    </script>

</body>
</html>

Using History.js with AJAX

Over the past decade, web applications have evolved to make heavy use of JavaScript in order to dynamically load content into web pages. One of the big challenges that developers face when creating these applications is preserving an accurate and useful browser history. Without this many of a browsers most used features, like the back and forward buttons, will not work as expected.

Aim

  • To store a history of every dynamically loaded pages.
  • To load dynamic contents base on the URL inputted / pasted directly into the brower’s URL bar.
  • To make the browser’s forward and backward buttons work.
  • To enable sharing of URLs or use them to create links from any HTML document.

History.JS currently supports a lot of JavaScript libraries, but for this example I will only be demonstrating how to use the jQuery version of History.JS in working with dynamic contents.

Demo

Logs

Using History.Log() we can check the data stored to the history of our browser in object representation.

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery.history.js"></script>
   
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
         
</head>
<body>
    <br />
    <div class = "container">
        <nav class="navbar navbar-default">
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="home">Home</a></li>
                    <li><a href="about">About</a></li>
                    <li><a href="contact">Contact</a></li>     
                </ul>  
            </div>
        </nav>
        <div class = "content"></div>
    </div>
</body>

<script type='text/javascript'>
$(function(){
   
    var History = window.History;
   
    if (History.enabled) {
        var page = get_url_value('page');
        var path = page ? page : 'home';
        // Load the page
        load_page_content(path);
    } else {
        return false;
    }

    // Content update and back/forward button handler
    History.Adapter.bind(window, 'statechange', function() {
        var State = History.getState();
        // Do ajax
        load_page_content(State.data.path);
        // Log the history object to your browser's console
        History.log(State);
    });

    // Navigation link handler
    $('body').on('click', 'nav a', function(e) {
        e.preventDefault();
       
        var urlPath = $(this).attr('href');
        var title = $(this).text();
       
        History.pushState({path: urlPath}, title, './?page=' + urlPath); // When we do this, History.Adapter will also execute its contents.       
    });
   
    function load_page_content(page) {
        $.ajax({  
            type: 'post',
            url: page + '.html',
            data: {},                      
            success: function(response) {
                $('.content').html(response);
            }
        });
    }
   
    function get_url_value(variable) {
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
    }
});

</script>
</html>

Building a Real-Time Chat Application Using Pusher

824b1c56-87f0-11e1-9712-8f15a4b24539

Demo

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. In this tutorial we are going to create a simple chat application using Pusher. Pusher is a simple hosted API for quickly, easily and securely adding realtime bi-directional functionality via WebSockets to web and mobile apps, or any other Internet connected device.

Browser Support

Old browsers do not support WebSockets, you need latest browser that supports HTML5 WebSocket features, Please see caniuse.com to find-out all WebSocket supported browsers.

Scripts we need for our Chat Application:

  • jQuery
  • Pusher
  • Bootstrap JS and CSS (For the UI)
  • Bootbox (For our alert box)
  • Custom Styles

Create a Pusher Account

Step 1. Create an account at www.pusher.com
Step 2. Login to your pusher account then create an App, name it anything you want.
Step 3. After you have successfully created your app – the following will be generated: app_id, key, and secret.
Step 4. Go over the codes in this tutorial and replace the following: ‘your_app_id’, ‘your_app_key’, ‘your_app_secret’ with your app_id, key, and secret.
Step 5. Test the chat application in your server or local machine. Use 2 different browsers for the testing.


The Tutorial

Include the following code in the header part of your file.

1
2
3
4
5
6
7
8
9
10
11
12
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript" ></script>
<script src="//js.pusher.com/2.2/pusher.min.js" type="text/javascript" type="text/javascript" ></script>   
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript" ></script>  
<script src="//cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.3.0/bootbox.min.js" type="text/javascript" ></script>

<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<style = "text/css">
<!--       
.messages_display {height: 300px; overflow: auto;}     
.messages_display .message_item {padding: 0; margin: 0; }      
.bg-danger {padding: 10px;} -->
</style>

Create the chat form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div class = "container">      
    <div class = "col-md-6 chat_box">                      
        <div class = "form-control messages_display"></div>        
        <br />                     
        <div class = "form-group">             
            <label>Name</label>            
            <input type = "text" class = "input_name form-control" placeholder = "Name" />         
        </div>                     
        <div class = "form-group">             
            <label>Message</label>             
            <textarea class = "input_message form-control" placeholder = "Message"></textarea>         
        </div>                     
        <div class = "form-group input_send_holder">               
            <input type = "submit" value = "Send" class = "btn btn-primary input_send" />          
        </div>                 
    </div> 
</div>

Client Side script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<script type="text/javascript">        
// Enter your own Pusher App key
var pusher = new Pusher('your_app_key');
// Enter a unique channel you wish your users to be subscribed in.
var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function(data) {
    // Add the new message to the container
    $('.messages_display').append('<p class = "message_item">' + data.message + '</p>');
    // Display the send button
    $('.input_send_holder').html('<input type = "submit" value = "Send" class = "btn btn-primary input_send" />');
    // Scroll to the bottom of the container when a new message becomes available
    $(".messages_display").scrollTop($(".messages_display")[0].scrollHeight);
});

// AJAX request
function ajaxCall(ajax_url, ajax_data) {
    $.ajax({
        type: "POST",
        url: ajax_url,
        dataType: "json",
        data: ajax_data,
        success: function(response, textStatus, jqXHR) {
            console.log(jqXHR.responseText);
        },
        error: function(msg) {}
    });
}

// Trigger for the Enter key when clicked.
$.fn.enterKey = function(fnc) {
    return this.each(function() {
        $(this).keypress(function(ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        });
    });
}

// Send the Message
$('body').on('click', '.chat_box .input_send', function(e) {
    e.preventDefault();
   
    var message = $('.chat_box .input_message').val();
    var name = $('.chat_box .input_name').val();
   
    // Validate Name field
    if (name === '') {
        bootbox.alert('<br /><p class = "bg-danger">Please enter a Name.</p>');
   
    } else if (message !== '') {
        // Define ajax data
        var chat_message = {
            name: $('.chat_box .input_name').val(),
            message: '<strong>' + $('.chat_box .input_name').val() + '</strong>: ' + message
        }
        // Send the message to the server
        ajaxCall('message_relay.php', chat_message);
       
        // Clear the message input field
        $('.chat_box .input_message').val('');
        // Show a loading image while sending
        $('.input_send_holder').html('<input type = "submit" value = "Send" class = "btn btn-primary" disabled /> &nbsp;<img src = "loading.gif" />');
    }
});

// Send the message when enter key is clicked
$('.chat_box .input_message').enterKey(function(e) {
    e.preventDefault();
    $('.chat_box .input_send').click();
});
</script>

Server Side Script (message_relay.php):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
require('lib/Pusher.php');

// Change the following with your app details:
// Create your own pusher account @ www.pusher.com
$app_id = 'your_app_id'; // App ID
$app_key = 'your_app_key'; // App Key
$app_secret = 'your_app_secret'; // App Secret
$pusher = new Pusher($app_key, $app_secret, $app_id);

// Check the receive message
if(isset($_POST['message']) && !empty($_POST['message'])) {    
    $data['message'] = $_POST['message'];  
   
    // Return the received message
    if($pusher->trigger('test_channel', 'my_event', $data)) {              
        echo 'success';        
    } else {       
        echo 'error';  
    }
}

Character Count with Live Progress Bar using jQuery

Character Count with Progress Bar using jQuery

Demo Download

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
jQuery(document).ready(function() {
   
    $('textarea').keyup(function() {
        var box = $(this).val();
        var main = box.length * 100;
        var value = (main / 100);
        var count = 0 + box.length;
        var reverse_count = 100 - box.length;
       
        if(box.length >= 0){
            $('.progress-bar').css('width', count + '%');
            $('.current-value').text(count + '%');
            $('.count').text(reverse_count);
           
            if (count >= 50 && count < 85){
                $('.progress-bar').removeClass('progress-bar-danger').addClass('progress-bar-warning');
            }
            if (count > 85){
                $('.progress-bar').removeClass('progress-bar-warning').addClass('progress-bar-danger');
            }
            if(count >= 0 && count < 50){
                $('.progress-bar').removeClass('progress-bar-danger');
                $('.progress-bar').removeClass('progress-bar-warning');        
                $('.progress-bar').addClass('progress-bar-success')
            }
           
        }
        return false;
    });
});

HTML

1
2
3
4
5
6
7
8
9
10
11
<div class = "col-md-6">       
    <div class="progress">
        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
            <span class = "current-value">0%</span>
        </div>
    </div>
    <div class = "form-group">
        <textarea class = "form-control" rows = "7" maxlength = "100" placeholder = "Enter a text"></textarea>
    </div>
    <div class = "count btn btn-primary">100</div>
</div>

How to use Pace.Js

Do you want to add a nice loading bar on top of your pages similar to YouTube’s beautiful progress indicator?

This plugin pretty much does everything for us automatically, all we have to do is to include the Pace.Js and a custom loading style that you wish to apply into your website.

Download Pace.Js

It is advisable that you include these 2 files first thing on the header of your website.

1
2
3
4
<head>
    <script src="/pace/pace.js"></script>
        <link href="/pace/themes/pace-theme-barber-shop.css" rel="stylesheet" />
</head>

Download your preferred style bellow:

How to use niceScroll.Js

Nice Scroll is a simple jQuery plugin that replaces your browser’s default scroll bar with a custom scroll bar which you can fully customize.

  • Compatible with all desktop browser: Firefox 4+, Chrome 5+, Safari 4+ (win/mac), Opera 10+, IE 6+. (all A-grade browsers)
  • Compatible with mobile device: iPad/iPhone/iPod, Android 2.2+, Blackberry phones and Playbook (WebWorks/Table OS), Windows Phone 7.5 Mango and Windows Phone 8
  • Compatible with all touch devices: iPad, Window Surface.
  • Compabible with multi-input device (mouse with touch or pen): Window Surface, Chrome Desktop on touch notebook.
  • Compatible with 2 directions mice: Apple Magic Mouse, Apple Mouser with 2-dir wheel, PC mouse with 2-dir wheel (if browser support it).

CDN:

1
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.nicescroll/3.5.1/jquery.nicescroll.min.js"></script>

Very easy to integrate, simply copy the CDN on the header part of your website then add this additional script just bellow the CDN:

1
2
3
$(document).ready(function() {
    $("html").niceScroll({cursorwidth: '10px', autohidemode: false, zindex: 999 });
});

Replace “html” with whatever element you wish to integrate niceScroll.

To customize the appearance and behavior, use these parameters:

  • cursorcolor – change cursor color in hex, default is “#000000”
  • cursoropacitymin – change opacity very cursor is inactive (scrollabar “hidden” state), range from 1 to 0, default is 0 (hidden)
  • cursoropacitymax – change opacity very cursor is active (scrollabar “visible” state), range from 1 to 0, default is 1 (full opacity)
  • cursorwidth – cursor width in pixel, default is 5 (you can write “5px” too)
  • cursorborder – css definition for cursor border, default is “1px solid #fff”
  • cursorborderradius – border radius in pixel for cursor, default is “4px”
  • zindex – change z-index for scrollbar div, default value is 9999
  • scrollspeed – scrolling speed, default value is 60
  • mousescrollstep – scrolling speed with mouse wheel, default value is 40 (pixel)
  • touchbehavior – enable cursor-drag scrolling like touch devices in desktop computer (default:false)
  • hwacceleration – use hardware accelerated scroll when supported (default:true)
  • boxzoom – enable zoom for box content (default:false)
  • dblclickzoom – (only when boxzoom=true) zoom activated when double click on box (default:true)
  • gesturezoom – (only when boxzoom=true and with touch devices) zoom activated when pitch out/in on box (default:true)
  • grabcursorenabled, display “grab” icon for div with touchbehavior = true, (default:true)
  • autohidemode, how hide the scrollbar works, true=default / “cursor” = only cursor hidden / false = do not hide
  • background, change css for rail background, default is “”
  • iframeautoresize, autoresize iframe on load event (default:true)
  • cursorminheight, set the minimum cursor height in pixel (default:20)
  • preservenativescrolling, you can scroll native scrollable areas with mouse, bubbling mouse wheel event (default:true)
  • railoffset, you can add offset top/left for rail position (default:false)
  • bouncescroll, enable scroll bouncing at the end of content as mobile-like (only hw accell) (default:false)
  • spacebarenabled, enable page down scrolling when space bar has pressed (default:true)
  • railpadding, set padding for rail bar (default:{top:0,right:0,left:0,bottom:0})
  • disableoutline, for chrome browser, disable outline (orange hightlight) when selecting a div with nicescroll (default:true)
  • horizrailenabled, nicescroll can manage horizontal scroll (default:true)
  • railalign, alignment of vertical rail (defaul:”right”)
  • railvalign, alignment of horizontal rail (defaul:”bottom”)
  • enabletranslate3d, nicescroll can use css translate to scroll content (default:true)
  • enablemousewheel, nicescroll can manage mouse wheel events (default:true)
  • enablekeyboard, nicescroll can manage keyboard events (default:true)
  • smoothscroll, scroll with ease movement (default:true)
  • sensitiverail, click on rail make a scroll (default:true)
  • enablemouselockapi, can use mouse caption lock API (same issue on object dragging) (default:true)
  • cursorfixedheight, set fixed height for cursor in pixel (default:false)
  • hidecursordelay, set the delay in microseconds to fading out scrollbars (default:400)
  • directionlockdeadzone, dead zone in pixels for direction lock activation (default:6)
  • nativeparentscrolling , detect bottom of content and let parent to scroll, as native scroll does (default:true)
  • enablescrollonselection, enable auto-scrolling of content when selection text (default:true)

Reference: http://areaaperta.com/nicescroll/

How to use LazyLoad.Js

I was recently working on a portfolio website that contains a lot of images, this kind of website usually takes longer to load since it has to complete rendering all page images from top to bottom. Lately I came across this plugin called “LazyLoad” which delays the loading of images in long web pages, the images outside of viewport are not loaded until user scrolls to them. Using this plugin will make the page load faster, it can also help to reduce server load.

Download Example

Lazy Load depends on jQuery. Include them both in your HTML code:

1
2
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>

To apply LazyLoad to the images, we need to define a unique class within the image tag which will be identified by the plugin and then hook it into the lazyload(); function.

1
$("img.lazy").lazyload({effect : "fadeIn"});

For the img tag, we are not going to use the “src” attribute, instead we are going to use a new attribute “data-original”. Also, make sure to include both width and height attributes because without them the plugin may not work or can cause undesirable behaviors.

1
<img class="lazy" data-original="images/1.jpg" width="640" height="480">

Complete code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
<script>
$(function() {
    $("img.lazy").lazyload({effect : "fadeIn"});
});
</script>
</head>
<body>
    <div align = "center">
        <img class="lazy" data-original="images/1.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/2.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/3.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/4.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/5.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/6.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/7.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/8.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/9.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/10.jpg" width="640" height="480"><br />
        <img class="lazy" data-original="images/11.jpg" width="640" height="480">
    </div>
</body>
</html>

If you need to load images from another server, you can use AJAX via the jQuery function: load();

1
2
3
4
5
 $("#container").one("click", function() {
     $("#container").load("images.html", function(response, status, xhr) {
         $("img.lazy").lazyload();
     });              
 });

When checking the example, clear browser cache between each request. You can check what is actually loaded using your browser’s developer console (Chrome, Safari and IE) or FireBug (Firefox)

If you check your console, you will notice that the images that are NOT YET visible looks like this:

1
<img class="lazy" data-original="images/3.jpg" width="640" height="480" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC">

The “src” attribute doesn’t have the actual path, therefore it hasn’t been loaded yet.

Using LazyLoad with AJAX

To achieve this, we have to make sure that we execute LazyLoad only when the DOM elements have already been outputted to the screen, so it would make sense if we put our LazyLoad script after displaying the images on AJAX success.

1
2
3
4
5
6
7
8
9
10
$.post(ajax_url, data, function(response, textStatus, jqXHR) {
    if(textStatus == 'success'){
        // Display the images into the container
        $(".container").html($(response).fadeIn('slow'));
        // Execute LazyLoad
        $('.lazy').lazyload({
            effect: 'fadeIn'
        });
    }
});

Fall back for browsers that do not support JavaScript

It is always a good practice to enable default image to load when JavaScript is not supported by the browser.

1
2
<img class="lazy" src="images/example.jpg" data-original="img/example.jpg" width="100%" />
<noscript><img src="images/example.jpg" width="100%" /></noscript>

To prevent double copy of images from showing up, we should place the following CSS on our stylesheet file:

1
2
3
.lazy {
    display: none;
}

Ensuring that we initialize the images and would only show if JavaScript is enabled, we need to force the images to show up using the .show() function. Our code will now look like this:

1
2
3
$("img.lazy").show().lazyload({
    effect : "fadeIn"
});

Setting and Getting Cookies in jQuery

In this tutorial, we are going to use a jQuery library called jquery.cookie.min.js so that we can access cookies like this: $.cookie(‘name’)

Set a cookie:

1
2
3
4
5
6
7
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function($){
        $.cookie('cname', 'cvalue', { path: '/', expires: 1 });
    });
</script>

Retrieve the cookie:

1
$.cookie("cname")