Advertisement
  1. Code
  2. JavaScript
  3. jQuery

Use the jQuery UI to Control the Size of Your Text

Scroll to top
Read Time: 12 min

JQuery's UI can add so much to a web page. There are many different widgets that the UI provides. One up and coming star, is the slider. In this tutorial, I will show you how to use a slider to control the text size of an article on a page. This lets the user control exactly the size that suits them, and is also a pretty impressive feature to have on a site!

The slider portion of this tutorial reproduces a technique originally created by Buck Wilson.

Our Goal

We will eventually want our page to look something like this:

Behavior:

  • When the slider is dragged, a bubble will fade in, telling the current size.
  • The text "current text size" will also appear with the current text size next to it.
  • We will also attempt to make the text increase one px or decrease one px on the click of the plus or minus sign.

previewpreviewpreview

Step 1: Getting the Necessary Javascript Files

Obviously we need JQuery, but we're also going to need some UI files to extend JQuery. We can get a UI file that is custom to our needs at the JQuery UI Build Your Download page.

JQuery UI Download Page

As you can see, there are some really great sounding effects there! As tempting as it may be though, we don't need all of these effects to achieve the desired product. All we need is:

Step 2: The HTML

For this tutorial, I'm not going to waste time explaining the basics of HTML, and creating a layout using it and CSS. If you'd like to learn more about that, there are other tutorials here like my Top Panel tutorial or Collis' Tabbed Content tutorial.

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
3
   "http://www.w3.org/TR/html4/strict.dtd">
4
<html lang="en">
5
<head>
6
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
7
<title>Nettuts Slider</title>
8
<!--[if lt IE 7]>
9
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js" type="text/javascript"></script>
10
<![endif]-->
11
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
12
<script type="text/javascript" src="scripts/jquery.ui.js"></script>
13
<script type="text/javascript" src="scripts/cookie.js"></script>
14
</head>
15
<body>
16
<div id="header">
17
  <div class="slider_container">
18
    <div class="minus"></div>
19
    <div class="slider_bar">
20
      <div id="slider_caption"></div>
21
      <div id="slider1_handle" class="slider_handle"></div>
22
    </div>
23
    <div class="add"></div>
24
  </div>
25
</div>
26
<div id="text">
27
  <h1>Text Size Slider</h1>
28
  <div id="font_indicator">Current Font Size: <b></b> </div>
29
  <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p>
30
</div>
31
</body>
32
</html>

So you'll notice several things:

  1. The PNG fix for IE 5.5 and 6. I've linked directly to the google code page. This means I will have to end every transparent PNG with a -trans.png .
  2. I have also linked directly to JQuery and our custom made UI file.
  3. I have put the necessary tags for the slider in the #header

NOTE: For the slider to work, we need to have a bar and a handle.

Step 3: The CSS

Here is the CSS to make that page look a little bit better. This page is pretty simple, and therefore the CSS is pretty simple as well:

1
2
body {
3
	background: #373737;
4
	text-align: center;
5
	margin: 0px;
6
}
7
#header {
8
	width: 700px;
9
	height: 200px;
10
	background: #48887d url(images/header.jpg);
11
	margin-left: auto;
12
	margin-right: auto;
13
	position: relative;
14
}
15
.slider_container {
16
	position: absolute;
17
	height: 25px;
18
	top: 170px;
19
	left: 165px;
20
}
21
.minus {
22
	background: url(images/minus-trans.png) no-repeat;
23
	height: 9px;
24
	width: 25px;
25
	overflow: hidden;
26
	float: left;
27
	cursor: pointer;
28
}
29
.slider_bar {
30
	background: url(images/bar-trans.png) no-repeat;
31
	height: 9px;
32
	width: 316px;
33
	float: left;
34
	margin: 0px 5px;
35
	position: relative;
36
}
37
.add {
38
	background: url(images/add-trans.png) no-repeat;
39
	height: 25px;
40
	width: 23px;
41
	float: left;
42
	position: relative;
43
	top: -5px;
44
	cursor: pointer;
45
}
46
.slider_handle {
47
	background: url(images/selector-trans.png) no-repeat;
48
	height: 25px;
49
	width: 12px;
50
	position: absolute;
51
	top: -8px;
52
}
53
#slider_caption {
54
	background: url(images/caption-trans.png) no-repeat;
55
	height: 45px;
56
	width: 38px;
57
	overflow: hidden;
58
	position: absolute;
59
	top: -50px;
60
	margin-left:-10px;
61
	padding: 5px 0px 0px 0px;
62
	font-family: "Myriad Pro";
63
	color: #36665d;
64
	font-weight: bold;
65
	text-align: center;
66
}
67
#text {
68
	font-family: Helvetica, Arial, sans-serif;
69
	width: 655px;
70
	background: #f9f9f9;
71
	margin-left: auto;
72
	margin-right: auto;
73
	padding: 20px 20px 20px 25px;
74
	position: relative;
75
}
76
#text p {
77
	font-size: 12px;
78
	text-align: left;
79
	color: black;
80
}
81
#text h1 {
82
	text-align: left;
83
	margin-left: 20px;
84
}
85
86
p{
87
font-family: Arial, Helvetica, sans-serif;
88
color: #CCCCCC;
89
}
90
91
#font_indicator{
92
position: absolute;
93
right: 100px;
94
top: 50px;
95
font-size: 10px;
96
display: none;
97
}

Again, I'm not going to go into great detail with the CSS either. If you still need more help with that, be sure to check out those two tutorials I mentioned above. If you do have any questions, be sure to let me know in the comments.

Notice that all of the png images that have alpha transparency have a -trans.png ending.

Step 4: Basic Slider Effects

When I was first learning about the slider effect, I Googled it to research a little bit more about it and how it works. Well I was lucky to find this amazing screencast. It had a really neat effect too; a caption that appeared to display the position of the slider, on top of the slider. Unfortunately, they stopped there. We're going to use a variation of their JQuery code as a jumping off point:

1
2
$(function() {
3
4
5
	$('#slider_caption').hide();
6
	var captionVisible = false;
7
	$('.slider_bar').slider({
8
		handle: '.slider_handle',
9
		startValue: 26,
10
		minValue: 0,
11
		maxValue: 100,
12
		start: function(e, ui) {
13
			$('#slider_caption').fadeIn('fast', function() { captionVisible = true;});
14
		},
15
		stop: function(e, ui) { 
16
			if (captionVisible == false) {
17
				$('#slider_caption').fadeIn('fast', function() { captionVisible = true;});
18
19
				$('#slider_caption').css('left', ui.handle.css('left')).text(Math.round(ui.value * 15/100 + 8 ));
20
21
				$("div#text p").animate({fontSize: ui.value * 15/100 + 8 }).fadeIn("slow");
22
			}
23
			$('#slider_caption').fadeOut('fast', function() { captionVisible = false; });
24
			
25
		},
26
	
27
		slide: function(e, ui) {
28
			$('#slider_caption').css('left', ui.handle.css('left')).text(Math.round(ui.value * 15/100 + 8 ));
29
30
			$("div#text p").css({fontSize: ui.value * 15/100 + 8 }).fadeIn("slow");
31
		}
32
	});

Some Key Ideas:

  • First, we hide the caption with Javascript. This makes the caption visible if Javascript is disabled for just a little bit more accessibility.
  • As you can see, we now have a .slider modifier and several sub items as well:
    • startValue : This specifies the position that the handle starts at
    • minValue : This specifies the minimum value that the handle will go to
    • maxValue: This specifies the maximum value that the handle will go to
    • start: This allows us to tell JQuery what to do when the user starts sliding the bar
    • stop: This specifies what happens when the slider is let go of
    • slide: This specifies what happens when the slider is being slid
    • handle: This allows us to specify what will be the handle
  • We also assign a variable that will help us know, when stop: occurs, whether the caption is visible or not, and then perform an action based on that conclusion.
  • We also had to put a limit on the font sizes possible, so we limited the slider value possibilities to between 8 and 23. We did this by performing basic math on the value of the slider. (multiplied it by 15/100 and added 8 )
  • This equation resulted in decimal place sizes, so we had to round it the Math.round
  • Notice also, the method by which we made the caption stay on top of the handle. We made the css left value of the caption equal to the handle.
  • Notice that on the stop: I have the text size animated, while on the slide, I have the css size constantly changing. This might seem counter-intuitive, that on slide: I wouldn't animate it, but by the essence of gradually sliding and enlarging the size it does the same thing. If I were to animate instead of just changing the css, it would be choppy and unresponsive.


Step 5: Adding the Text Caption

1
2
$(function() {
3
4
5
	$('#slider_caption').hide();
6
	var calloutVisible = false;
7
	$('.slider_bar').slider({
8
		handle: '.slider_handle',
9
		startValue: 26,
10
		minValue: 0,
11
		maxValue: 100,
12
		start: function(e, ui) {
13
			$('#slider_caption').fadeIn('fast', function() { calloutVisible = true;});
14
			$('#font_indicator').fadeIn('slow');
15
		},
16
		stop: function(e, ui) { 
17
			if (calloutVisible == false) {
18
				$('#slider_caption').fadeIn('fast', function() { calloutVisible = true;});
19
				$('#font_indicator').fadeIn('slow');
20
				$('#slider_caption').css('left', ui.handle.css('left')).text(Math.round(ui.value * 15/100 + 8 ));
21
				$('#font_indicator b').text(Math.round(ui.value * 15/100 + 8 ));
22
				$("div#text p").animate({fontSize: ui.value * 15/100 + 8 }).fadeIn("slow");
23
			}
24
			$('#slider_caption').fadeOut('fast', function() { calloutVisible = false; });
25
			$('#font_indicator').fadeOut('slow');
26
			
27
			
28
		},
29
	
30
		slide: function(e, ui) {
31
			$('#slider_caption').css('left', ui.handle.css('left')).text(Math.round(ui.value * 15/100 + 8 ));
32
			$('#font_indicator b').text(Math.round(ui.value * 15/100 + 8 ));
33
			$("div#text p").css({fontSize: ui.value * 15/100 + 8 }).fadeIn("slow");
34
		}
35
	});



Key Ideas about #font_indicator

  • We added the same fade in and fade out effects in the same spots as the caption
  • We left out the css left position though
  • Notice that we have a <b> tag within the div#font-indicator. This not only makes the number stand out more, but allows us to just put the current slider handle value as text into it. If we just appended to the end of the div, every font size value would just pile up at the end.

Step 6: Giving the Plus and Minus Actions

This just wouldn't be a functional design, if we didn't give the plus and minus signs actions on click. This code might be a little bit sloppy and not perfectly efficient, but it gets the job done. This project required a surprising amount of math, which explains some of the wacky numbers that end up being used.

Without further ado, here is the rest of the javascript, I'll explain it afterward:

1
2
	  $(".add").click(function(){
3
    var currentFontSize = $('#text p').css('font-size');
4
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
5
    var newFontSize = currentFontSizeNum+1;
6
	if (newFontSize < 24) {
7
    $('#text p').css('font-size', newFontSize);
8
	$('#slider_caption').css('left', newFontSize*19.75 - 158).fadeIn('fast').text(Math.round(newFontSize )).fadeOut();
9
	$('.slider_handle').css('left', newFontSize*19.75 - 158);
10
	$('#font_indicator').fadeIn('slow');
11
	$('#font_indicator b').text(Math.round(newFontSize ));
12
	$('#font_indicator').fadeOut('slow');
13
	}
14
	else{
15
	$('#font_indicator').fadeIn('slow');
16
	$('#font_indicator b').text("Isn't 23 big enough?");
17
	$('#font_indicator').fadeOut('slow');
18
	}
19
    return false;
20
  });
21
  	  $(".minus").click(function(){
22
    var currentFontSize = $('#text p').css('font-size');
23
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
24
    var newFontSize = currentFontSizeNum-1;
25
	if (newFontSize > 8) {
26
    $('#text p').css('font-size', newFontSize);
27
	$('#slider_caption').css('left', newFontSize*19.75 - 158).fadeIn('fast').text(Math.round(newFontSize )).fadeOut();
28
	$('.slider_handle').css('left', newFontSize*19.75 - 158);
29
	$('#font_indicator').fadeIn('slow');
30
	$('#font_indicator b').text(Math.round(newFontSize ));
31
	$('#font_indicator').fadeOut('slow');
32
	}
33
	else{
34
	$('#font_indicator').fadeIn('slow');
35
	$('#font_indicator b').text("Isn't 8 small enough?");
36
	$('#font_indicator').fadeOut('slow');
37
	}
38
	return false;
39
  });

Some Key Notes:

  • If you know basic Javascript syntax, this should be pretty self evident.
  • I assign an initial variable to get the current font size.
  • I then convert it to an integer
  • I then create another variable that is one value higher.
  • I place a limit between under 24 and above 8, by using an if else statement.

Math Time

Adjusting the handle and caption to react to the plus and minus click was a real challenge. What I ended up doing, was figuring out the width of the bar (316px), and dividing that between the 16 possible font sizes (8-23) to figured out how much space each increment took.

316/16 =

19.75

To be safe, I then needed to figure out the starting spot for the font size. I knew this wasn't exactly 12, because I modified it slightly with the 15/100 + 8. So I took the starting value of the handle (26) and multiplied it by that:

26*15/100 + 8=

11.9

I figured that, since it was rounded it would be twelve anyway.

So I figured that the handle would be the [font size*19.75 - 158 (The first 8 sizes)]px.

Just thought that I'd give you a glimpse into my weird and over complicated math ;) .There's probably much easier ways to do it, but I guess this is my logic.

Step 7: Cookie Time, reading the cookie

For dealing with cookies I used Klaus Hartl's excellent cookie plugin. You can view the basic syntax of the plugin in the link I provided. The challenge, was to find a spot that would reliably set the cookie. I ended up setting it when the browser refreshes or changes the page. This way, it only does it when necessary and realiably too. First we add the code to the top of the javascript file to read the cookie:

1
2
var startSize = $.cookie('fontSize');
3
var startSize = parseFloat(startSize, 12);
4
5
$('#text p').css('font-size', startSize);

What I Did:

  • I first read the cookie and sent it to the variable startSize
  • I then changed that variable into an integer
  • I then added that number to the default css of the text

Step 8: Setting The Cookie

As I mentioned above, we need to set the cookie when the page is exited. We do this by using the following code:

1
2
  window.onbeforeunload = leaveCookie;
3
4
function leaveCookie()
5
{
6
			var FontSize = $('#text p').css('font-size');
7
   			var IntFontSize = parseFloat(FontSize, 10);
8
			$.cookie('fontSize', IntFontSize);
9
}

What I Did:

  • NOTE: This JS is outside of the JQuery $(function() {});
  • First, I activated a function when the browser left the page
  • Then I converted the text size into an integer
  • Then I put this into the cookie

That's It!

Hope you found this tutorial useful! Please excuse my programming logic, I don't always think so efficiently :P. If you have any questions or comments please feel free to let me know in the comments!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.