Adding a header widget in your Thematic child-theme

I’ve been building lots of wordpress sites lately and have been loving the thematic framework. I install the theme and then make my edits in a custom child theme. I’ve begun seeing a few things I end up doing in nearly every site and I wanted to share them because finding out exactly how to do it was a bit like finding a needle in a haystack.

The first one I’ll share is related to creating an extra widget area. I know thematic already has a ton of widget areas. I needed a spot in the header to easily update and add elements. It’s a place that commonly holds links, search boxes, phone numbers etc, and normally it’s ok hard coding that into the theme. But what about when it changes? I always try to empower my clients with the option of making tweaks like this on their own. I have found that it keeps them happy, as they don’t get billed or have to wait for me, and it keeps me happy, since that’s really not what I want to spend my time doing. I try to make my sites the kind that I need to do the heavy lifting and some instruction at launch, but then the client is in control and can maintain the site. Of course I explain that if they break it and I have to come in to fix it, then those are billable hours, anyways… that’s another post for another day. I wanted to give the header area (normally to the right of the logo but above the navigation) a widget area. It turns out that it is really a simple few lines of code put into the child-themes functions.php file to do it!

[cc lang=”php”]
// Add Widget area in header
function add_header_aside($content) {
$content[‘Header Aside’] = array(
‘args’ => array (
‘name’ => ‘Header Aside’,
‘id’ => ‘header-aside’,
‘before_widget’ => thematic_before_widget(),
‘after_widget’ => thematic_after_widget(),
‘before_title’ => thematic_before_title(),
‘after_title’ => thematic_after_title(),
),
‘action_hook’ => ‘thematic_header’,
‘function’ => ‘thematic_header_aside’,
‘priority’ => 0,
);
return $content;
}
add_filter(‘thematic_widgetized_areas’, ‘add_header_aside’);

// And this is our new function that displays the widgetized area
function thematic_header_aside() {
if (is_sidebar_active(‘header-aside’)) {
echo thematic_before_widget_area(‘header-aside’);
dynamic_sidebar(‘header-aside’);
echo thematic_after_widget_area(‘header-aside’);
}
}
[/cc]

I know I got this code from someone in some forum somewhere, but it was a long search, and I couldn’t find it again when I looked, so whoever you are, thanks! I usually end up putting a search widget in the header and a phone number or other contact links or rss links and it’s become pretty standard in my toolkit. Hope it helps!

Better jquery mega-menu tutorial

My earlier simple mega menu implementation post displayed some simple css and jquery to explode a standard navigation menu into a mega-menu… I’ve made it even better. My biggest issue with that implementation was that it did not keep the order like you’d expect. It read left to right in columns rather than down each column. In the example you can see the first column of three would read from the top: a, d, g, j… this could potentially be confusing. So I wanted to update it to keep the order better and just stack the columns of elements rather than the elements themselves.

I used some different jquery to execute this. First we walk through the menu elements and calculate which column they should be in. We basically map that element’s (li)index to the column it should be, some big math. Luckily I had some experience from actionscript in my arsenal doing just that, so porting the function to javascript I was ready to go. If your number X falls between A and B, and you would like to convert it to Y which falls between C and D follow this formula: Y = (X-A)/(B-A) * (D-C) + C. Plugging this function in and cancelling out the zeros and adding some rounding to get integers I got: Math.floor((liindex / $total * $cols)+1). Using this I added a class to each ‘li’ designating which column it should be in, and then used wrapAll to wrap them into column divs. Very simple and a much better implementation overall anyways. Better code, better user experience… what more can you ask… so here’s the example and jquery code. I’m thinking I should make this into a jquery plugin or something, any thoughts?

better-mega-menu-screenshot

See the mega menu in action

Javascript code

[cc lang=”javascript”]
jQuery(document).ready(function() {
//clean up the row of the mega menu. add css class to each element on bottom row.
//only if more than 7 elements. if more than 16, mm-3
jQuery(‘#nav li ul’).each(function(ulindex, ulele){
$total = jQuery(this).children(‘li’).size();
if ($total <= 7) { jQuery(this).addClass('mm-1'); } else { $cols = Math.floor(($total) / 8) + 1; $remainder = $total % $cols; $rows = Math.ceil($total / $cols); jQuery(this).addClass('mm-' + $cols + ' total-' + $total + ' rem-'+$remainder );jQuery(this).children().each(function(liindex, liele){ //alert("total: "+$total+", remainder: "+ $mod+", ulindex: "+ulindex+", liindex: "+liindex); //If your number X falls between A and B, and you would like to convert it to Y which falls between C and D follow this formula: Y = (X-A)/(B-A) * (D-C) + C. jQuery(this).addClass('col-' + Math.floor((liindex / $total * $cols)+1) ); if( (liindex+1) % $rows == 0) { jQuery(this).addClass('last'); } });for (var colcount = 1; colcount<= $cols; colcount++){ jQuery(this).children('.col-'+colcount).wrapAll('

‘);
}
}
});
});
[/cc]

css

[cc lang=”css”]
ul { list-style:none; }

/********** < Navigation */ .nav-container { float:left; background: #398301; margin: 10em 0; width: 960px; } #nav { border: 0px none; padding:3px 0 2px 44px; margin:0; font-size:13px; }/* All Levels */ #nav li { text-align:left; position:relative; } #nav li.over { z-index:999; } #nav li.parent {} #nav li a { display:block; text-decoration:none; } #nav li a:hover { text-decoration:none; } #nav li a span { display:block; white-space:nowrap; cursor:pointer; } #nav li ul a span { white-space:normal; }/* 1st Level */ #nav li { float:left; } #nav li a { float:left; padding:5px 10px; font-weight:normal; color: #fff; text-shadow: 1px 1px #1b3f00; } #nav li a:hover { color: #fff; text-shadow: 1px 1px 3px #ccc; } #nav li.over a, #nav li.active a { color:#fff; }/* 2nd Level */ #nav ul { position:absolute; width:15em; top:26px; left:-10000px; border:1px solid #1b3f00; border-width: 0 1px 2px 1px; background:#398301; padding: 6px 0 6px; } #nav ul div.col { float:left; width: 15em; } #nav ul li { float:left; padding: 0; width: 15em; } #nav ul li a { float:none; padding:6px 9px; font-weight:normal; color:#FFF !important; text-shadow: 1px 1px #1b3f00; border-bottom:1px solid #1b3f00; background:#398301; } #nav ul li a:hover { color:#fff !important; text-shadow: 1px 1px 3px #ccc; background: #2b6301; } #nav ul li.last > a { border-bottom:0; }
#nav ul li.last.parent > a { border-bottom:0; }

#nav ul li.over > a { font-weight:normal; color:#fff !important; background: #1b3f00; }
#nav ul.mm-1 { width: 15em; }
#nav ul.mm-2 { width: 30em; }
#nav ul.mm-3 { width: 45em; }
#nav ul.mm-4 { width: 60em; }
/* 3rd+ leven */
#nav ul ul { top:-6px; background: #1b3f00; }

/* Show Menu – uses built-in magento menu hovering */
#nav li.over > ul { left:0; }
#nav li.over > ul li.over > ul { left:14em; }
#nav li.over ul ul { left:-10000px; }

/* Show Menu – uses css only, not fully across all browsers but, for the purpose of the demo is fine by me */
#nav li:hover > ul { left:0; z-index: 100; }
#nav li:hover > ul li:hover > ul { left:14em; z-index: 200; }
#nav li:hover ul ul { left:-10000px; }
[/cc]

Download

Visit this demo page and view source or save as…

A simple mega menu implementation with CSS and jquery

I’ve been skinning quite a few ecommerce sites with the magento platform and wanted a simple way to explode the navigation menus. Some sites end up getting a long list of categories and sub-categories, so I wanted to do a mega-menu style navigation. One way to do it was to rewrite the html code for the navigation and pop each column into another nested unordered list. I’m not a fan of doing this because one – I didn’t want to manipulate the html. I like the simplicity of ul navigation with a clear flat list of li elements. Of course for nested sub-navigation any li can contain another ul. I wanted to just use some css and maybe javascript to visually accomplish the same thing. I also wanted it to be portable, so I could take it and use it on a wordpress install or even a plain html site. I went to my favorite: jquery. I knew there was a likely plugin out there already that would do something similar, but nothing after my initial search, but I realized that it was a simple procedure and mostly accomplished with some css.
mega menu screenshot
I’ll walk you through the process here and let you inspect the code yourself and see it in action on the demo page. Assign each ul to be a default width of 15em, then each li element we float:left and also give it a width of 15em. This way we can change the ul width to 30em and automatically I have 2 columns! Assigning the nested ul a specific width according to it’s class is done through css, mm-0 will be 15em and incrementally each next one will be 15em more. mm-1 is 30 and mm-2 is 45. Then we use jquery to determine the number of elements in the list and assign it a class accordingly. This involves some math and some preferences. Using the magic ui number 7, I determined that a menu with more than 7 elements should explode into multiple columns. So anything less than or equal to 7 I assign the class ‘mm-1’ which in the css sets the width to the standard 15em (ie 1 mega menu column). More than 7 should pop into columns no more than 8 tall. So dividing the total by 8 will give us the number of columns we want. We’ll add a class of mm-x, where x would be the number of columns. And the li elements will float to the left and fill in the space in columns.
One specific issue is the last element in the menu, sometimes we need to style that element differently. I’ll loop through each child of the nested ul element and if it is on the bottom row apply a class of ‘last’. But this was a little tricky in calculating which would be last because were never sure how many elements there will be or how many columns. I just used the remainder after dividing the total by the number of columns, then if the remainder could be used to know which elements are on the bottom row.

OK, now that that’s out of the way, let’s look at the code.

HTML

This I won’t show, you can inspect the source of the demo if you wish to see it, it a basic nested collection of unordered lists. It’s the standard that is created by magento, wordpress and most other CMS platforms.

CSS

[cc lang=”css”]
html, body { margin:0; padding:0; }
ul { list-style:none; }

/********** < Navigation */ .nav-container { float:left; background: #186C94; margin: 10em 0; width: 960px; } #nav { border: 0px none; padding:3px 0 2px 44px; margin:0; font-size:13px; }/* All Levels */ #nav li { text-align:left; position:relative; } #nav li.over { z-index:999; } #nav li.parent {} #nav li a { display:block; text-decoration:none; } #nav li a:hover { text-decoration:none; } #nav li a span { display:block; white-space:nowrap; cursor:pointer; } #nav li ul a span { white-space:normal; }/* 1st Level */ #nav li { float:left; } #nav li a { float:left; padding:5px 10px; font-weight:normal; color: #fff; text-shadow: 1px 1px #111; } #nav li a:hover { color: #fff; text-shadow: 1px 1px 3px #ccc; } #nav li.over a, #nav li.active a { color:#fff; }/* 2nd Level */ #nav ul { position:absolute; width:15em; top:26px; left:-10000px; border:1px solid #104A65; border-width: 0 1px 2px 1px; background:#186C94; padding: 6px 0 6px; } #nav ul div.col { float:left; width: 15em; } #nav ul li { float:left; padding: 0; width: 15em; } #nav ul li a { float:none; padding:6px 9px; font-weight:normal; color:#FFF !important; text-shadow: 1px 1px #111; border-bottom:1px solid #104A65; background:#186C94; } #nav ul li a:hover { color:#fff !important; text-shadow: 1px 1px 3px #ccc; background: #135575; } #nav ul li.last > a { border-bottom:0; }
#nav ul li.last.parent > a { border-bottom:0; }

#nav ul li.over > a { font-weight:normal; color:#fff !important; background: #104A65; }
#nav ul.mm-1 { width: 15em; }
#nav ul.mm-2 { width: 30em; }
#nav ul.mm-3 { width: 45em; }
#nav ul.mm-4 { width: 60em; }
/* 3rd+ leven */
#nav ul ul { top:-6px; background: #104A65; }

/* Show Menu – uses built-in magento menu hovering */
#nav li.over > ul { left:0; }
#nav li.over > ul li.over > ul { left:14em; }
#nav li.over ul ul { left:-10000px; }

/* Show Menu – uses css only, not fully across all browsers but, for the purpose of the demo is fine by me */
#nav li:hover > ul { left:0; z-index: 100; }
#nav li:hover > ul li:hover > ul { left:14em; z-index: 200; }
#nav li:hover ul ul { left:-10000px; }
[/cc]

Javascript

Don’t forget to include jQuery (I prefer using the google hosted version at http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js)
[cc lang=”javascript”]
jQuery(document).ready(function() {
//clean up the row of the mega menu. add css class to each element on bottom row.
//only if more than 7 elements. if more than 16, mm-3
jQuery(‘#nav li ul’).each(function(ulindex, ulele){
$total = jQuery(this).children(‘li’).size();
if ($total <= 7) { jQuery(this).addClass('mm-1'); } else { $cols = Math.floor(($total) / 8) + 1; $remainder = $total % $cols; jQuery(this).addClass('mm-' + $cols + ' total-' + $total + ' rem-'+$remainder );jQuery(this).children().each(function(liindex, liele){ //alert("total: "+$total+", remainder: "+ $mod+", ulindex: "+ulindex+", liindex: "+liindex); if( liindex + $remainder >= $total || $remainder == 0 && liindex + $cols >= $total ){
//alert(“total: “+$total+”, remainder: “+ $remainder+”, index: “+liindex);
jQuery(this).addClass(‘last’);
}
});
}
});

});
[/cc]

See the demo in action

Flashvars and as3

flashvars_as3_thumbFlashvars and actionscript 3! Flashvar is a way that in your html embed codes (object tags) you can send variables and values into your swf file. These variables can then be grabbed internally and used your programming! Examples of these could be images that you want to use in your swf but don’t want to import or hardcode them into the flash file or paths to xml or flv files to use as well. Actionscript 3 has a different procedure than as2 did as to how you read these flashvars from the actionscript side. The embed codes and html side of things are still the same, but in case your new to actionscript altogether, I’ll give an example of the html as well. [cc lang=”html”] [/cc] In actionscript 3 we use the loaderInfo object to access the flashvars. The parameters Object of the loaderInfo will contain all the flashvar variables and values. [cc lang=”actionscript”] this.loaderInfo.parameters [/cc] As an example of something that is visual I’ve created this little app to read some options from flashvars about colors. An app that will read a list of colors and update a box that is on the stage already to those colors with the specified delay. I always have fun with randomness so I threw in the option for random colors as well. This file looks for certain flashvars: color, loop, delay and random. These are the keys or names of the variables and they are followed by the values you want them to hold. Note that flashvars can be set in any order, so you don’t have to start with color and end with random. In this example I’m looking for 4 flashvars specifically (in any order):

  • colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0x000000 in flash) (default is random)
  • loop:Boolean – whether or not to repeat these colors (default is true)
  • delay:Number – the delay between colors (in seconds). (default is 1 second)
  • random:Boolean – determines whether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false)

This is much more than is required for this example, but I was having fun playing with random colors and timing and options. I figured it doesn’t hurt to show the effect you can have with a couple different variables on one file. Here is an example using the object tags above: [kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/12/flashvars_as3.swf” width=”200″ height=”200″ targetclass=”flashmovie” fvars=”colors=0xFF0000,0x0FF000,0x00FF00,0x000FF0,0X0000FF,0xF0000F&delay=.66&loop=true&random=false”] Get Adobe Flash player [/kml_flashembed] And here are some more (please don’t have a seizure!) Here’s the full source if you’re interested: [cc lang=”actionscript”] /* circlecube.com App to demonstrate the process of getting flashvars from embed code to actionscript (as3) Displays colors specified. looking for 4 flashvars specifically (in any order): colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0x000000) (default is random) loop:Boolean – wether or not to repeat these colors (default is true) delay:Number – the delay between colors (in seconds). (default is 1 second) random:Boolean – determines wether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false) */ //initialize vars var myflashvars:Object = new Object() var myColors:Array = new Array(“random”); var myLoop:Boolean = true; var myDelay:Number = 1; var randomOrder:Boolean = false; var allRandom:Boolean = false; //read flashvars in actionscript3 //if colors flashvars doesn’t exist use these defaults if (!this.loaderInfo.parameters.colors){ myflashvars = {colors: “random”, delay: 1}; } else{ myflashvars = this.loaderInfo.parameters; } //assign flashvars to variables within flash for (var item:String in myflashvars) { trace(item + “:\t” + myflashvars[item]); if (item == “colors”){ myColors = myflashvars[item].split(‘,’); } else if(item == “loop”){ myLoop = parseBoolean(myflashvars[item]); } else if(item == “delay”){ myDelay = myflashvars[item]; } else if(item == “random”){ randomOrder = parseBoolean(myflashvars[item]); } } //use my variables! if (myColors[0] == “random”){ allRandom = true; } var counter:Timer = new Timer(myDelay * 1000); counter.addEventListener(TimerEvent.TIMER, nextColor); trace (“color number: 0”, “color hex: “+myColors[0]); setColor(myBox, myColors[0]); counter.start(); stop(); function nextColor(e:Event):void{ //cycle through colors if (!allRandom && !randomOrder){ if (counter.currentCount+2 > myColors.length){ if (myLoop == true || myLoop == “true”){ counter.reset(); counter.start(); } else{ counter.stop(); } } trace (“color number: “+counter.currentCount, “color hex: “+myColors[counter.currentCount]); setColor(myBox, myColors[counter.currentCount – 1]); } //randomly select a color from the myColors array else if (!allRandom && randomOrder){ var randomColor = Math.floor(Math.random() * myColors.length); trace (“random number: “+randomColor, “color hex: “+myColors[randomColor]); setColor(myBox, myColors[randomColor]); } //randomly create colors else{ trace (“number: “+counter.currentCount, “color hex: “+myColors[0]); setColor(myBox, myColors[0]); } } function setColor(item:DisplayObject, col):void{ if (col == “random”){ setRandomColor(item); } else{ setHexColor(item, col); } } function setHexColor(item:DisplayObject, col:Number):void { var myColor:ColorTransform = item.transform.colorTransform; //check color bounds if (col > 16777215) col = 16777215; else if (col < 0) col = 0; myColor.color = col; item.transform.colorTransform = myColor; } function setRandomColor(item:DisplayObject):void{ setColor(item, (Math.floor(Math.random() * 16777215))); } function parseBoolean(str:String):Boolean { switch(str.toLowerCase()) { // Check for true values case “1”: case “true”: case “yes”: return true; // Check for false values case “0”: case “false”: case “no”: return false; // If all else fails cast string default: return Boolean(str); } } [/cc]

Tutorial to Create a Responsive Image Scroller in ActionScript 3.0

responsive-images-scroller-as3-thumb

I’ve written a tutorial which is published over at flash.tutsplus. This tutorial demonstrates how to create a horizontally scrolling image viewer and covers xml parsing, loading and resizing external images, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

So check out the Tutorial to Create a Responsive Image Scroller in ActionScript 3.0 over at flash.tutsplus.com!

sourcedemomilestone

You’ll find full source code available for download as well as the demo files and step by step milestones all throughout the tutorial.

Forthcoming Actionscript Image Scroller Tutorial

image-scroller-thumbnail

Here is a preview of a file I’m writing a tutorial for. It’s nothing groundbreaking, but it deals with many normal tasks and will show my process a bit. This tutorial will show how to create a horizontally scrolling image viewer. It will cover xml loading & parsing, loading & resizing external images to fit into a scrollable container, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Let me know what you think, and if there’s anything you want specifically mentioned/explained in it I’ll do my best! Or if you have any ideas of how this could be improved.

Update: The article/tutorial has now been published follow the link to theTutorial to Create a Responsive Image Scroller in ActionScript 3.0

Stock Flash Site, Introducing 'BuyStockFlash.com'

Buy Stock Flash


Sell & Buy Flash

Buy or Sell, Start Now –

Stock Flash – Royalty Free Stock Flash effects, Video, Audio

The New Kid on the block… it’s good to see some competition coming to the stock flash world. BuyStockFlash is revving it up. They are positioned to provide a place where flash-ers can upload components, templates, utilities, flv & mp3 players, logos & icons and any other flash elements to sell and earn at least 50% from the proceeds. I haven’t yet uploaded any files, but will once I have some time to do so. They also have a pretty rewarding affiliate program! They let the site speak for itself, displaying a gallery of available files on the homepage. The site just started last fall, is based in Prauge and since they have expanded to become buystocknetwork, including a site for flash, design templates, and sound files!

While the content is still somewhat bare, I’ve seen a few items that are top shelf! I see a lot of potential in this site! Good luck to them and to you, enjoy BuyStockFlash!

Actionscript Drag & Drop Tutorial | Vertical and Horizontal Flash Sliders

as3dragdrop-slider png A specific use of drag and drop which is a bit more complicated than your average drag & drop needs is a slider. You can use components, but I usually prefer using my own graphics and code, partly because the components tend to bloat the filesize of the swf and partly because that’s just how I am, I like to make it myself. Many projects I’ve worked on require sliders as a form of user input, such as a volume control in my video player, or the inputs for my Voter’s Aide app that let users assign value to issues in the 2008 presidential election. I figured I’d just pull out the code I used with the sliders there, since it was already done. The issue with sliders is we need to restrict the dragging to a certain area, which in itself is a line of code, but I also prefer to allow users to click the actual bar as well for quick selection.

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/05/as3dragdrop-sliders.swf” targetclass=”flashmovie” useexpressinstall=”true” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Vertical Slider Steps

The vertical slider here goes from 0 – 100. We need to drag the handle but have it restricted to the slider, so users won’t be confused when they click and drag the handle off the slider and break it. We want to click the background bar of the slider and have the handle snap to that place, and we need to be able to see what value the slider holds (0 – 100). I made this code to be pretty reusable, as long as the slider is set up in similar fashion.

  1. Make graphics for slider bg and handle
  2. Put the graphics into a slider mc
  3. Place them each at 0,0 and center their registration points (for easier control and code later)
  4. Assign button mode to handle and bar (for better usability)
  5. Add Mouse Down Event Listener for handle and bar and assign press function
  6. In bar press function set position of handle according to mouse position, and then call the handle press function
  7. In handle press function remove the Mouse Down listeners and add stage mouse event listeners for both mouse Up and Move (Stage listeners emulate onReleaseOutside (from as2) and also provide more accurate results)
  8. Define dragging area as a rectangle(x, y, width, height), if you’ve do the set up earlier it should be close to Rectangle(0,0,0,slider.bar.height);
  9. Begin dragging handle and apply the drag area limiting rectangle
  10. Mouse Move function find value (should simply be the handle’s y position) and updateAfterEvent for smooth animation
  11. Mouse Release function remove stage listeners, re-add the listeners to the slider and stop dragging

Actionscript (as3)


// Vertical Slider
sliderVertical.handle.buttonMode = true;
sliderVertical.bar.buttonMode = true;
sliderVertical.handle.addEventListener(MouseEvent.MOUSE_DOWN, verticalHandlePress);
sliderVertical.bar.addEventListener(MouseEvent.MOUSE_DOWN, verticalBarPress);

function verticalBarPress(e:MouseEvent):void{
sliderVertical.handle.y = sliderVertical.mouseY;
verticalHandlePress(e);
}
function verticalHandlePress(e:MouseEvent):void {
sliderVertical.handle.removeEventListener(MouseEvent.MOUSE_DOWN, verticalHandlePress);
sliderVertical.bar.removeEventListener(MouseEvent.MOUSE_DOWN, verticalBarPress);
stage.addEventListener(MouseEvent.MOUSE_UP, verticalHandleRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, verticalHandleDrag);
//limit dragging area
var verticalDragArea:Rectangle = new Rectangle(0, 0, 0, -sliderVertical.bar.height+1);
sliderVertical.handle.startDrag(false, verticalDragArea);
}
function verticalHandleRelease(e:MouseEvent):void{
stage.removeEventListener(MouseEvent.MOUSE_UP, verticalHandleRelease);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, verticalHandleDrag);
sliderVertical.bar.addEventListener(MouseEvent.MOUSE_DOWN, verticalBarPress);
sliderVertical.handle.addEventListener(MouseEvent.MOUSE_DOWN, verticalHandlePress);

sliderVertical.handle.stopDrag();
updateVNumber();
}
function verticalHandleDrag(e:MouseEvent):void{
e.updateAfterEvent();
updateVNumber();
}
function updateVNumber():void{
sliderVertical.sliderValue = sliderVertical.stat.htmlText = Math.abs(sliderVertical.handle.y);
sliderVertical.stat.y = sliderVertical.handle.y - sliderVertical.handle.height/2;
}

Horizontal Slider Steps

Pretty much the same as the vertical slider, but adjust heights and y positions to widths and x positions. Note in this example I have a range of (-100 to 100) and to accomplish the bar I just reused the same on flipping it around, so here we have the handle, the barLeft and the barRight. I use both of these combined to calculate the limiting rectangle area.

Actionscript (as3)


// Horizontal Slider
sliderHorizontal.handle.buttonMode = true;
sliderHorizontal.barLeft.buttonMode = true;
sliderHorizontal.barRight.buttonMode = true;
sliderHorizontal.handle.addEventListener(MouseEvent.MOUSE_DOWN, horizontalHandlePress);
sliderHorizontal.barLeft.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
sliderHorizontal.barRight.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);

function horizontalBarPress(e:MouseEvent):void{
sliderHorizontal.handle.x = sliderHorizontal.mouseX;
horizontalHandlePress(e);
}
function horizontalHandlePress(e:MouseEvent):void {
sliderHorizontal.handle.removeEventListener(MouseEvent.MOUSE_DOWN, horizontalHandlePress);
sliderHorizontal.barLeft.removeEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
sliderHorizontal.barRight.removeEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
stage.addEventListener(MouseEvent.MOUSE_UP, horizontalHandleRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, horizontalHandleDrag);
//limit dragging area
var dragArea:Rectangle = new Rectangle(-sliderHorizontal.barLeft.width+1, 0, sliderHorizontal.barLeft.width+sliderHorizontal.barRight.width-2, 0);
sliderHorizontal.handle.startDrag(false, dragArea);
}
function horizontalHandleRelease(e:MouseEvent):void{
stage.removeEventListener(MouseEvent.MOUSE_UP, horizontalHandleRelease);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, horizontalHandleDrag);
sliderHorizontal.handle.addEventListener(MouseEvent.MOUSE_DOWN, horizontalHandlePress);
sliderHorizontal.barLeft.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);
sliderHorizontal.barRight.addEventListener(MouseEvent.MOUSE_DOWN, horizontalBarPress);

sliderHorizontal.handle.stopDrag();
updateHNumber();
}
function horizontalHandleDrag(e:MouseEvent):void{
e.updateAfterEvent();
updateHNumber();
}
function updateHNumber():void{
sliderHorizontal.sliderValue = sliderHorizontal.stat.htmlText = sliderHorizontal.handle.x;
sliderHorizontal.stat.x = sliderHorizontal.handle.x - sliderHorizontal.handle.width;
}

Source

source as3dragdrop-sliders.fla file

Flash Drag and Drop Tutorial | startDrag Actionscript

I find that Drag and Drop is the most intuitive form of user interaction (at least using a mouse). Actionscript has some of this functionality built in, with the interactive functions startDrag and stopDrag, these can help make our coding pretty easy. If you are transitioning from as2, the code was incredibly simple:

Actionscript2

[cc lang=”actionscript”]
on (press) {
startDrag (this);
}
on (release, releaseOutside) {
stopDrag ();
}
[/cc]
On the movie clip action panel you’d just put that script, which is actually pretty readable even if you don’t know code. The releaseOutside is to keep from the clip missing the release event, because sometimes if a user released the mouse button but was not currently over the clip being dragged for whatever reason, it will not stop dragging.

Actionscript 3

drag-drap-as3-ballSome things have changed with as3, other than the actual coding structure, the biggest change for me doing drag and drop in the new actionscript was that the mouse events have changed. There is no more a press or release. They were replaced with, MOUSE_DOWN and MOUSE_UP. There is no more releaseOutside either and this one is a little more complicated to find among the new MouseEvent list.
Leaving it out works, but we still have the same problem. Check out the working example below and try dragging the red ball to the green or yellow one and drop it there. Since the green is above the red in the layer sequence, the mouse is over the green and when the MouseEvent.MOUSE_UP fires, it’s not on the red ball but on the green, so we don’t get to the code that drops the red ball. So the red ball code basically has times when the dragging sticks even after we release the mouse button. Not to mention the dragging is very jumpy!
[cc lang=”actionscript”]
ballRed.addEventListener(MouseEvent.MOUSE_DOWN, dragRed);
ballRed.addEventListener(MouseEvent.MOUSE_UP, dropRed);
function dragRed(e:MouseEvent):void{
ballRed.startDrag();
}
function dropRed(e:MouseEvent):void{
ballRed.stopDrag();
}
[/cc]

Using the Mouse Move event will help us to customize our behavior a bit more. Plus I wanted to get a more abstract level to it, so I could apply the event listeners to any display object and use the event properties to target the right clips. We begin the drag with the Mouse Down, and the create some other eventListeners for the stage that will watch the Mouse Move and Up events. So clicking on the green or yellow ball, fires the grabMe function which sets the me variable (which will hold any object) to the current target of the event, which should always be the object that you click. So we are using the same code for both the green and yellow ball. I’m a big fan of code consolidation and reuse, it takes a little more effort, but the code is much more clean and portable even. Then we add the event listeners for the stage on MOUSE_MOVE and MOUSE_UP. So first, mthe dragMe function, just says to update after event. This makes the animation smoother cause it only updates the display after the event completes it’s process. Then the drop me function is attached to the stage, so anywhere you release the mouse, the object will stop dragging, plus we remove the stage event listeners and add back the listener for the original object (me). Note the buttonMode property as well, this will make the cursor turn to a hand when you hover that object.
[cc lang=”actionscript”]
ballYellow.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
ballYellow.buttonMode = true;
ballGreen.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
ballGreen.buttonMode = true;

var me:Object;
function grabMe(e:MouseEvent):void{
me = e.currentTarget;
me.removeEventListener(MouseEvent.MOUSE_DOWN, grabMe);
me.startDrag();
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMe);
stage.addEventListener(MouseEvent.MOUSE_UP, dropMe);
}
function dropMe(e:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragMe);
me.stopDrag();
me.addEventListener(MouseEvent.MOUSE_DOWN, grabMe);
}
function dragMe(e:MouseEvent):void {
e.updateAfterEvent();
}
[/cc]
This functionality is much smoother and then when I want to add more code to the dragging or dropping, I have a place to do it already!

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/04/as3dragdrop-ball.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Source

as3dragdrop-ball.fla

How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_tut png
One of the best features of the flash player if you’re doing video is the fullscreen functionality. It has been a question I’ve heard repeatedly. There are limits to what you can do in fullscreen. Such as minimal keyboard support while in fullscreen. But it is perfect for a video player! Who doesn’t want to see a video expanded to full screen mode?

There are a couple things to consider when coding fullscreen into your flash. Remember the hard coded “Press Esc to exit full screen mode.” that Adobe has placed into the flash player. This is untouchable by developers, and the function returns to normal stage display state. So we call the function to go fullscreen, but the exit fullscreen has already been written for us. This can pose a problem though, when we need the player to do something when we exit fullscreen, that is when we want it to do something more than the generic black box function adobe includes.

Steps

  1. specify stage properties
  2. full screen button and listeners
  3. stage fullscreenEvent listener
  4. (functions for each)
  5. allowfullscreen = true

Example

[kml_flashembed fversion=”9.0.28″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/03/fullscreen_tut.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″ allowfullscreen=”true”]Get Adobe Flash player

[/kml_flashembed]

1. Stage properties exist that allow us to specify what type of fullscreen we want.  We can have the swf scale to fit the fullscreen area (StageScaleMode.SHOW_ALL), not scale at all (StageScaleMode.NO_SCALE), skew to fit fullscreen (StageScaleMode.EXACT_FIT), and scale to fill fullscreen area (Stage.ScaleMode.NO_BORDER).  We may also edit the alignment of the stage in the fullscreen area; in this example I’m using TOP, but refer to documentation for more options

2. Adobe has placed restrictions on when a swf can enter fullscreen, and has deemed that it must result from a user interaction, a mouse click or keystroke. So create your buttons (or keyListeners). I prefer to have one button to enter fullscreen and another to exit, and have them both call the same function to toggle fullscreen. It gives a clearer communication to the user. I then control the visibility of these buttons depending on the current display state of the stage.

3. Another listener to watch the stage dispaly state. stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange); This will fire every time the stage display state changes. We need this because as I mentioned earlier, when entering fullscreen we use our own function, but the ‘hit esc to exit fullscreen’ functionality is built into the flash player, we can’t update our stage layout or button visibility without watching to catch when the display state is changed. Using this method we can update our stage layout any and every time.

4. Of course flesh out the fullscreenToggle function to include anything else you need.

5. Lastly, for a SWF file embedded in an HTML page, the HTML code to embed Flash Player must include a ‘param’ tag and ’embed’ attribute with the name ‘allowFullScreen’ and value ‘true’, like this:

<object>
    ...
    <param name="allowFullScreen" value="true" />
    <embed ... allowfullscreen="true" />
</object>

The allowFullScreen tag enables full-screen mode in the player. If you do everything else right and don’t include this in your embed codes, fullscreen will not work. The default value is false if this attribute is omitted. Note the viewer must at least have Flash Player version 9,0,28,0 installed to use full-screen mode. Also note that  the simple (ctrl + enter) testing your movie in flash will not allow fullscreen either, you must use the debug tester (ctrl + shift + enter) … or go open the published swf in flash player.

Actionscript

[cc lang=”actionscript”]
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP;

var stageDisplayAdjustCounter:uint = 0;

fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);

fsb.buttonMode = true;
ssb.buttonMode = true;

//fullscreen buttons need this to adjust the stage display state.
//pressing escape to exit fullscreen bypasses this function
function fullscreenToggle(e:MouseEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. fullscreenToggle from “+stage.displayState+”\n”);
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
//here we subtract 1 from the counter because it has already incremented (in onFullscreenChange) when we set the display state above

status.appendText((stageDisplayAdjustCounter-1)+”. fullscreenToggle to “+stage.displayState+”\n”);
status.scrollV = status.maxScrollV;

}

//this function is called every and anytime the stage display state is adjusted
//either by pressing our buttons or
function onFullscreenChange(e:FullScreenEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. onFullscreenChange\n”);
status.scrollV = status.maxScrollV;
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
fsb.visible = false;
ssb.visible = true;
}
else {
fsb.visible = true;
ssb.visible = false;
}

stageDisplayAdjustCounter++;
}

onFullscreenChange();

[/cc]

Source

Download fullscreen_tut.fla file