Drag-and-Drop with the YUI: Part-3

Exclusive offer: get 50% off this eBook here
Learning the Yahoo! User Interface library

Learning the Yahoo! User Interface library — Save 50%

Develop your next generation web applications with the YUI JavaScript development library

£16.99    £8.50
by Dan Wellman | November 2009 | AJAX Open Source Web Development

Read Part One of Drag-and-Drop with the YUI here.

Read Part Two of Drag-and-Drop with the YUI here.

Visual Selection with the Slider Control

So far in this chapter we've focused on the functionality provided by the Drag-and-Drop utility. Let's shift our focus back to the interface controls section of the library and look at one of the components which is related very closely to drag-and-drop—the Slider control.

A slider can be defined using a very minimal set of HTML. All you need are two elements: the slider background and the slider thumb, with the thumb appearing as a child of the background element:

<div id="slider_bg" title="the slider background">
<div id="slider_thumb" title="the slider thumb">
<img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="images/slider_thumb.gif"></div>
</div>

These elements go together to form the basic Slider control, as shown in below:

Learning the Yahoo! User Interface library

The Slider control works as a specific implementation of DragDrop in that the slider thumb can be dragged along the slider background either vertically or horizontally. The DragDrop classes are extended to provide additional properties, methods, and events specific to Slider.

One of the main concepts differentiating Slider from DragDrop is that with a basic slider, the slider thumb is constrained to just one axis of motion, either X or Y depending on whether the Slider is horizontal or vertical respectively.

The Slider is another control that can be animated by including a reference to the Animation control in the head of the page. Including this means that when any part of the slider background is clicked on, the slider thumb will gracefully slide to that point of the background rather than just moving there instantly.

The Constructor and Factory Methods

The constructor for the slider control is always called in conjunction with one of the three factory methods, depending on which type of slider you want to display. To generate a horizontal slider the YAHOO.widget.Slider.getHorizSlider is called, with the appropriate arguments.

To generate a vertical slider, on the other hand, the YAHOO.widget.Slider.getVertSlider would instead be used. There is also another type of slider that can be created—the YAHOO.widget.Slider.getSliderRegion constructor and factory method combination creates a two-dimensional slider, the thumb of which can be moved both vertically and horizontally.

There are a range of arguments used with the different types of slider constructor. The first two arguments are the same for all of them, with the first argument corresponding to the id of the background HTML element and the second corresponding to the id of the thumb element.

The type of slider you are creating denotes what the next two (or four when using the SliderRegion) arguments relate to. With the horizontal slider or region slider the third argument is the number of pixels that the thumb element can move left, but with the horizontal slider it is the number of pixels it can move up. The fourth argument is either the number of pixels which the thumb can move right, or the number of pixels it can move down.

When using the region slider, the fifth and sixth arguments are the number of pixels the thumb element can move up and down, so with this type of slider all four directions must be specified. Alternatively, with either the horizontal or vertical sliders, only two directions need to be accounted for.

The final argument (either argument number five for the horizontal or vertical sliders, or argument number seven for the region slider) is optional and refers to the number of pixels between each tick, also known as the tick size. This is optional because you may not use ticks in your slider, therefore making the Slider control analogue rather than digital.

Class of Two

There are just two classes that make up the Slider control—the YAHOO.widget.Slider class is a subclass of the YAHOO.util.DragDrop class and inherits a whole bunch of its most powerful properties and methods, as well as defining a load more of its own natively.

The YAHOO.widget.SliderThumb class is a subclass of the YAHOO.util.DD class and inherits properties and methods from this class (as well as defining a few of its own natively).

Some of the native properties defined by the Slider class and available for you to use include:

  • animate—a boolean indicating whether the slider thumb should animate. Defaults to true if the Animation utility is included, false if not
  • animationDuration—an integer specifying the duration of the animation in seconds. The default is 0.2
  • backgroundEnabled—a boolean indicating whether the slider thumb should automatically move to the part of the background that is selected when clicked. Defaults to true
  • enableKeys—another boolean which enables the home, end and arrow keys on the visitors keyboard to control the slider. Defaults to true, although the slider control must be clicked once with the mouse before this will work
  • keyIncrement—an integer specifying the number of pixels the slider thumb will move when an arrow key is pressed. Defaults to 25 pixels

A large number of native methods are also defined in the class, but a good deal of them are used internally by the slider control and will therefore never need to be called directly by you in your own code. There are a few of them that you may need at some point however, including:

  • .getThumb()—returns a reference to the slider thumb
  • .getValue()—returns an integer determining the number of pixels the slider thumb has moved from the start position
  • .getXValue()—an integer representing the number of pixels the slider has moved along the X axis from the start position
  • .getYValue()—an integer representing the number of pixels the slider has moved along the Y axis from the start position
  • .onAvailable()—executed when the slider becomes available in the DOM
  • .setRegionValue() and .setValue()—allow you to programmatically set the value of the region slider's thumb

More often than not, you'll find the custom events defined by the Slider control to be most beneficial to you in your implementations. You can capture the slider thumb being moved using the change event, or detect the beginning or end of a slider interaction by subscribing to slideStart or slideEnd respectively.

The YAHOO.widget.SliderThumb class is a subclass of the DD class; this is a much smaller class than the one that we have just looked at and all of the properties are private, meaning that you need not take much notice of them. The available methods are similar to those defined by the Slider class, and once again, these are not something that you need to concern yourself with in most basic implementations of the control.

Learning the Yahoo! User Interface library Develop your next generation web applications with the YUI JavaScript development library
Published: March 2008
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

A Very Simple Slider

What we're aiming to achieve over the course of this example is to produce a small widget that visitors to your site could use to dynamically change the font size of text on the page in a visually appealing manner.

I know that the font-size of any given page can easily be adjusted by your visitors using the native method of their browser's UI, but it's a nice effect to have directly on your own pages, it promotes usability, and would sit nicely in a 'user control panel' area of your site/page.

The screenshot below demonstrates how our slider will appear by the end of this example:

 

Getting Started

All instances of the Slider control must be built not only from underlying HTML and JavaScript, but also CSS. Certain aspects of the control can only be set using a stylesheet. When using this control styling is just as important as the other two aspects, but we'll come to that in just a moment.

We'll also be making use of the reset-fonts-grids.css tool for this example as well. Yahoo! recommends the use of this file in all library implementations so that you get a consistent look across browsers.

In a blank page in your text editor, begin with the following basic page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8">
<title>Yui Slider Example</title>
<script type="text/javascript"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="yui/build/yahoo-dom-event/yahoo-dom-event.js">
</script>
<script type="text/javascript"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="yui/build/dragdrop/dragdrop-min.js"></script>
<script type="text/javascript"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="yui/build/slider/slider-min.js"></script>
<link rel="stylesheet" type="text/css"
href="yui/build/reset-fonts-grids/reset-fonts-

grids.css">
<link rel="stylesheet" type="text/css"

href="slider.css">
</head>
<body>
<div id="doc" class="yui-t5">
<div id="bd">
<div id="yui-main">
<div class="yui-b">
<div class="content" id="content">
<div>Lorem ipsum etc…</div>
</div>
</div>
</div>
<div class="yui-b">
<div id="sli_bg" title="font size slider">
<div id="sli_thumb"><img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="images/sli_thumb.gif"
alt="slider_thumb"></div>
</div>
<p class="sli_legend">Set the Font-size</p>
</div>
</div>
</div>
</body>
</html>

A lot of the nested <div> elements are required for the doc3 and yui-t5 CSS template used to layout our example page. Don't worry too much about those (just make sure they're all there), the key part of the code is the mark up defining the underlying slider.

The slider thumb, sli_thumb, has the image making up the slider thumb hard-coded directly into it as opposed to being set with CSS, as the slider background is, and is defined as a child of the slider background element sli_bg. Save what we have so far as slider.html in the yuisite folder.

Adding the CSS

As I mentioned before, CSS is essential to the correct layout and functioning of the slider object and is used to set the background image of the outer slider <div> element among other things. In a new page in your text editor, add the following CSS:

#sli_bg {
position:relative;
width:240px;
height:50px;
background:url(images/sli_bg.gif) no-repeat;
margin:5px auto auto 5px;
}
#sli_thumb {
position:absolute;
top:20px;
left:110px;
}


These two selectors target the slider background and thumb components respectively; both elements of the slider must have a specified position for the control to work. The main rule for the slider background is the background property which is used to display the slider background image. Save this file as slider.css.

In our example, the middle of the slider is the default position so when the page loads, it is important for the slider thumb to be centered over the background image. This is done by positioning the image with CSS, instead of using a property of the slider object as you may do with other controls.

We'll also need just a couple of other selectors specific to this demonstration page:

.content {
font-size:100%;
margin-top:5px;
padding:10px;
border:1px solid black;
}
.sli_legend {
font-size:100%;
margin-top:10px;
text-align:center;
}
</style>


Adding the JavaScript

Now we're ready to move on to the final part of this example—the JavaScript that will turn a couple of images into a fully working Slider element. Make sure slider.html is open in your text editor. Just before the closing </body> tag, add the following code:

<script type="text/javascript">
//setup the namespace object for this example
YAHOO.namespace("yuibook.slider");
//define the initSlider function
YAHOO.yuibook.slider.initSlider = function() {
//define the slider object
var fontslider = YAHOO.widget.Slider.getHorizSlider
("sli_bg", "sli_thumb", 110, 110, 20);
//subscribe to the change event
fontslider.subscribe("change", setFontSize);
//define the sizes object
var sizes = {
"-100":61,
"-80":69,
"-60":77,
"-40":85,
"-20":93,
"0":100,
"20":108,
"40":116,
"60":123,
"80":131,
"100":138
};
//define the setFontSize function
function setFontSize() {
//get the position of the slider thumb
var val = fontslider.getXValue();
//set the new font-size according to the slider

position
var newSize = sizes[val] + "%";
YAHOO.util.Dom.setStyle("content", "font-size",

newSize);
}
}
//execute initSlider when DOM is ready
YAHOO.util.Event.onDOMReady(

YAHOO.yuibook.slider.initSlider);
</script>

The .onDOMReady() method kicks s the paeverything off as soon as the DOM is in a complete state which will ensure that our slider is available as soon age has loaded. The rest of the code then goes within the curly brackets of the setSlider() function.

The Slider.getHorizSlider constructor has five arguments. The first is the element with an id attribute of sli-bg, the second is the element with an id of sli_thumb. The next two arguments indicate how far the slider thumb can travel in left and right directions, it is important that the distance does not exceed the boundary of the slider background or the thumb will be able to leave the slider background.

The final parameter sets up the tick marks for the slider, making it digital instead of analogue. The visible lines that mark each tick are part of the picture itself and are not created automatically by the control.

We want the text size to increase or decrease depending on the position of the thumb. To achieve this we'll need to find out how far the slider has moved in either direction and then translate this into the corresponding font-size. We also need to tell the script 'when' the font-size should be changed.

We start off by addressing that last point first, which is going to be very easy to do using one of the custom events built into the Slider control.

The change event fires every time the position of the slider thumb changes. We can easily subscribe a callback function to the event which we can use to execute the code which changes the size of the text. We use a literal object to map the slider positions to font-size values, we can then refer to items in the object using a simple string.

The .getXValue() method provided by the YAHOO.widget.Slider class allows us to retrieve the number of pixels the thumb has moved from the start position. Each time the thumb is moved, we can use this to determine its new position and store it in the val variable.

As we've defined tick marks of 20 pixels, the val variable will only be holding a value which matches one of the strings used in the associative array. So the newSize variable will hold one of the values from the array, which correspond (mostly) to a small range of the font sizes used in fonts.css.

We also need to concatenate a percentage symbol onto the end of the value returned from the object. This is in order to avoid the value being treated as the default of points, as this would make the text ridiculously large.

Finally, we make use of the .setStyle() DOM method to physically change the size of the text contained in the content element. The format of the arguments supplied to the method is: the element reference to target, the style property you wish to change, and the value by which to change it.

 

It's as easy as that, no further coding is needed for the slider to work as intended. Save the page and view it in your browser of choice, it should appear as shown here:

Learning the Yahoo! User Interface library

When designing a slider implementation, it is important to take into account the sizes of the slider background and thumb images when configuring properties such as the pixel distance the thumb can travel and the distance between ticks, to make sure everything looks as it should.

Summary

The code required to make the images on our product listing page draggable could best be described as minimal. It's also very easy code to get to grips with. As the example highlighted, it's the mechanics of what you want to achieve with the Drag-and-Drop utility's functionality that takes far more consideration.

A close descendant of Drag-and-Drop, the Slider, is even easier to implement and can be a very effective and visually appealing addition to your pages. Although this control is relatively basic and compact, it still provides a series of custom events to hook into and a range of configurable properties.

[ 1 | 2 | 3 ]

If you have read this article you may be interested to view :

Learning the Yahoo! User Interface library Develop your next generation web applications with the YUI JavaScript development library
Published: March 2008
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

About the Author :


Books From Packt

Ext JS 3.0 Cookbook
Ext JS 3.0 Cookbook

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

ICEfaces 1.8: Next Generation Enterprise Web Development
ICEfaces 1.8: Next Generation Enterprise Web Development

alt=
Joomla! E-Commerce with VirtueMart

Spring Web Flow 2 Web Development
Spring Web Flow 2 Web Development

Zend Framework 1.8 Web Application Development
Zend Framework 1.8 Web Application Development

Oracle SOA Suite Developer's Guide
Oracle SOA Suite Developer's Guide

Spring 2.5 Aspect Oriented Programming
Spring 2.5 Aspect Oriented Programming

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software