Search This Blog

Sunday, October 20, 2013

Creating Custom Scrollbar with jQuery

Custom vertical / horizontal scroll bars is a nice and unique features for websites, as a web developer or designer we can apply this features in our web projects to become our projects unique.
Most websites using custom scroll bar areFacebook, Twitter and Google Gmail, So what they secrets to create custom scroll bar?
In the web there have many available ready to use plugins of this web application, but how to create our own code? In this tutorial I would like share our own idea on how to create a custom vertical scroll bar with jQuery.
This custom scroll bar we will create are have similarity on Facebook and Google GmailScroll bar. So let’s begin.

1. Creating the Page Template

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Creating Custom Vertical Scrollbar with jQuery | istockphp.com</title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="js/jquery-1.9.1.js"> </script>
<script type="text/javascript" src="js/jquery.mousewheel.js"> </script>
<script type="text/javascript" src="js/jquery-ui-draggable.js"> </script>
<script type="text/javascript" src="js/script.js"></script>
</head>

<body>
	<div id="wrapper">
		<div id="scroll_block">
			<div id="scrollbar_holder">
            	<div class="scrollbar"></div>
            </div>
			<div id="scroll_content">
                    <div id="content" align="justify">
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <p>
                        2013 &copy; Work by <a href="http://istockphp.com">istockphp.com</a><br />
                        <br />
                        Support us our social fan pages, we inspire to create more.
                        <br />
                        <strong>Facebook: </strong><a href="http://www.facebook.com/pages/Istockphp/235451993242578">http://www.facebook.com/pages/Istockphp/235451993242578</a><br />
                        <strong>Twitter:</strong> <a href="http://twitter.com/istockphp">http://twitter.com/istockphp</a><br />
                        <strong>Google Plus:</strong> <a href="https://plus.google.com/104655767794822143257">https://plus.google.com/104655767794822143257</a><br />
                        </p>
                        <br />
                    </div> <!--content end-->
               </div> <!--scroll_content end-->
      </div> <!--scroll_block end-->
    </div> <!--wrapper end-->
</body>
</html>
In the index.html we included the stylesheet and the jQuery script, to complete this web application fast and easy we need to include the jquery.mousewheel.js to get the trigger of mouse scroll event and jquery-ui-draggable.js for drag gable trigger event and lastly our custom jQuery script.

2. The stylesheet

style.css
body {
	font-family: Arial, Helvetica, sans-serif;
	font-size:13px;
	margin:0;
	padding:0
}
div#scroll_block {
	width: 500px;
    height: 500px;
    overflow:hidden; /* hide the scroll bar*/
	margin: 20px auto 0 auto;
	background:#E4E7F0;
	position:relative;
}
div#scroll_content {
    height: 500px;
    width: 485px;
	position:relative;
}
div#scrollbar_holder {
   	background: #ced0d3;
	border-radius:8px;
	float: right;
    width: 15px;
	position:absolute;
	right:0;
}
div#content {
	padding: 0 14px;
}
div.scrollbar {
	background: #7c7d7f;
	border-radius:8px;
	width: 15px;
	top:0;
}
In stylesheet, in the div#scroll_block we need to set overflow hidden to hide the contents and the div#scrollbar_holder we set to position absolute and float right for scroll bar holder.

3. The jQuery script

script.js
/*
	Author: Axl Mulat
	Site: http://istockphp.com
*/
jQuery(function($) {

	var scrollBlockHeight = $("div#scroll_block").height(); // get height
	$("div#scrollbar_holder").height(scrollBlockHeight); // set height for scroll holder

	var contentHeight 	= $("div#content").height(); // get content div height
	// formula custom scroll bar
	var scrollbarHeight = ( scrollBlockHeight / contentHeight ) * scrollBlockHeight;

	if(contentHeight < scrollBlockHeight) { // if the content is short, hide the scrollbar
		$("div.scrollbar").css('display', 'none');
		$("div#scrollbar_holder").css('display', 'none');
	} else {
		$("div.scrollbar").height(scrollbarHeight)
	  }

	/* trigger 1: start function drag */
	$("div.scrollbar").draggable({
			axis: 'y',
			containment: 'parent',
			drag: function() {
				var getPositionTop 	= parseInt($(this).css('top')); // get css top
				// formula for content up
				var scrollTopNew 	= ( getPositionTop / scrollBlockHeight) * (contentHeight);
				//console.log(getPositionTop); // logs
				$("div#scroll_content").css("top", '-'+scrollTopNew+'px'); // up the content
			}
	});
	/* trigger 1: end function drag */

	/* trigger 2: function scroll */
	var getmoduloHeight = scrollBlockHeight - scrollbarHeight; // scrollBlock - scrollbar

	// get total height content
	var formulateHeight = ( getmoduloHeight / scrollBlockHeight) * (contentHeight);

	$('#scroll_block').bind("mousewheel", function (event, delta) {
		//console.log(delta); // delta scroll trigger
		var getPositionTop		= parseInt( $('div.scrollbar').css('top')); // get css top
		var scrollTopNew		= getPositionTop - (delta * 10); // with delta
		var scrollTopContent	= ( scrollTopNew / scrollBlockHeight) * (contentHeight);

		//console.log(getPositionTop);
		if(scrollTopNew < 0) { // if rich the top content, return false, and set default
			$("div.scrollbar").css("top", "0px" );
			$("div#scroll_content").css("top", "0px" );
			return false;
		}
		if(scrollTopContent > formulateHeight) { // if rich the bottom content, return false, and set default
			$("div.scrollbar").css("top", getmoduloHeight );
			$("div#scroll_content").css("top", '-'+formulateHeight+'px');
			return false;
		}

		$("div#scroll_content").css("top", '-'+scrollTopContent +'px'); // up the content
		$("div.scrollbar").css("top", scrollTopNew ); // down the scroll bar
	});
	/* trigger 2: end function scroll */

	/* trigger 3: click scrollbar holder, scroll start */
	$("div#scrollbar_holder").click(function(e) { // add event

	  	var getPositionTop 	= parseInt($("div.scrollbar").css('top')); // get css top

	  //var pageX 			= e.pageX - this.offsetLeft;
		var pageY 			= e.pageY - this.offsetTop;

		var topWithScroll 	= getPositionTop + scrollbarHeight; // get height scrolltop + scrollbar Height
		var positionTop 	= pageY - scrollbarHeight; // pagey - scrollbar Height =  to get the get height scrolltop

		//console.log(pageY);
		var pageY_adjust = (pageY - 20); // adjust
		if(pageY_adjust < getPositionTop) { // click up the scroll bar

				$("div.scrollbar").stop(true, false).animate({ "top" :   pageY-40 }, 'fast');
				var getPositionTop_click = pageY-40;

				if(getPositionTop_click < 0) { // if user click the top level of the scroll, set to animate to top

					$("div.scrollbar").stop(true, false).animate({ "top" :   0 }, 'fast');
					$("div#scroll_content").stop(true, false).animate({ "top" :   0 }, 'fast');

				} else {

					var scrollTopNew 	= ( getPositionTop_click / scrollBlockHeight) * (contentHeight);
					$("div#scroll_content").stop(true, false).animate({ "top" :   '-'+scrollTopNew+'px' }, 'fast');

					}
		} else { // click down the scroll bar
			if(pageY > topWithScroll) {

					$("div.scrollbar").stop(true, false).animate({ "top" : positionTop }, 'fast');
					var getPositionTop_click = positionTop;

					if(pageY > scrollBlockHeight) { // if user click the bottom level of the scroll, set to animate to bottom

						$("div.scrollbar").stop(true, false).animate({ "top" : getmoduloHeight }, 'fast'); // getmoduloHeight from scrollbar var
						$("div#scroll_content").stop(true, false).animate({ "top" :   '-'+formulateHeight+'px' }, 'fast');  // formulateHeight from scrollbar var

					} else {

						var scrollTopNew 	= ( getPositionTop_click / scrollBlockHeight) * (contentHeight);
						$("div#scroll_content").stop(true, false).animate({ "top" :   '-'+scrollTopNew+'px' }, 'fast');

					}
			}
		  }

	e.preventDefault(); // like return false
	});
	/* trigger 3: click scrollbar holder, scroll end */
}); // jQuery End
Finally the long custom jquery script, first things first in line 7-12, we need the get the height of div#scroll_block dynamically and set the height to the div#scrollbar_holder. Then getting the height value of div#content for the formula of scroll bar. So let’s start the triggers event.
Trigger 1: Draggable Content
In line 20-32 the div#scrollbar we apply the draggable functions comes from jquery-ui-draggable.js, while dragging the div we getting the css top value that will apply the formula for content up scrolling.
Trigger 2: Scrolling Content
The scrolling event trigger starting from line 34-61, these trigger are same in drag gable function, but we need some values to work this, first the getmoduloHeight variable are the getting the value of (scrollBlockHeight – scrollbarHeight) to use and get the total height of the content, this value will we used to prevent the scroll out of the content, these variables applied in line 48-57. The delta event is for mouse scrolling, it gets the value for scrolling and we use for content up and down function.
Trigger 3: Clicking Drag Content
Finally the click drag content, it start the line 64-114, this trigger happened if the user click the div#scrollbar_holder, it move up and down the content, we set the event in the click trigger to get the value of offsetTop, what will happened in the script if the user click below and above the scroll bar it animate the content up/down and animate the scroll bar.

4. Done

We’re done, we’re creating our own custom scroll bar using jQuery. I know some of my code are complicated to understand, but sharing ideas is a good starting to create more and ideas. Hopefully my ideas you’ll make sense.
Let’s have a look at what we’ve achieved:
  • Creating our own custom scroll bar
  • Works in cross browser platform.
  • Simple and working Vertical scroll bar.

7 comments:

  1. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks for any other wonderful post. Where else may just anyone get that type of info in such a perfect means of writing? I’ve a presentation next week, and I am on the look for such information.

    hardware and networking training in chennai

    hardware and networking training in velachery

    xamarin training in chennai

    xamarin training in velachery

    ios training in chennai

    ios training in velachery

    iot training in chennai

    iot training in velachery

    ReplyDelete