How to Position Movie Clips Based on Browser Resizing

Flash ActionScript 2.0

It’s not hard to make a SWF resize itself to the dimensions of the browser.  All it takes, in fact, is to set the width and height attributes of the HTML’s <object> <param> element and/or <embed> element to 100%.  There are a number of ways to determine the SWF’s display, too:  show all (default) makes the entire movie visible while maintaining the original aspect ratio of the SWF (if the browser’s aspect ratio differs, you’ll get the equivalent of “letterbox” borders either horizontally or vertically); no border gets rid those potential borders, but may crop parts of the SWF instead; exact fit distorts the SWF, if necessary, to make the entire movie visible without borders or cropping.  See Adobe TechNote 12701 for complete details.

Fine and good.  Now, what if you want to allow the Stage to resize, but not its contents?  What if you want to adjust the position of various movie clips — such as a logo, navigation, or content area — in response to the Stage’s new dimensions as the browser is resized?  Luckily, that’s not hard either.  :)   Let’s take a look. 

An answer, short and sweet

Open a new FLA and draw a quick shape — a circle will do.  Convert the shape to a movie clip (Modify > Convert to Symbol…, then choose Movie Clip) and give the clip an instance name via the Property inspector.  For this example, let’s call it mcLogo.

Create a scripts layer and type the following into frame 1:

Stage.scaleMode = "noScale";
Stage.align = "TL";
var stageListener:Object = new Object ();
stageListener.onResize = positionContent;
Stage.addListener(stageListener);

function positionContent():Void {
   mcLogo._x = Stage.width - mcLogo._width;
   mcLogo._y = Stage.height - mcLogo._height;
}
positionContent();

Test your SWF, and you’ll see the circle hug the lower right corner as you resize the SWF’s dimensions in Flash.  Either that, or publish to an HTML file and set the width and height attributes for both the <option> <param> element and the <embed> element to 100% and resize the browser.

How it works

In the first line, we’re telling the SWF not to scale itself.  In your HTML — this is important — you’re going to set the width and height to 100%, but the SWF itself will not scale to fit those dimensions.  In the second line, we’re telling the SWF to register itself to its upper left (top left) corner.

Next, an arbitrarily named variable, stageListener, is declared as a generic Object instance.  This object acts as an “ambassador” for the Stage.onResize event, so we need to assign a function to a new onResize property of our object, rather than of Stage directly.  In this example, the function is arbitrarily named positionContent() and is defined shortly below.  Note:  if you like, you may assign a function literal …

stageListener.onResize = function() {
  // instructions here
}

… but in this case, I chose a named function because you may want position dozens of movie clips, and it’s arguably “cleaner code” to define the function separately.  If you go the named function route, as we’re doing, make sure to omit the parentheses in this line, as shown.

The next line adds our ambassador as a listener to the Stage.  The Stage.addEventListner() method is what “wires up” the listener object to the object that dispatches the event (here, the Stage).

Finally, the custom positionContent() function tells mcLogo what to do.  In this case the movie clip’s _x property is set to the width of the Stage minus its own width.  That makes it hug the right side.  To center this clip, you could set its MovieClip._x property to half the Stage’s width minus half its own …

mcLogo._x = Stage.width / 2 - mcLogo._width / 2;

Follow suit for vertical positioning.  Makes sense, right?  Be sure to call the positionContent() function after you declare it, to make sure everything is positioned at the start, otherwise the Stage/browser would have to resize first.

By the way, this setup expects movie clips to be registered to their upper left corners.  If mcLogo’s shape was centered horizontally in its own timeline, you would only have to minus half its width from the Stage’s width to make it hug the right hand side.  If you want a 20 pixel buffer between this right-aligned clip and the Stage, account for that extra 20:

mcLogo._x = Stage.width - mcLogo._width - 20;

To keep a clip to the left side, set its _x to 0.

Keep in mind, you’re not limited to setting MovieClip._x and _y properties.  You may adjust a clip’s _width, _height, _xscale, _yscale … whatever you like.  Experiment and have fun with it!  For every clip you wish to position, simply add its entry to the positionContent() function.  Note, below, that an mcNav clip is being set to a position based on the original mcLogo clip.  Here, both clips would hug the right edge of the Stage, and mcNav would float below mcLogo, with a buffer of 20 pixels.

function positionContent():Void {
  mcLogo._x = Stage.width - mcLogo._width;
  mcLogo._y = 20;
  mcNav._x = Stage.width - mcNav._width;
  mcNav._y = mcLogo._y + mcLogo._height + 20;
}

Note:  See How to Fix Wrong-sized SWFs in Firefox to work around a common issue with 100%-sized SWFs in Firefox.  (Thanks for the cross-reference suggestion, Markus!)

154 Responses to “How to Position Movie Clips Based on Browser Resizing”

  1. Markus Mathieu Says:

    Hi David,
    I think you really should link this to your entry about sizing full-browser swfs in Firefox (or all browsers in standards compatible mode).

    There is another thing I’d like to forget about this issue:
    If your in “strict” mode, you will have to set the css display value to “block” for your swf (#mySWF {display:block}) otherwise there will be some pixles reserved for baseline which will make scrollbars appear etc.

  2. David Stiller Says:

    Markus,

    Thanks! Great idea.

  3. Patrick Loza Says:

    I found this tuturial to be very valuable. I have a few questions though. Can you help me with the scripts that will position a mc exactly in the center of the resized browser (both horizontal and vertical)? Also, the script to have elements resized, scaled with the browser, for example a header or footer or background image?

  4. David Stiller Says:

    Patrick,

    The basis for positioning of any kind is accomplished in three steps.

    1. Preparation of the Stage, done with these two lines:
      Stage.scaleMode = "noScale";
      Stage.align = "TL";
    2. Handling of the Stage.onResize event, done with these three lines:
      var stageListener:Object = new Object ();
      stageListener.onResize = positionContent;
      Stage.addListener (stageListener);
    3. Definition of the positionContent. This is where your questions come into play.

    Can you help me with the scripts that will position a mc exactly in the center of the resized browser (both horizontal and vertical)?

    For that, use the code suggested halfway into the “How it works” section; just make sure to apply it to both _x and _y. Assuming a movie clip with the instance name mcLogo, registered to its own upper left corner …

    mcLogo._x = Stage.width / 2 - mcLogo._width / 2;
    mcLogo._y = Stage.height / 2 - mcLogo._height / 2;

    Those two lines would go inside your declaration for the positionContent() function.

    Also, the script to have elements resized, scaled with the browser, for example a header or footer or background image?

    Scaled and resized in what way? :)

    If you scale a movie clip along its x-axis, but leave the y-scale as is, that movie clip will appear horizontally stretched (or squished) most of the time. This doesn’t much matter for swaths of solid color, but it would certainly look wrong if that clip contained text. If your header contains both textual (or image) elements and a background element, you might consider separating the elements into separate movie clips and stretching your background element only.

    mcBackgroundRect._width = Stage.width;

    Make sense?

    Or, if you want to maintain aspect ratio, arbitrarily note the change ratio of one axis and apply that same change ratio to the other.

    // First, adjust width
    mcBackgroundRect._width = Stage.width;
    // Second, note radio along this axis
    var ratio:Number = mcBackgroundRect._xscale;
    // Third, apply this same change to the other axis
    mcBackgroundRect._yscale = ratio;
  5. Moonwalker Says:

    Very nice article. Thank you very much. I still have a question though. I’m planning to make a website like: http://www.2advanced.com. As you can see they have a full browser flash website. My question is: How can I get a background like they use? I tried your solution but it does not work at all.

    Besides…How do they get the scrollbar? I tried to make the height of the stage 1200 px but when published there is no scrollbar and the things at the bottom of the page are not visible. Unless you hit the right mouse button and choose the option “show all”.

    Is that a different approach for the problem?

    I would be very grateful if you could explain it to me.

    Thanks in advance.

  6. David Stiller Says:

    Moonwalker,

    The 2advanced site doesn’t appear to be using Stage.onResize at all. :) They’re just publishing a very large SWF and letting the browser handle it (with scrollbars, if necessary) as the browser would handle any large content.

    If you publish to percentages, then the SWF will be resized and you won’t see scrollbars (unless they’re inside Flash). You can use your browser to view the HTML source and see that they’re using SWFObject to embed the SWF. Although width if set to 100%, the height is a pre-determined 1000 pixels.

    The “show all” you mentioned isn’t currently showing, but in cases when it goes, that’s just the Flash Player overriding what the browser’s width and height (or zoom) specify.

    To achieve what they’re doing, you wouldn’t have to use the technique described in the article … just don’t publish with percentages. If you wanted the content to actually respond to the browser, you’d need Stage.onResize after all. Make your background image a movie clip (even if it’s originally a large JPG, or the like) and center it both horizontally and vertically.

  7. Moonwalker Says:

    Thank you very much David for your quick reply. I’m adding your blog to my Bookmarks and I will give it a try.

    Thank you again and wish you many luck in your life. ;)

    Bye.

    mw

  8. Jenny Says:

    Hi David,

    I need some insight on how you would handle an issue:

    1. I need a website with a changeable background. Thus, i have a mc that uses system.capabilities on clip event. This would fill up the entire screen, allowing me to animate the background
    2. For the above to happen, I would need to publish flash in noscale mode
    3. All is fine, BUT you can’t scroll the page, and i need to be able to scroll this

    I would like to know how would you approach this situation….thks!

    Best,
    Jen

  9. David Stiller Says:

    Jen,

    Flash generally allows several ways to accomplish a given goal. If the Flash content (the SWF) truly needs to be full screen, then yes, it will have to be embedded in the HTML at 100% width and height, which means the HTML won’t scroll. You could experiment with 100% width and a hard-coded height. I haven’t tried that, but that might work. You could set the SWF’s background as transparent and put your background image in the HTML document itself (see WMODE information here; use the ExternalInterface class to talk to JavaScript if you need to manipulate the external background image programmatically). You might also take a look at the ScrollPane UI Component: use that to load either external SWFs or content from the Library — resize that with Stage.onLoad as needed (use the ScrollPane.setSize() method) and it’ll scroll its contents.

  10. Flash Hints » Blog Archive » Actionscript to center content on a 100% width and height background Says:

    […] I accomplished this goal using actionscript. First I started with David Stiller’s quick tutorial on resizing movie clips on stage resize here. I will paste all the code I used here which started from David’s and was modified with my own. Stage.scaleMode = “noScale”; Stage.align = “TL”; var stageListener:Object = new Object (); stageListener.onResize = positionContent; Stage.addListener(stageListener); […]

  11. full-page flash « The not-so-Real Life of Digitalemma Says:

    […] i asked Mel if she knew how to do this, she pointed me to these references: david stiller’s blog mm livedocs […]

  12. pirco Says:

    hi david,
    i very much liked your clear explanation about the fixed position of a movieclip.

    now i’m in a situation where i need to get a movieclip to stick to a specific position relative to the edge of the browser window. so in this case, the movie will not be published at 100% instead it will be a very large stage (something like 2400×1600 or crazy like that). anyway, this will cause scrollbars, of course, and my movieclip still needs to always stick to about 20px above the bottom scrollbar.

    you might know the effect of the “floating div” in HTML, a DIV that always stays in position, no matter where you scroll to.

    well, do you think it’s possible to do that in flash?

    thanks in advance for your insight.

    pirco

  13. David Stiller Says:

    pirco,

    The System.capabilities object lets you know the user’s full screen dimensions, but that doesn’t help in this case. That’s too bad.

    Those scrollbars you’re talking about are the property of the browser, not the SWF, so ActionScript has no direct access to them. Once you leave the realm of Flash, this sort of thing gets considerably more complex! I haven’t personally tried what you describe, but it may be possible with communication between ActionScript and JavaScript, which you could manage with ExternalInterface. You’d have to let the SWF know the dimensions of the browser’s viewport area and then alert the SWF every time the browser changed size or was scrolled. Sounds like a cool thing to experiment with!

  14. pirco Says:

    yes. thanks. i thought about it some more and, of course, there would have to be that bridge between the browser and flash… javascript. yes.
    i think i know what to do. i’ll try to send samples.

    thanks again for quick answer. i’m starting to like this blog!

  15. David Stiller Says:

    Thanks, pirco! If you come up with something and would like to share, please feel free. My evenings are completely eaten up over the next couple months on a project I can’t mention quite yet, but will. Neat stuff on the way. ;)

  16. oiram Says:

    Hi David, nice article. Thanks so much. I have a question, how do i achieve to put “little animation” to code. Let’s say I’ve designed a menu box, which always sticks to bottom of the page. And I want to have this box to come on its postion 1sec or 2 secs later, after browser window was resized.

    Same, like on this website, http://www.captaincomatose.com/cc01_content.html - the sign formular on the bottom.

  17. David Stiller Says:

    oiram,

    Ah, I see what you’re saying. That captaincomotose site is pretty cool! Well, there are two things going on there (two things at least). First, that site is handling the Stage.onResize event — that much is clear — second, rather than using a function like the above positionContent(), it’s using some sort of delay mechanism. Chances are good the mechanism is either the setInterval() or the setTimeout() function.

    Either one of those will trigger whatever function or method you like after a given amount of time. I would think that site uses clearInterval() and/or clearTimeout() to stop the timer in case someone changes the browser after an interval has already been set in motion — otherwise the animations would occur, perhaps when they shouldn’t, even when someone fires the Stage.onResize repeatedly.

    Take a look at the Tween class (Components Language Reference), which makes it relatively easy to animate movie clips with ActionScript. You could have setTimeout() trigger the Tween.start() on a given Tween instance associated with one of your movie clips.

  18. Serge Says:

    I have a problem.

    After
    1). I click the right mouse button and choose the option “zoom in”.
    2). I click the right mouse button and choose the option “show all”.

    listener does not call function onResize

  19. David Stiller Says:

    Serge,

    The Stage.onResize event is dispatched when the Stage changes size — that is, when the dimensions of the Stage change, such as when the browser is resized — but not when it is zoomed. I can see where those events might seem like the same thing, but the Flash Player distinguishes between them. Check the Stage.showMenu property to see how you can turn off the right-click zooming.

  20. Tony Says:

    Dave,

    I’d searched the web for a quick, short PRECISE answer to the question on how to center a published SWF. Yours was the first that I came across that was RIGHT ON THE MONEY!!!! No jibber-jabbing - I love it!

    Thank You!!!!

  21. David Stiller Says:

    Tony,

    Heh, I often do jibber-jabber quite a bit, actually, but I’m glad this article was helpful to you!

  22. Bill Says:

    I am having trouble with the main swf that calls in all the other sub swfs that have different positioning script…for example…whenever i load in any swf with say…”align right”, even though the main is “top and centered”, the whole main movie’s positioning and everything slams to the right.
    But I want one swf to load in “right” and one swf to load in to the “bottom” without messing up the main…ya know?

    Thanks in advance

    Bill

  23. David Stiller Says:

    Bill,

    Given that there’s only one Stage, that does make sense. If loaded SWFs invoke Stage.align and tell it to do otherwise, it must obey.

    Pick one alignment and stick with it, because that sets your movie’s base coordinates. If you want a loaded SWF to position itself to the right, you’ll need to set its _x property to the width of the Stage minus the value of its own width, as shown in the original article with mcLogo.

    Because you’re loading external content, you’ll have to use some mechanism to track its loading, then manipulate its positioning via Stage.onResize after loading is complete.

  24. april Says:

    hello,

    I love this effect. How do you “loadMovie” or load external swfs in to the main movie and have them also move with the stage. I have loaded them into an empty container movie clip and it appears that they aren’t behaving.

    Thanks!

  25. David Stiller Says:

    april,

    The reason they don’t move is one of the hidden “gotchas” of dealing with dynamically loaded content. You’ll have to wait until your external SWFs are fully loaded; only then can you adjust the properties of their container clips.

    If your positionContent function, or something like it, is already in place, you should merely have to set the Stage.onResize event to that function when the content has loaded.

  26. sascha Says:

    hi,
    i think i have kind of the same problem: i want to load a swf-file(very complex with scrollbars and xml) into a container_mc which is centered in the middle of the browser/player with “onResize”.
    first all the functions like scroller and external loaded data didnt worked at all until i changed all the paths in the swf to “_root.container_mc…”
    when i now resize the browser/player, the container_mc and its whole content disappears very random-like.
    where do i have to place the loadMovie-action or is it a problem with the absolut paths?? or how can i tell flash to NOT take attention to the external data in the swf, because if i dont load external data in the container_mc, it works fine!

    thanks for listening to me! sniff.. : /

  27. sascha Says:

    sorry for spaming your blog, but i found a solution myself.
    and for everybody who has the same problem should just put all the data of the external.swf in a content_mc. then load the external.swf in the resize.swf with the onResize-action > loadMovie(”external.swf”,3) and then align the mc in the external.swf to one of the movieclips in the resize.swf, like this:

    loadMovie(”external.swf”,3);
    onEnterFrame = function () {
    if (Stage.height>=615) {
    _level3.content_mc.moveIt(header_mc._x, (Stage.height-600)/2, 2);
    } else {
    _level3.content_mc.moveIt(header_mc._x, 8 , 4);
    }
    };
    MovieClip.prototype.moveIt = function(targetX, targetY, delay) {
    if (this._x != targetX || this._y != targetY) {
    this.onEnterFrame = function() {
    var difX = -this._x+targetX;
    var difY = -this._y+targetY;
    if (Math.round(Math.abs(difX))>0 || Math.round(Math.abs(difY))>0) {
    this._x += difX/delay;
    this._y += difY/delay;
    } else {
    this._x = targetX;
    this._y = targetY;
    delete this.onEnterFrame;
    }
    };
    }
    };

    ////
    voilà!!
    flash can be so annoying and not logical at all!!! :@
    but lucky us that there is always a way to trick flash. : P

  28. Ozgurerdogan Says:

    Great blog. I am newbie at flash and trying to fit a background at any resulotion just like at : http://www.butspace.com/dupont/livingtomorrow/
    Thanks in advance.

  29. David Stiller Says:

    To sascha …

    flash can be so annoying and not logical at all!!! :@

    Hehe … well, I think that’s occasionally true, but as long as you can find a way to make it work, the bills get paid. :) Glad you found a solution that worked for you.

    To Ozgurerdogan …

    That Dupont site is really just using a whopping large image. It will fit nicely into many resolutions, but if you go high enough you’ll see the edges. The easiest way to center an image this big is to wrap it in a movie clip and set its registration point to its center (rather than upper left), then position it at half of the Stage’s width by half of the Stage’s height.

  30. Nick Baker Says:

    Alright, I was wondering how I would go about having this container resize when the site is resized to fit the browser window. Basically I want all of the images in the container to resize to the new browser size but I want the copy to stay consistent no matter what browser window it is in. How would I go about achieving this resize? Currently I can get it to position whereever I want, I just can’t get it to resize automatically when the browser window is enlarged. Thanks in advance for your help

  31. David Stiller Says:

    Nick,

    Just as you can update a container clip’s position (MovieClip._x and _y), you can update any other read/write property of that container, such has _width, _height, _xscale, or _yscale. If you want that container clip to be half the width of the Stage, you might do this:

    containerClip._width = Stage.width / 2;

    Now, doing so is going to affect that movie clip’s _xscale property (horizontal scale) by a certain amount. If half the Stage’s width happens to be twice the original width of the movie clip, its _xscale property will be 200 (that’s 200%). In order to keep that movie clip from looking stretched, you’ll want to set its _yscale property to the same value.

    containerClip._width = Stage.width / 2;
    containerClip._yscale = containerClip._xscale;

    Make sense?

  32. Nick Baker Says:

    I’m following you 100%, thank you for your help. I’ll get on it right now. Thanks again for taking the time to respond.

  33. Linda Fiske Says:

    I have been unsucessfully trying to find out the answer to this question through many newgroups and forums and after reading your blog, it seems you would be the person to help.

    I have an all flash site (embedded as a large swf into a 1 column/1 row table in an html file) published as 100% of browser window and would like to know how to keep a slide show (movie clip) within the large swf from resizing so the photographs in the slide show won’t distort when the swf enlarges.

    I want the movie clip to remain a certain distance from the vertical and horizontal center of the large swf.

    Is this possible and does it use code similar to what you are describing above?

    Thanks in advance for any help.

  34. David Stiller Says:

    To Nick …

    Glad to hear it! :)

    To Linda …

    What you’re after is definitely possible. The first step is to is tell the Stage itself not to scale, even if the SWF — as embedded in your percentage-based HTML — does. Then, use the Stage.onResize event, as described in the article, to adjust the MovieClip._x and _y properties of that slideshow clip as desired.

  35. Linda Fiske Says:

    Thank you. I will try that and let you know. I am happy to know it is possible. Again, thanks.

    Linda

  36. David Stiller Says:

    Linda,

    Sure thing!

  37. kineticKlash Says:

    David,

    i would like to know how it is posible for a movieclip to move (at ease) or in a certain speed to the position assigned in the _X & _Y when the browser is resized. I’ve seen this in many websites and i can’t seem to find a good response.

    Thanks!

  38. kineticKlash Says:

    I found a good link where it explained a bit on how it can be done! thanks anyhow! :)

  39. David Stiller Says:

    kineticKlash,

    Hey, glad you found your answer — and sorry I’ve been delayed in replying to comments lately. :) I imagine the link you found will lead you toward notifying the movie clip of its new desired location, then using a standard easing algorithm to get it there. The trick is to make sure your Stage.onResize event handler stops any easing already in progress (in case the user resizes several times in a row) or isn’t thrown off by an adjustment to the destination coordinates.

  40. Marc Says:

    How can I get my Movie Clip to stay at the bottom on a full-page flash screen? Can you post the scrpt I need to use to get this effect?

    Thanks in advanced!

  41. Matthew Says:

    i am looking to create a background like the one used on this site

    http://www.letstakepictures.info/index.php

    when you resize the browser the image gets smaller but never distorts and stretches. id love to know how this is done.
    Ive looked at the source and its uses 100% width and height but the image does not stretch. Is there code i could add to a movieclip or give an instance to, and code it to go fullscreen like shown with whatevers in it?

    Im really sorry if this topic has already been covered here ive read through everything and cant find one similar except the 2advanced website used as an example and that didnt help me :(
    thank you

  42. David Stiller Says:

    To Marc …

    To make a movie clip stay on the bottom, use the Stage.onResize event to set the movie clip’s _y property to the height of the Stage minus the clip’s own height.

    myClip._y = Stage.height - myClip._height;

    To Matthew …

    When you say you looked up the source, do you mean you had access to the ActionScript inside the FLA file (or an external AS file)? I wonder if you’re talking about the HTML, which unfortunately isn’t going to tell you how the Flash content is programmed.

    In any case, you can maintain an image’s aspect ratio by sizing one axis first, then setting the other axis to the same percentage of scale. For example …

    myClip._width = Stage.width;  // or any number
    myClip._yscale = myClip._xscale;

    That will keep the image from distorting. To me, it looks like they’re setting the image to some percentage of the Stage, rather than a direct correspondence, but you could experiment with that. You would do this resizing inside the custom positionContent() function shown above.

  43. adam Says:

    hi david. i’m just wondering how i make a mc stay at the top of the screen and centred? thanks for a great tutorial - most helpful.

  44. adam Says:

    ah, got it! set _y to 0. thanks david!

  45. David Stiller Says:

    adam,

    Bingo! :)

  46. Can you help? Says:

    Hi David, wonderful site you have.
    I would not bother you with this but I have tried so hard for about 20 hours to do something that may be simple for yourself. I wondered if you could advice me on this?

    i have to put 2 movie clips on my site. The background is one and the site content is the other.

    the background has to be full screen. it needs to resize but never show the edges of the image. i can do this in the publish settings.

    the main content has to stay the same size as it includes all the pixel fonts etc and i can position it perfectly having followed your super advice above.

    the trouble i have is that as soon as i put the two together it doesnt work. the background returns to its original size.

    this must be because of the Stage.scaleMode = “noScale”;

    i have gone thru your advice above so many time but simply can get a suitable solution. is there any chance you could advise me on how to achieve this?

    i appreciate your time - you’re the best!

    Kevin

  47. javier Says:

    hello david, first i wanna say that your site helps me a lot, im not a flash expert and its great to hace such a resource

    im trying to layout a site similar to this http://www.minus.dk/
    i follow your tips and i almost there, the only thing i don´t get its how to get the bg image scale down only to a certain point, so if the browser aspect ratio its different that the image it stops scaling down and keeping the windows filled with the image.

    sorry my english, im from argentina
    thank you!

  48. David Stiller Says:

    To Kevin …

    I hear what you’re saying, and you nailed it: by setting Stage.scaleMode to "noScale", which is what you need in order for the Stage.onResize event to work, you’re overriding the environment that allows your background to resize itself. What you need, then, is to program that background movie clip to resize. If you don’t care that the background squashes/stretches, you can simply set its _width and _height to match that of the Stage:

    // Inside the positionContent() function ...
    bgClip._width = Stage.width;
    bgClip._height = Stage.height;

    If you do care — meaning, you want to maintain the background’s aspect ratio — see my reply to Matthew on June 19.

    To javier …

    For something like this, you could use the Math.max() method, which returns the larger of two numbers provided to it. For example, if you want your background to always be at least 300 pixels wide, you could do this …

    // Inside the positionContent() function ...
    image._width = Math.max(Stage.width, 300);
    image._yscale = image._xscale

    Make sense?

  49. javier Says:

    yes, makes sense, but no matter with number i choose, there´s always a portion of the screen that would not be filled because the code is maintaining the aspect ratio.

    the example site i put before, it seems like the “stage.scalemode” is set to “noBorder”, thats the behavior i need in the background, but if i choose “noborder” the movieclips scale too.

    many thanks for answering!

  50. David Stiller Says:

    javier,

    Gotcha. In that case, you may want to choose a percentage of the Stage slightly higher than 100%.

    // Inside the positionContent() function ...
    image._width = Math.max(Stage.width * 1.2, 300);
    image._yscale = image._xscale
  51. M.A. Turner Says:

    Here you go guys. A super simple way to acheive relative aspect ratio. Dave, sorry if there are double posts, Safari crashed on me.

    Stage.align = "TL";
    Stage.scaleMode = "noScale";
    Stage.showMenu = false;
    _global._focusrect = false;
    _global._quality = "BEST";
    this._lockroot = true;
    
    function set_stage() {
      // SET THE ASPECT RATIO
      original_width = 320;
      original_height = 240;
    
      scale_width = Stage.width/original_width;
      scale_height = Stage.height/original_height;
    
      if (scale_width>scale_height) {
        new_ratio = scale_width;
      } else {
        new_ratio = scale_height;
      }
    
      // THE CLIP YOU WANT TO SCALE
      my_mc._width = original_width*new_ratio;
      my_mc._height = original_height*new_ratio;
    }
    
    Stage.addListener({onResize:set_stage});
    
    set_stage();
    
    stop();
  52. javier Says:

    another way, similar but shorter

    Stage.align = "TL";
    var stageListener:Object = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    
    function positionContent():Void {
      mybg._width = Stage.width;
      mybg._yscale = mybg._xscale;
      if (mybg._height < Stage.height) {
        mybg._height = Stage.height;
        mybg._xscale = mybg._yscale;
      }
    }
    positionContent();
  53. David Stiller Says:

    M.A. Turner and javier,

    Thanks so much for the input, both of you! I dig this sort of interaction. :) Makes blogging pretty cool.

  54. Linda F. Says:

    Hi David:

    Forgive me if this is a really basic question, but I keep getting the following error message when I cut and paste the code above into frame 1 of an actions layer. I have only a beginning knowledge of action script so haven’t been able to figure out what to tweak. Can you help?

    Thank you.
    Linda

    Scene=Scene 1, Layer=Layer 2, Frame=1: Line 7: ‘{’ expected
    function positionContent():Void {

    Scene=Scene 1, Layer=Layer 2, Frame=1: Line 10: Unexpected ‘}’ encountered
    }

    1. Stage.scaleMode = “noScale”;
    2. Stage.align = “TL”;
    3. var stageListener:Object = new Object ();
    4. stageListener.onResize = positionContent;
    5. Stage.addListener(stageListener);
    6.
    7. function positionContent():Void {
    8. mcLogo._x = Stage.width - mcLogo._width;
    9. mcLogo._y = Stage.height - mcLogo._height;
    10. }
    11. positionContent();

  55. David Stiller Says:

    Linda,

    The errors messages in Flash are something of a mixed bag. They can often be helpful, but the “[some punctuation] expected” messages are often misleading, because they result from something else.

    I copy/pasted the code from the blog entry into a new FLA and, for me, the code didn’t generate errors, so I wonder what’s going on here. The curly brace characters are definitely in the right place.

    It would be a bit tedious, but have you tried carefully typing in the code snippet, line by line? I’m wondering if somehow the copy/paste introduced an incorrect line break or unexpected character.

  56. foss t. Says:

    hallo, this is actually my first ever post in a flash related forum… but i ve been bending backwards to find an answer to this but i cant…
    i use slightly different code but even when i follow what you outline i still come up to the same problem…
    namely, what happens when you stage align to “BL”..
    this is either very bizarre or i am overlooking something completely obvious..
    it seems that the x axis scales properly but the y doesnt follow..
    so if i have Stage.align to BL and a place an mc with _x=Stage.width-20 lets say, thats works fine.. but, same scenario,.. if i try to place an mc with _y=0 then this is placed where the actual stage size of the flash file is…

    same thing happens with your example when i use the exact same code but change the “TL” to “BL”…
    makes any sense?

    and the thing is.. it should work..
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

  57. David Stiller Says:

    foss t.,

    Just for clarity, this isn’t actually a Flash forum. ;) This is my personal/professional blog, so I’m the only one who “officially” answers questions here, though I always welcome helpful input.

    Setting the Stage.align property to anything but “TL” is fine, but it means you’ll have to reconsider your math. With “TL”, the main movie’s point of alignment — its registration point, so to speak — is the upper left corner. Since Flash counts horizontally up to the right and vertically up in the direction of down, the math shown above works without a hitch. If you set the registration point to “BL”, which is bottom left, the zero point (the starting point) is now at the bottom of the screen, so you’ll have to count backwards rather than forwards for the y axis.

  58. Aaron G Says:

    Hi David. I’ve read through all of the Q & A listed here so far and I’m still experiencing problems. The website i am working on is entirely contained in one swf. the swf size is 1024×768. I think i need to use “noBorder” to entirely fill the page with the swf. My problem is the cropping that occurs. I also would like to limit the size that you can scale the swf to - in other words - i don’t want to be able to scale it to smaller than say, 640×480. I can’t seem to get the Math.max to work properly. Is there a way to fill the browser window completely with no cropping of the swf while maintaining the relative aspect ratio when scaling?

    thanks for your time!

  59. David Stiller Says:

    Aaron,

    For the Stage.onResize event to do its thing, you’re really going to need to set the align property to “noScale” — use CSS in your HTML document to get rid of the page border …

    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>

    To limit scaling, you might use an if statement along the lines of, say …

    if (Stage.width >= 640) {
      mcLogo._x = Stage.width - mcLogo._width;
    } else {
      mcLogo._x = 640 - mcLogo._width;
    }

    … or, even better, Math.max() or min(), as you alluded to …

    mcLogo._x = Math.max(
      Stage.width - mcLogo._width,
      640 - mcLogo._width,
    )

    The trick may be to talk it through, like a word problem. “I want this logo to never get pulled in tighter 640 pixels. That means I want its minimum distance from the left to be 640 minus its own width — but it should always take the maximum dimensions it can.”

  60. Aaron G Says:

    thanks again! i appreciate the super-fast response time!

  61. David Stiller Says:

    Aaron,

    Sure thing. :) Response time is luck of the draw, I’m afraid. I’m always glad to help, though, when I can.

  62. Aaron G Says:

    Hi again! So far I have everything basically working the way i want it to…except the movie clip using the onResize doesn’t appear in the browser window until the widow has been resized. is there a fix for this?

  63. David Stiller Says:

    Aaron,

    You betcha. That’s why the resizing mechanics are stored inside a named function. After you define the positionContent(); function, call it. That will make it do its thing immediately — and the Stage.onResize event handler is what makes it do its thing when the Stage resizes.

  64. Jarrad Says:

    Hey David… Big wraps- Very helpful gear. Look my question is, I’m getting a handle on the basic full screen “browser” coding but i am still trying to figure out how to animated ” transitions” of objects to different x & y around the “stage”. For example move objects on and off the screen in full screen mode. Any help would be great ;)

  65. David Stiller Says:

    Jarrad,

    Animation can be a challenge to combine with the Stage.onResize event, mainly because you have to write your code in such a way that repeated triggering of the positionContent() function (or whatever equivalent) doesn’t upset the animation itself: the Stage’s width and height may change at any moment, so you may (for example) send a movie clip to 500px from the left over a period of 20 seconds, and yet within 10 seconds, the browser has been narrowed to 400px wide. Obviously, your movie clip will not be visible when it comes to its stopping place.

    It may help to think in terms of percentages, sending objects to a sliding scale of destination points, based on Stage width and height. You can certainly animate your objects independently of the Stage.onResize event. You might use setInterval() or the MovieClip.onEnterFrame event — anything can repeatedly trigger a function. You might also check into the Transition class, which facilitates scripted animation, or (even better), The Fuse Kit. If your Stage alignment is set to “TL,” then anything less than zero will be above the Stage or to the left, out of sight. Anything greater than the current Stage.width and height properties will be below the Stage or to the right, out of sight. (And again, that’s the tricky part.)

  66. TicoXXX Says:

    Hi Mr. Stiller,
    How can I keep the image background from stretching when resizing the browser window, anotherwords like this website: www.zinkmag.com/
    notice how the menus stay in true size and centered, the menus on my code are in hello_mc and bkgrnd is the background image. Here is the code I have:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;

    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent():Void {
    bckgrnd._width = Stage.width;
    bckgrnd._height = Stage.height;
    //hello_mc._width = Stage.width ;
    ///hello_mc._height = Stage.height;

    hello_mc._x = Stage.width / 2;
    hello_mc._y = Stage.height -322;

    }

    positionContent();

  67. David Stiller Says:

    TicoXXX,

    See my reply to javier, back in June 25, 2007; plus, there are a cluster of comments during that time for other approaches. The easiest way I can think of is to set the width of your image (its MovieClip._width property) based on the Stage’s width (or some fraction of the Stage’s width, as you please). Doing so will affect that image’s MovieClip._xscale property. To maintain aspect ratio, set the image’s MovieClip._yscale to the same value.

    hello_mc._width = Stage.width;
    hello_mc._yscale = hello_mc._xscale;
  68. anthony scotti Says:

    David, I am having some trouble with an empty movie clip situation. I am creating a site for a photographer who wants many galleries with many pictures on each gallery. I have figured out how to call the jpgs into an empty movie clip from an outside folder. the issue I am having is this: how do I adjust the size of the movie clip to fit each picture? I’m sure I can adjust the size of the horizontal pics to fit the mc, but it’s the vertical pics that will mess that theory up. so I need to know how to get the empty mc to adjust to each individual jpg called into it. I will explain how I have the layers of the flash project laid out. The 1st layer is the loader with the empty mc, the next layer is for the thumbnails (buttons) that have the actionscript on each one to call the jpgs in and out. Do you think you can help me out with this? It will be greatly appreciated and would really pull me out of a big hole. Thank you for your time. Respectfully, Anthony Scotti

  69. Nicholas Monsour Says:

    Hi David,

    I am very inexperienced with actionscript in general, but I have been experimenting with a full window flash movie. My movie consists of a background animation which I would like to resize as the browser window is resized, but with menu bar and other clips above it that I would like to stay the same size and in the same position. The intro to this site has what I am talking about: http://www.thenorthatlantic.com/.

    I have been able to make this work with the positioning using the code you posted above, but not with width or height. I cannot find any tutorials that deal with keeping the size of objects the same whil others resize, and I’m almost ready to give up!

    So again, a background mc that resizes and foreground mcs that do not. HELP!

    -Nick

  70. David Stiller Says:

    To anthony …

    I have figured out how to call the jpgs into an empty movie clip from an outside folder. the issue I am having is this: how do I adjust the size of the movie clip to fit each picture?

    Assuming you haven’t changed the scale of your previously empty movie clip — this container clip — then any new JPGs you add to it will change the dimensions of that clip by virtue of being present. In other words, a new empty movie clip has a width and height of 0 x 0. If you load a 120 x 180 image into that clip, its new dimensions become 120 x 180. If you add a second image of the same dimensions and position it 10 pixels to the right of the first, the new dimensions of the container clip become 250 x 180 (that’s twice 120 plus the 10px gap between them, and the same height for both).

    I think what you’re after then, really, is nothing more than repositioning your container clip as new images are added, though it’s entirely possible I haven’t correctly envisioned your goal in my mind’s eye.

    To Nicholas …

    As it turns out, you can use the repositioning technique to adjust dimensions / scale in the same way as position. Rather than setting an object’s _x and _y properties, experiment with its _xscale and _yscale or _width and _height properties (see the relevant class file, such as MovieClip, to see what properties the object at hand supports).

    If your Stage.scaleMode is set to “noScale” (which it needs to be for Stage.onResize to work), then none of your content will scale unless you tell it to. Whatever you want to see enlarged or reduced will configured in relation to the current dimensions of the Stage, which can be gleaned from the Stage.width and Stage.height properties. Check out my earlier reply to TicoXXX to see one way to resize something while respecting its aspect ratio.

  71. timteka Says:

    hi. i still can’t center my movieclip. it has mask and mask dimensions don’t equal to its content dimensions. so i gonna center the movieclip according to the mask, not to its real _width and _height. but i can’t figure out how to make this reposition.

  72. Nicholas Monsour Says:

    Hi David —

    your are really good at this, and I cant believe you’re helping so many people all the time! That said, my flash movie still wont do what I want. I’ve got two movieClips — one called “jellyfish” that I want to resize and stay in the same aspect ratio, and one called “text” that I want to not rescale or reposition. The trouble is that whenever I tell “jellyfish” what to do via the positionContent function, the “text” movieClip also recales. Here’s the code I’m using:

    Stage.align = “TL”;
    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent():Void {
    jelyfish._width = Stage.width;
    jellyfish._yscale = jellyfish._xscale;
    }

    positionContent();

    Any idea why I can’t make it work?

    -Nick

  73. David Stiller Says:

    To timteka …

    Consider wrapping your masked movie clip inside another movie clip. That’s step one. Give this container movie clip an instance name so you can control it with ActionScript. Next, enter its timeline, which puts you back to where you were originally: a movie clip and its mask. Convert the mask to a movie clip as well and give it an instance name.

    Now you have three movie clips: the container, the mask, and the movie clip content. Your positionContent() function will set the _x and _y position of the container, but it will take its _width and _height measurements from the mask:

    function positionContent():Void {
      container._x = Stage.width / 2 - container.mask._width / 2;
      container._y = Stage.height / 2 - container.mask._height / 2;
    }

    To Nicholas …

    Chin up! :)

    Looking at your code, I don’t see any reference to a text field — only to jellyfish — so I wonder if jellyfish actually contains that text? If so, the text will resize with its container. You’ll have to either set the text movie clip in the same timeline as jellyfish (rather than inside jellyfish’s timeline) or type additional code to compensate the text’s inherited scaling.

    The only other thing I can see is that you haven’t set the Stage.scaleMode property to “noScale” — without that, everything in the SWF is going to scale automatically.

  74. Nicholas Monsour Says:

    Thanks for trying — I think I need to go back over some of the AS basics!

  75. David Stiller Says:

    [Follow up on Nicholas’s file.]

    It turns out the publish settings for Nick’s FLA were configured for ActionScript 1.0, which means he had to drop this strong typing. That worked, but then his jellyfish file would occasionally show letterboxing — black stripes around the bottom or right side, depending on the aspect ratio of the browser — so I suggested the following:

    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    
    function positionContent() {
      var ratio = Math.max(
        Stage.width / jellyfish._width,
        Stage.height / jellyfish._height
      );
      jellyfish._yscale *= ratio;
      jellyfish._xscale *= ratio;
    }
    positionContent();
  76. Barton Smith Says:

    Hey David,
    Good work with the blog, it’s great that you’ve been so generous answering all the questions. I’ve gone through all the comments, learning new things and fixing problems, however I am stuck with two.

    The file can be seen here:
    http://members.optusnet.com.au/expansiondesign/Website%20V6/

    Related code:
    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener: Object = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent():Void {
    background2._width = Stage.width;
    background2._height = Stage.height;
    content.sidebar._x = 0 - 147;
    content.sidebar._y = 0;
    content.sidebar._height = Stage.height;
    content.imagebar._x = content.artwork._x
    content.imagebar._y = content.artwork._y
    content.artwork._x = Stage.width / 2 - content.artwork._width / 2
    content.artwork._y = Stage.height / 2 - content.artwork._height / 2
    }
    positionContent();

    Firstly, the browser has to resize before the icons line up with the top left corner of the image. However I have called positionContent(); content.artwork is the image mc and content.imagebar is the mc containing the two icons (the script is on their parent timeline).

    Second problem is the 5-10px gap on the top and left. I read your entry on full size swfs in firefox and wondered if that is what I’m after. Do I place the code in the published html file? Cos I tried that but no dice. I’m testing it on Safari.

    Another question - if you add a second function (ie positionIntro) later on in the timeline, do you have to create a new Object(); and should it have a different name?

    Thanks so much mate,
    Cheers
    Barton

  77. David Stiller Says:

    Barton,

    Firstly, the browser has to resize before the icons line up with the top left corner of the image.

    That looks like an order-of-execution issue. In your code, you’re adjusting imagebar first, based on the position of artwork — and then you’re updating the position of artwork. Reverse those, and you should see an improvement.

    Second problem is the 5-10px gap on the top and left.

    That’s not the Firefox issue, per se. That’s happening because most browsers, by default, put a bit of padding on the margins of every page. In the CSS for your HTML document — either in an actual CSS file or a <style> tag in the page — you’ll need to set the margin property to 0 for the <body> tag (you’ll see that under the Variations heading of the Firefox article).

    if you add a second function (ie positionIntro) later on in the timeline, do you have to create a new Object(); and should it have a different name?

    There can only be on event handler for the Stage.onResize event at a time. You’re already set up to listen for the event, so if you change your mind in the future (i.e., later in the timeline), just do something like this:

    stageListener.onResize = positionIntro;

    The onResize event is going to fire, regardless. The Stage class is already wired up to listen for it (thanks to Stage.addListener(stageListener);), so you can update what it does by swapping out (re-assigning) a new function.

  78. Barton Smith Says:

    Great got all those problems solved. The reason I was confused with the padding is because I was opening up the html file in TextEdit and it wasn’t showing all the script. Opened in Dreamweaver and it all made sense :D
    Thanks for the quick reply.
    Barton

  79. David Stiller Says:

    Barton,

    Sure thing!

  80. Sherv Says:

    Hey David,

    great post. One question everything works fine, and i’ve added a actionscript inside my background movieclip that changes the images from a XML file to be resized. Problem is it only shows up when i resize my brower window. How do i get it to appear when the browser opens up? many thanks

  81. David Stiller Says:

    Sherv,

    Whatever your custom function is that resizes everything (above, it’s called positionContent()), you’ll need to call that function once in addition to assigning it to the Stage.onResize event. In the original article, you’ll see the function called immediately after it’s defined.

    Does that make sense?

  82. rhanks! Says:

    David,
    I am having troubles with resizing SWF’s loaded into a MC, could you post some code or tutorial that will help with this, I have been stumped on it for a while now!
    T

  83. David Stiller Says:

    rhanks,

    The trick to what you’re after is to hold off on the Stage.onResize event handler until your external content has loaded. Here’s a quick example, based on the code sample in the blog entry:

    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    var listener:Object = new Object();
    listener.onResize = positionContent;
    
    function positionContent():Void {
      mcLogo._x = Stage.width - mcLogo._width;
      mcLogo._y = Stage.height - mcLogo._height;
    }
    
    var mcl:MovieClipLoader = new MovieClipLoader();
    mcl.loadClip("externalImage.jpg", mcLogo);
    
    listener.onLoadInit = function():Void  {
      positionContent();
      Stage.addListener(this);
    };
    mcl.addListener(listener);

    Much of what you see is the same. The Stage listener object is now called listener (instead of stageListener), and I did that merely for clarity’s sake — because I’m using that same object for two events now: Stage.onResize and MovieClipLoader.onLoadInit. Note that the Stage.addListener() method has been moved inside the event handler for onLoadInit. The reason for that is so the onResize business doesn’t happen until the external JPG has loaded into its mcLogo container. The addListener() method for the Stage class adds this instead of listener because it’s inside a function already associated with listener.

  84. Kit Says:

    David,

    Thank so much for all your help thus far.

    I am wondering how to make the centered movie clips stop moving when they reach a a certain browser window size (in other words - when the window has been resized to small)

    I don’t want these objects to keep moving off screen when the window size is decreased. I want them to stop at a certain x and y value.

    From your discussion above with javier, I assumed this might do it….

    navBar._x = Math.max(Stage.width, 200);
    navBar._y = Math.max(Stage.width, 200);

    …but I guess not;)

    How do I achieve this?

  85. David Stiller Says:

    Kit,

    So … the clips move as someone resizes the browser (which is to say, the Stage) … and you’re cool with that — until the user makes the Stage very small. At that point, if the user makes the Stage even smaller, you want the clips to stay put. Is that right?

    If that’s right, keep in mind: the movie clips will disappear under the edge of the browser as the user continues to size the Stage into the smallest configuration it’ll accept. If that’s what you’re after, Math.max() should do it. In your snippet, navBar is set to the greater value between Stage.width and 200. If Stage.width happens to be 500, navBar will be at 500 pixels in. If Stage.width happens to be 400, navBar will be at 400 pixels in — because 400 is bigger than 200 — until Stage.width is finally smaller than 200. At that point, the greater number is 200, so navBar will stay at 200.

    Of course, if navBar’s registration point is on its left edge (upper left corner is standard), you won’t actually see navBar. You may want to do something like this:

    navBar._x = Math.max(Stage.width - navBar._width, 200);

    And then, for navBar._y, you’ll want to compare against Stage.height instead of width.

  86. Kit Says:

    Hmmm, it still isn’t doin what I would like. Maybe I am not describing it very well. I pretty much want it to do the same thing as in this site…

    http://www.chevaldetroie.net/

    Notice how the duck and clouds in the center stop moving when the browser window is reduced to a certain size…

  87. David Stiller Says:

    Kit,

    I really think those ducks and clouds are following the Math.max() strategy. :) If I were doing that site, I would probably put the registration point right in the middle of the movie clip that represents the cluster of clouds. That would make the centering very easy: clouds._x = Stage.width / 2; (as opposed to the usual clouds._x = Stage.width / 2 - clouds._width / 2;).

    When my browser is very wide, the clouds are centered. When I pull my browser narrower, the clouds stay centered up to a certain point. Finally, they stay put and eventually disappear under the right edge of the browser. This tells me they’re being positioned at the greater of two values: either Stage.width / 2 or approximately (looks like) 450px.

    Of course, this is based on the idea that the alignment of the Stage is set to “TL” (top left). You can set your Stage’s alignment to a number of settings, which is basically like setting the registration point of the Stage.

  88. Kit Says:

    OK. I played around a little more and got it. The movie clip with the large glowing effect (which extended much further off the size of the screen) was throwing it off.

    Thanks

    Do you have any idea why my navigation mc buttons are staying highlighted even when I roll off of them? The roll out sequence of frames does not seem to playing out every time. Sometimes it does, but other times the button stays on the “over” state:(

    Kit

  89. David Stiller Says:

    Kit,

    OK. I played around a little more and got it.

    Great!

    Do you have any idea why my navigation mc buttons are staying highlighted even when I roll off of them?

    If I remember right, you’re sending the playhead to a specific frame with gotoAndPlay() on over and on out. As you’ve seen, that’s certainly an approach, but it does tend to “hang” sometimes. You probably have stop() actions in the timelines of your buttons. Rather than stop every time, use an if statement to stop on a certain condition: the condition (which you’ll have to write) that gets set as a variable in your over and out event handlers.

    Please tell me if I’m off base, because I’m going from memory. In the timeline of your buttons, set your first keyframe’s script like this:

    if (!this.over) stop();

    Set the keyframe that represents the over state (highlighted) like this:

    if (this.over) stop();

    Set your last keyframe like this:

    this.gotoAndStop(1);

    In your custom over() and out() functions, replace the gotoAndPlay() statements with play() statements, and update the custom over variable appropriately:

    function over():Void {
      this.over = true;
      this.play();
    }
    function out():Void {
      this.over = false;
      this.play();
    }

    The key here is that custom over variable. When over is true, the timeline for that button still stop, because of the if statement in the middle keyframe of the button’ss (actually a movie clip) timeline. If the user has since removed the mouse, that timeline won’t stop — won’t get hung up — and will simply hit then end and be sent back to frame 1 of that timeline. Opposite for the first keyframe, which checks of over is not (!) true.

  90. Kit Says:

    That worked a treat! Thanks again David.

    Wow, you have helped me so much to understand the little things that I have always wondered about. This industry needs more guys like you who are willing impart of there knowledge. I owe you one!

    Thanks again

    Kit

  91. David Stiller Says:

    Kit,

    Glad to help. :)

  92. Eddy Says:

    Hi David,

    Your blogs are great, thanks for your hard work. I’ve read through all the posts, and tried everything but still cannot get this to work. I know this has been posted, but for some reason my code below isn’t working properly:

    I’d like the background to scale proportionately, which I’ve achieved already. However I’d like it to stop scaling once it reaches a certain point and not scaled the background image once it reaches 400 px in width.

    Can you please help, my code is below:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent() {
    var ratio = Math.max(
    Stage.width / mcBackgroundRect._width,
    Stage.height / mcBackgroundRect._height
    );
    mcBackgroundRect._yscale *= ratio;
    mcBackgroundRect._xscale *= ratio;
    }
    positionContent();

    Thank you…

  93. David Stiller Says:

    Eddy,

    Okay, mcBackgroundRect needs to scale proportionately in response to the browser — but its longest side should never get longer than 400? Here’s one way to do that:

    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    
    var isWiderThanTall:Boolean = mcBackgroundRect._width > mcBackgroundRect._height;
    
    function positionContent():Void {
      if (isWiderThanTall) {
        mcBackgroundRect._width = Math.min(Stage.width, 400);
        mcBackgroundRect._yscale = mcBackgroundRect._xscale;
      } else {
        mcBackgroundRect._height = Math.min(Stage.height, 400);
        mcBackgroundRect._xscale = mcBackgroundRect._yscale;
      }
    }
    positionContent();

    The only thing that changes is a new variable, isWiderThanTall, which determines how the resizing should go later. As appropriate, either mcBackgroundRect’s width or height is set to the smaller value between the Stage’s width or hight and 400. Then the _yscale (or _xscale) property is set to suit.

  94. Eddy Says:

    Hi David,

    Thanks for the quick reply. Please let me clarify what i meant, the image should fill up the whole window, and the image should scale proportinately until it’s dragged down to 800 px in width, or 600 px in height:

    here is my revised code:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent() {

    bgClip._width = Math.max(Stage.width, 800);
    bgClip._yscale = bgClip._xscale;

    logo._width = Stage.width;
    logo._y = Stage.height - logo._height;
    }

    positionContent();

    I’ve managed to get the width working, but when the window goes smaller, there’s white space underneath the image.

    Can you please have a look?

    Thank you…

  95. David Stiller Says:

    Eddy,

    If the browser dimensions ever veer from an 8:6 (i.e., 4:3) ratio, you’re simply going to get a letterbox effect unless you allow the image to spill over past the edges of the Stage. Now it sounds like you want the image to always be at least 800×600, but proportionately larger if the browser is too.

    Assuming your artwork is already equal to or greater than 800×600, the following would do it:

    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    
    function positionContent():Void {
      if (Stage.width > 800 || Stage.height > 600) {
        var ratio = Math.max(
          Stage.width / mcBackgroundRect._width,
          Stage.height / mcBackgroundRect._height
        );
        mcBackgroundRect._yscale *= ratio;
        mcBackgroundRect._xscale *= ratio;
      }
    }
    positionContent();
  96. Eddy Says:

    That is awesome… works like a charm.

    Thank you SO much David, I searched everywhere for this answer and almost pulled my hair out!! I really appreciate your help!

  97. Eddy Says:

    Hi David,

    One more quick question… the image flickers for a split second before it reaches full browser size. Is there a way to get it to be browser size on load?

  98. David Stiller Says:

    Eddy,

    Note that the positionContent() function only does something when the Stage’s dimensions are greater than 800px wide or 600px tall. If mcBackgroundRect is set to those dimensions by default, it should be fine … but you could always set the _width and _height properties of mcBackgroundRect outside of the function. Try preceding the positionContent() declaration with:

    mcBackgroundRect._width = 800;
    mcBackgroundRect._height = 600;
  99. Eddy Says:

    Thanks again for your help David, this has solved the problem. One last question, I have a footer that stays at the bottom of the window when it’s resized, however when the browser window shrinks below 800×600, the footer disappears. Is there a way to have it always at the bottom? My code is below:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    Stage.showMenu = false;
    mcBackgroundRect._width = 800;
    mcBackgroundRect._height = 600;

    function positionContent():Void {
    if (Stage.width > 800 || Stage.height > 600) {
    var ratio = Math.max(
    Stage.width / mcBackgroundRect._width,
    Stage.height / mcBackgroundRect._height
    );
    mcBackgroundRect._yscale *= ratio;
    mcBackgroundRect._xscale *= ratio;

    footer._width = Stage.width;
    footer._y = Stage.height - footer._height;

    }
    }
    positionContent();

    Thanks again,

  100. David Stiller Says:

    Eddy,

    Take your footer movie clip’s positioning instructions outside of that if statement. ;) You want the footer to move in all cases, not just of the Stage is wider than 800 or higher than 600.

    function positionContent():Void {
      if (Stage.width > 800 || Stage.height > 600) {
        var ratio = Math.max(
          Stage.width / mcBackgroundRect._width,
          Stage.height / mcBackgroundRect._height
        );
        mcBackgroundRect._yscale *= ratio;
        mcBackgroundRect._xscale *= ratio;
      }
      footer._width = Stage.width;
      footer._y = Stage.height - footer._height;
    }
  101. Kit Says:

    Hi David,

    I hope you are well.

    A while back on this message board you helped me make some movie clip buttons which did not get stuck when hovered over. This did help somewhat, but the problem is still there. Take at a look for yourself….

    www.motorcademarketing.com

    Is there anything else I can do?

    Thank you

    Kit

  102. David Stiller Says:

    Kit,

    At first, I didn’t see the buttons sticking — the hovering works fine — but then I pretended to actually click one and saw what you’re talking about. This should be easy to fix, actually. :) The problem is that clicking-and-dragging-off causes the button to stick. The reason for that (this is a guess, of course) is that you haven’t written an onDragOut event handler. You’ll want drag outs to the same thing roll outs do, so follow your onRollOut event handler with the following line:

    buttonInstanceName.onDragOut = buttonInstanceName.onRollOut;

    … which performs the same function for both events.

  103. Paul Gemp Says:

    Excellent tutorial, excellent comments…!

    I thought I would find here the solution to the problem I spent the day trying to figure out. But either nobody stumbled on it or it is impossible (I think more too tough for me).

    Centering works flawlessly. The thing is I have inside the centered movie clip a dynamic scrolling text and, depending on its size and position, it makes its container grow, first on the right, then on the left as it scrolls, screwing up the centering big time.

    I already noticed that masked items are included in the width of an object and read the comment about it. I simply don’t know how to deal with it when they’re dynamic. I tried everything I could think of, I’m cooked.

    Thanks,

  104. David Stiller Says:

    Paul,

    I’m not sure I follow 100% what you’re after, but you may want to consider nesting your movie clips in creative ways to achieve your goal. If your text field’s flexible dimensions are upsetting the current centering, try using a different movie clip, also within the main movie clip, as your gauge for width and height.

  105. Jimmy Says:

    I wonder how they do in the Dupont website (http://www.dupontvisual.com/DuPont/LivingTomorrow/) to move the picture when the mouse is getting closer to the border. Any suggestion?

  106. David Stiller Says:

    Jimmy,

    Looks like they’ve got an onMouseMove handler or maybe an onEnterFrame handler that continuously notes the position of the mouse compared with the coordinates of the Stage. That would work independently of the onResize event, as it turns out — wouldn’t depend on it at all. So you could start experimenting in a new FLA file with nothing in it. Write a MovieClip.onMouseMove handler for the main timeline:

    this.onMouseMove = function():Void {
      trace(this._xmouse + ", " + this._ymouse);
    }

    Move the mouse around to see the coordinates of the mouse. What you do with those numbers, of course, is up to your imagination. ;) With a series of if statements, you could determine when the mouse was within range of the corners or edges, then instruct a movie clip (new content you’d have to add) to move in response to that.

  107. Paul Gemp Says:

    It took me most of my free time these last ten days to figure out my apparently ill-described problem and I’m not proud of that. But being self-taught I may miss some essentials which sometimes come to bug me. I will summarize my findings so it might help other wannabe programmers.

    As I mentioned before, a symbol or a movie bigger than its container or or placed outside its container’s boundaries makes the latter grow. What I discovered is that it only grows from its point of origin. Stupidly enough, it took me hours to understand the implication of that: whatever happens inside the container, its point of origin on the stage doesn’t change…

    I made a little demonstration of this behaviour here.

    With that in mind, centering anything is a piece of cake. Instead of using the actual _width and _height of the container in the positionContent() function, store them in variables BEFORE adding or loading anything in it. The centering will be made with the original size of the container, not the size it may grow to with loaded content.

    So simple it hurts.

  108. David Stiller Says:

    Paul,

    It took me most of my free time these last ten days to figure out my apparently ill-described problem and I’m not proud of that.

    Oh man … I hope my earlier reply didn’t discourage you! Looking back on what I wrote, I could call my own reply “ill-described.” ;) I’ve been unusually busy these last several weeks, and it may very well be that I wasn’t in a wakeful state of mind when I read your question.

    For what it’s worth, you shouldn’t feel bad at all about taking ten days to slog through a problem. What you’ve described isn’t out-there at all.

    So simple it hurts.

    Those are the best kind! They stick! :)

    Thanks for following up with your discovery, Paul, and for putting it in exactly the terms you did. I’m confident it’ll be useful to others.

  109. Eddy Says:

    Hi David,

    Thank you again for all your help. I do have one more question, I am really stumped on this one. I am using this code you suggested to load a full screen background image, and it is working perfectly:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener = new Object();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    Stage.showMenu = false;
    mcBackgroundRect._width = 800;
    mcBackgroundRect._height = 600;

    function positionContent():Void {
    if (Stage.width > 800 || Stage.height > 600) {
    var ratio = Math.max(
    Stage.width / mcBackgroundRect._width,
    Stage.height / mcBackgroundRect._height
    );
    mcBackgroundRect._yscale *= ratio;
    mcBackgroundRect._xscale *= ratio;

    footer._width = Stage.width;
    footer._y = Stage.height - footer._height;

    }
    }
    positionContent();

    However, I would like the background image to fade out and fade in another fullscreen background image when the user clicks on a button. Essentially, it gives the user the option to change the fullscreen bkgd image.

    I really have no idea on how to even start, could you please offer some insights?

    Thank you!

  110. Rita Says:

    Hi David,
    I’m facing a very stupid problem, I think,

    I’m using the following code:
    var stageListener:Object = new Object();
    init();
    function init() {
    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    Stage.addListener(stageListener);
    stageListener.onResize = stageResize;
    back1._width = Stage.width;
    back1._height = Stage.height;
    back2._width = Stage.width;
    back2._height = Stage.height;
    back3._width = Stage.width;
    back3._height = Stage.height;
    }
    function stageResize() {
    back1._width = Stage.width;
    back1._height = Stage.height;
    back2._width = Stage.width;
    back2._height = Stage.height;
    back3._width = Stage.width;
    back3._height = Stage.height;
    }

    It work really fine, the “back” 1, 2, 3, are background movieclips that contains jpeg images and are load one after another. Everything works fine until I resize the window, the current background proceeds it’s animation normally but in the endof the animation, when I load the next image, it won’t resize or show up the next image at all…

    Can you help me?

    Thanks

  111. Ricky Says:

    Hi David,

    Have you ever tried to center align the page flip component? (http://page-flip.com/)

    I’m having a few issues. The component once loaded uses lots of masking inside it therefore making the size of the mc on the stage rather large in _width and _height.

    I’ve tried to place the component into a new MC on the stage and scale it to fit proportionally inside the Stage.width and Stage.height but haven’t had much luck.

    Any help would be much appreciated.

  112. devon Says:

    Hey man.
    This helps me a lot here but I still have one question.
    This code is based on the fact of the mc the movie is talking to is aligned to the upper left corners of itself. And if you wanted to have the mc be centered within itself, to align it right, you would do the (Istage - half the mc) thing. What I want to do is have the mc centered within itself but also centered on the stage. I’ve been wracking my brain to come up with something that links (stage.width/2-mc.width/2) and (mc.width/2) btu to no avail. You kind of understand what I mean?
    Any insight would be appreciated.
    Thanks in advance man.

  113. Aaron Says:

    Hi David

    Nice topic here, it’s very hard to find a good tutorial or post in regards to this problem And especially get some to answer them. I have a problem a long with many other people. Ill give you a straight example of exactly how i think full screen should work. http://www.lessrain.com/index.php?localeISO=en_UK. The guys at less rain have nailed this, and for years i have always wondered how they have done this. The content is xml based, but the full screen landscape is controlled somehow, maybe js thats called in as, but it is exactly how i would like my background to function. I have my background solid 100%, but it does not scale proportionally. Would you have any ideas on how i could make this work?

    Thanks

    Aaron

  114. Aaron Says:

    Oh i forgot the code im using, whivh works in firefox, safari, but not ie7.

    Stage.scaleMode = “noScale”;
    bkg._width = Stage.width;
    bkg._height = Stage.height;
    stageListener = new Object();
    stageListener.onResize = function() {
    // resizes the bkg MovieClip to fit width and height of Stage
    bkg._width = Stage.width;
    bkg._height = Stage.height;
    };
    // Assign a listener for the Stage object
    Stage.addListener(stageListener);

    I want my menu in the bottom left corner, and the main content to load into the top middle of the screen, preferably using external swf’s. But also wnat that content to scale with the background, just not proportionally. Pretty much what less rain have achieved.

    Thanks man

  115. David Stiller Says:

    To Eddy …

    I would like the background image to fade out and fade in another fullscreen background image when the user clicks on a button. … I really have no idea on how to even start, could you please offer some insights?

    Sure thing, Eddy. Here’s a new article, “How to Position Dynamically Loaded Content Based on Browser Resizing,” that covers an approach I’ve used in the past. I hopd this answer is still useful to you after such a long wait!

    To Rita …

    I’m not sure, but I think my answer to Eddy might help you in your own endeavor. If not, you may need to make sure to re-assign the onResize when new content is loaded. If you put back1, back2, and back3 into the same container — just another movie clip, a parent clip to all three of them — and set your width and height changes to the single container, that may do it for you, and you could bypass the need to reassign the event handler.

    To Ricky …

    I haven’t tried to align the flip component, actually. Masking can certainly have an effect on the width and height measurements of a SWF (that is, a movie clip), but there are additional MovieClip class members you can use to dig around for the information you need. Have you tried the MovieClip.getBounds() method, for example? (Not a trick question, by the way … I honestly don’t remember, offhand, if that gives you different measurements than _width and _height, but it just might. Another avenue to try, anyway. :)

    To devon …

    I think you’re saying that your movie clip’s registration point is at its center (”if you wanted to have the mc be centered within itself”) — and if that’s so, then centering it to the Stage would simply need:

    mc._x = Stage.width / 2;

    mc’s position is its center, so putting its position (its _x at the center of the Stage does what you’re after.

    To Aaron …

    It looks like they’re using JavaScript to resize and position the browser (see their doResize() function when you use your browser to view source). That resizing would be handled by the Stage.onReisze event the same as a user-initiated resize. In fact, when I resize my browser, I notice that various elements on their site respond, so yes, it looks like they’re using both. That said, it doesn’t look to me as if their ActionScript directly calls their JavaScript, so while both are present, they’re essentially unrelated.

    I have my background solid 100%, but it does not scale proportionally. Would you have any ideas on how i could make this work?

    This is one way to do it:

    bkg._width = Stage.width;
    bkg._yscale = bkg._xscale;

    The width of the background is set to the width of the Stage, when the _yscale is set to whatever the _xscale happens to be, now that it matches the width of the Stage.

    Oh i forgot the code im using, whivh works in firefox, safari, but not ie7.

    The code you’ve shown should work just fine in IE7. That one stumps me.

    I want my menu in the bottom left corner, and the main content to load into the top middle of the screen

    To keep content to the bottom left — assuming its registration point is in the upper left — you could use this:

    content._y = Stage.height - content._height;

    To keep content in the top middle (i.e., top center), you can set the content’s _x property to the Stage’s width divided by two, minus the content’s own width divided by two:

    content._x = Stage.width/2 - content._width;

    It’s really just a matter of thinking through where items need to be, then figuring out those positions translate into numbers. It usually helps me to draw stick figures on a piece of paper or whiteboard using actual numbers, then slowly work through how to make the numbers “generic” in terms of a Stage whose width and height are unknown.

  116. pip williams Says:

    Hi David,

    sorry if this has been answered before! I’m not great with flash but am trying my best.

    I have a background with navigation btns. When you click one of these I want to load an external swf onto the background.

    When I do this using createEmptyMovieClip it seems to position ranged top left and I can’t centre it as I’d like.

    Have tried another way where the position is not centred, but when you resize the window it jumps into the centre. But I can’t get it centred properly until it’s resized! I have no idea what’s going on… sorry

    many thanks in advance
    Pip

  117. cranberryjello Says:

    David-

    This blog has really helped me with my site. My problem is I have a movie clip loading into a container. I have code from this site that uses a listener to wait until my swf is loaded before the stage resizes. My problem is that if I load another movie into the same container or even another, it won’t stay in the same position, centered. I have to drag the screen to active the code again. Is there a way to refresh the onResize code after you load another movie? Or how can I get a clip to center after the screen has already been resized? Thanks.

  118. David Stiller Says:

    To Pip …

    When I do this using createEmptyMovieClip it seems to position ranged top left and I can’t centre it as I’d like.

    That’s right, the MovieClip.createEmptyMovieClip() method will produce a movie clip whose registration point is the upper-left for any content it contains. This means you’ll have to use the width and height of this movie clip, along with its x and y position, to center its content.

    Have tried another way where the position is not centred, but when you resize the window it jumps into the centre. But I can’t get it centred properly until it’s resized!

    I’m afraid I don’t understand that part. I’m confident we can work through your questions, but to get there, I’ll have to be able to see clearly on my mind what’s going on. Could you describe your issue again?

    To cranberryjello …

    The Stage.onResize event is only dispatched when the user resizes the stage (via the browser), as you’ve seen. You can certainly invoke your repositioning code (positionContent(), in the above article) by simply naming that function in your load listener. (I’m assuming you’re using the MovieClipLoader.onLoadInit event, so in your listener for that event, you would simply include positionContent() in the event handler.)

    This tutorial might give you exactly what you’re looking for:

    How to Position Dynamically Loaded Content Based on Browser Resizing

  119. cranberryjello Says:

    David-

    I had previously looked at the tutorial you linked and it is pretty over my head. I tried it out, but one of my problems is that one of the swfs im loading into the container contains the buttons that control the loading of image galleries. so i couldnt target the buttons, or find a way to change the mcl.loadClip into loadGallery without messing up all the code.

    Anyway I think there’s an easier way. You were saying I could invoke the code to resize based on another listener. I using the “listener.onLoadInit”, but I’m confused as to how to write another listener that basically says, when this swf is loaded (viewer.swf), resize. Heres my code:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var listener:Object = new Object();

    listener.onResize = positionContent;

    function positionContent():Void {
    mcPackage._x = 25;
    mcPackage._y = 25;
    mcLogo._x = Stage.width - mcLogo._width - 25;
    mcLogo._y = 25
    mcLoader_diagram._x = Stage.width / 2 - mcLoader_diagram._width / 2;
    mcLoader_diagram._y = Stage.height / 2 - mcLoader_diagram._height / 2;
    mcLoader_viewer._x = Stage.width / 2 - mcLoader_viewer._width / 2;
    mcLoader_viewer._y = Stage.height / 2 - mcLoader_viewer._height / 2;
    mcLoader_small._x = Stage.width - mcLoader_small._width - 25;
    mcLoader_small._y = Stage.height - mcLoader_small._height - 25
    }

    var mcl:MovieClipLoader = new MovieClipLoader();
    mcl.loadClip(”mcDiagram.swf”, mcLoader_diagram);

    listener.onLoadInit = function():Void {
    positionContent();
    Stage.addListener(this);

    };
    mcl.addListener(listener);

    //Image Gallery code
    _global.SVStageWidth = 550;
    _global.SVStageHeight = 425;

    function loadGallery(galName){
    _root.xmlDataPath = galName;
    mcLoader_diagram.loadMovie(”viewer.swf”);
    }

    The code for my button in my mcDiagram clip:

    on(release){
    loadMovie(”",_root.mcLoader_viewer);
    loadMovie(”mcDiagram_sm.swf”,_root.mcLoader_small);
    _root.loadGallery(”gallery1.xml”);
    }

    Thanks for your help. I’ve been trying to nail down this issue for a few weeks now, but my knowledge of Flash is limited.

  120. David Stiller Says:

    cranberryjello,

    You were saying I could invoke the code to resize based on another listener. I using the “listener.onLoadInit”, but I’m confused as to how to write another listener that basically says, when this swf is loaded (viewer.swf), resize.

    Essentially, that happens right here:

    listener.onLoadInit = function():Void {
      positionContent();
      Stage.addListener(this);
    };

    Your function that handles the onLoadInit event is calling positionContent(), which means that — even though positionContent() is normally triggered by the onResize event — you’re also calling it once during each loading of a new SWF (or whatever gets loaded by your mcl instance).

    The reason nothing happens on subsequent loads, it looks like, is because you’re no longer using the mcl instance (that is, MovieClipLoader) to load your galleries. Instead, your loadGallery() function uses the MovieClip.loadMovie() method, as invoked on mcLoder_diagram.

    If you re-use mcl.loadClip(), you’ll get the benefit of the MovieClipLoader.onLoadInit event handler associated with that instance.

    Does that make sense?

  121. cranberryjello Says:

    So youre basically saying to change it to this right:

    function loadGallery(galName){
    _root.xmlDataPath = galName;
    mcl.loadClip(”viewer.swf”, mcLoader_diagram);

    }

    Whats funny is then it positions the content thats loaded through the button, mcDiagram_sm.swf into its container. but it wont center the viewer.swf thats loaded into the mcLoader_diagram container. I tried a bunch of different things but simply cant get that viewer.swf clip to load centered unless i resize the browser. Any ideas?

  122. David Stiller Says:

    cranberryjello,

    Then it may be time for some troubleshooting. Add trace("Hey, a SWF just loaded!"); to your onLoadInit handler to make sure the handler is getting triggered as new content loads.

  123. Jeremy Says:

    I haven’t got a question at the moment but I have read your blog and I wanted to say how impressed I am that you have gone out of your way to be so helpful to others. It is tremendous.

    Jeremy

  124. Aizil Says:

    Hi David,

    QUOTE: “By the way, this setup expects movie clips to be registered to their upper left corners. If mcLogo’s shape was centered horizontally in its own timeline, you would only have to minus half its width from the Stage’s width to make it hug the right hand side. If you want a 20 pixel buffer between this right-aligned clip and the Stage, account for that extra 20:

    mcLogo._x = Stage.width - mcLogo._width - 20;

    To keep a clip to the left side, set its _x to 0.”
    ——–
    I’m curious how to set the MC always to left. How the syntax looks like? Can you help me?

  125. David Stiller Says:

    To Jeremy …

    Thanks! You just painted a smile on my face. :)

    To Aizil …

    Assuming your movie clip’s instance name is mcLogo, then setting its _x property to 0 would look like this:

    mcLogo._x = 0;

    Again, that assumes the movie clip’s registration point is on the left side. It always depends on registration. If the clip’s registration point is on the right side, then you’d have to account for its width in order to keep it flush left:

    mcLogo._x = mcLogo._width;

    Does that help?

  126. kahfai Says:

    Hi David,

    I had previously looked at the tutorial u wrote for oiram, a full screen flash site and all the movieclip will arrange into their position after few sec. like this website

    http://www.if.net.my/manifesto/

    I already tried several time and i couldn’t make it works. can u provide the script or tutorial?

    can you help me ?

  127. umit celik Says:

    i have same problem with kahfai. can you help me too?

  128. David Stiller Says:

    kahfai and umit,

    I notice that I suggested the Tween class to oiram, so here’s a quick example that uses Tween to accomplish what it sounds like you’re both after.

    First, you’ll have to import the Tween class and its easing package:

    import mx.transitions.Tween;
    import mx.transitions.easing.*;

    This is ActionScript 2.0, by the way. Importing the classes lets Flash know when you’re talking about when you later make an instance of the Tween class and referencing one of the easing classes. After that, you’ll set the Stage’s scale and alignment, as before:

    Stage.scaleMode = "noScale";
    Stage.align = "TL";

    Since we’ll be using Tween class and the setTimeout() function (for the delay), declare some variables for them:

    var tw1X:Tween;
    var tx1Y:Tween;
    var timer:Number;

    The first two represent one Tween instance apiece for X and Y movement of one particular movie clip. The third represents a numeric value returned by the setTimeout() function, which you’ll see in just a moment.

    First, set up a listener for the Stage.onResize event, as before. This time, we’ll use a custom function named triggerContent(), rather than the previous positionContent() (the positionContent() function will be triggered by triggerContent()).

    var stageListener:Object = new Object ();
    stageListener.onResize = triggerContent;
    Stage.addListener(stageListener);

    Done. Now for that triggerContent() function:

    function triggerContent():Void {
      clearInterval(timer);
      timer = setTimeout(positionContent, 500);
    }

    Pretty short, right? All that’s going on here is that the clearInterval() function cancels any setTimeout() delay that might already be happening. This line is important because the onResize event is going to dispatch repeatedly — for example, if the user does a lot of continuous resizing — and you only want the positionContent() function triggered once per occurence of a Stage-resize, no matter how crazy and/or repetitive that Stage-resize is.

    Then, the timer variable (which was just used to cancel the possibly pending delay) is re-assigned a value from the setTimeout() function, which is instructed to trigger the custom positionContent() function in 500 milliseconds (0.5 seconds) … obviously, you’ll change that 500 figure depending on how much of a delay you want. Two seconds would be 2000.

    Finally, the reconstructed positionContent() function:

    function positionContent():Void {
      tw1X.stop();
      tw1X = new Tween(
        mcContent,
        "_x",
        Strong.easeInOut,
        mcContent._x,
        (Stage.width / 2) - (mcContent._width / 2),
        2,
        true
      );
      tw1Y.stop();
      tw1Y = new Tween(
        mcContent,
        "_y",
        Strong.easeInOut,
        mcContent._y,
        (Stage.height / 2) - (mcContent._height / 2),
        2,
        true
      );
    }
    positionContent();

    It looks pretty big, but it’s not so bad. It’s pretty much a duplicate for the _x and _y properties of a movie clip whose instance name happens to be mcContent. Here’s how it works.

    First, the tw1X instance is instructed to stop, in case it happens to already be animating. Next, the tw1X variable is set to a new instance of the Tween class. The constructor receives a number of parameters:

    a) which object to animate (mcContent)
    b) which property to animate (_x)
    c) which easing function to use (Strong.easeInOut)
    d) start position (mcContent._x; in other words, mcContent’s current _x position)
    e) end position ((Stage.height / 2) - (mcContent._height / 2), which just happens to center mcContent horizontally … what you do here is up to you)
    f) duration (2)
    g) whether or not to count the duration as time (true) or frames (false)

    The same concept is repeated for mcContent’s _y property.

  129. kahfai Says:

    To David,

    It’s work ! It’s work !

    Thanks David ~~But i still have a minor problem, what if the MovieClip need to positioning by numeric way? i mean like _x ,_y position …Could it be possible? Cause i browse through some example that is using (Stage.height / 2 )

    Thank you again !

  130. David Stiller Says:

    kahfai,

    Glad to hear that’s working! :)

    Yes, you can indeed manipulate movie clip properties directly. For example, if you wanted to make _x changes immediately, but delay _y values, you could do something like this:

    import mx.transitions.Tween;
    import mx.transitions.easing.*;
    
    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    
    var tw1X:Tween;
    var tx1Y:Tween;
    var timer:Number;
    
    var stageListener:Object = new Object ();
    stageListener.onResize = triggerContent;
    Stage.addListener(stageListener);
    
    function triggerContent():Void {
      clearInterval(timer);
      timer = setTimeout(positionContent, 500);
      mcContent._x = Stage.width / 2) - mcContent._width / 2;
    }
    triggerContent();
    
    function positionContent():Void {
      tw1Y.stop();
      tw1Y = new Tween(
        mcContent,
        "_y",
        Strong.easeInOut,
        mcContent._y,
        (Stage.height / 2) - (mcContent._height / 2),
        2,
        true
      );
    }
  131. kahfai Says:

    To David,

    oh i see… the problem is solved !!!
    i fully understand how is work, thanks David !

  132. David Stiller Says:

    kahfai,

    Glad to help!

  133. BrianF Says:

    Hello Dave,

    I have an issue with a loaded movieclip in a container when using the positioning code. When you resize the browser, the loaded swf flies to the upper right like its trying to rebel from its parent. I did not use the loadinit code because I am not to sure on how to execute it properly.

    http://hephisio.com/hephisio.html

    Though I am sure you’ve explained this issue in the blog, i would prefer a fresh explanation of issue, if its not too much trouble.

  134. BrianF Says:

    Hey Dave,

    Nevermind, I decided to stay with html for a bit and see how it pans out.

    http://hephisio.com/hephisio2.html

    Later.

  135. Remzi Jobin Says:

    Hi David,

    i find your code really clean and the principle got to me in a few seconds.

    I just wonder if I do a 2-3 minute animation, in wich I have several movie clips that will appear sooner or later in the animation, ex: a pencil animation at 40 seconds, or X other animation at 2: 20 I just wonder if it will respond well to the code if those movie clips are positionned anywhere in the timeline, and the code is still in frame 1 of the scene….. ill give you and example:

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent():Void {
    mcLogo._x = Stage.width - mcLogo._width;
    mcLogo._y = Stage.height - mcLogo._height;
    }

    function positionContent():Void {
    mcLogo2._x = Stage.width - mcLogo2._width;
    mcLogo2._y = Stage.height - mcLogo2._height;
    }

    function positionContent():Void {
    pencil01._x = Stage.width - pencil01._width;
    pencil01._y = Stage.height - pencil01._height;
    }

    function positionContent():Void {
    otherobject._x = Stage.width - otherobject._width;
    otherobject._y = Stage.height - otherobject._height;
    }
    positionContent();

    Now, I just wonder if my code sequence is written properly or If I need to call a stage listener for each and every single I create? Can I put a hundred movie clip listed in my first frame code? If yes, do I use the correct method? :D

    Cheers for your help to everyone David, and I thank you in advance!

  136. Remzi Jobin Says:

    Or should I use this form?
    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent():Void {
    mcLogo._x = Stage.width - mcLogo._width;
    mcLogo._y = Stage.height - mcLogo._height;
    pencil01._x = Stage.width - pencil01._width;
    pencil01._y = Stage.height - pencil01._height;
    papersheet01._x = Stage.width - papersheet01._width;
    papersheet01._y = Stage.height - papersheet01._height;
    papersheet02._x = Stage.width - papersheet02._width;
    papersheet02._y = Stage.height - papersheet02._height;
    }

    And will it work if a movieclip starts at frame 500 and the code is still in frame 1?
    (and i know i positionned all objects in the same coord. hehehhehe, i just want the right syntax to write the code) CHEERS!

  137. Remzi Jobin Says:

    Or if someone, somewhere, has a working example! that would be great! :D

  138. David Stiller Says:

    To BrianF …

    Nevermind, I decided to stay with html for a bit and see how it pans out.

    No worries! I’m sorry I wasn’t able to reply soon enough to be helpful. I’ve been stuck in hermit-mode for months, and have only just now resurfaced … because I finished the last chapter of my last book a week ago — just before I left for Flashforward 2008 — and I’m finally free! With any luck, I’m on the upswing again for email, forum, and blog replies.

    Because you mentioned onLoadInit, I wonder if you might benefit from this variant tutorial?

    How to Position Dynamically Loaded Content Based on Browser Resizing

    To Remzi Jobin …

    i find your code really clean and the principle got to me in a few seconds.

    Sweet! Thanks.

    I just wonder if it will respond well to the code if those movie clips are positionned anywhere in the timeline, and the code is still in frame 1 of the scene…..

    The location of your movie clips along the timeline is crucial to your success. If this code is in frame one, then the referenced movie clips must also appear in frame 1 — otherwise their instance names “don’t exist yet” as far as the code is concerned.

    Now, I just wonder if my code sequence is written properly or If I need to call a stage listener for each and every single I create?

    The problem with your first batch of code was the repeated definitions of positionContent(). Only the last definition (for otherobject) will take, because each new definition overwrites the previous one. Your code looks fine in the second batch looks fine.

    To make this work, I suggest you make every one of those movie clips available in frame 1, but for most of them, set their MovieClip._visible properties to false. This makes them invisible, but still referenceable to the positionContent() function. Later, in frame 500, you can “unhide” pencil01, for example, by putting a simple script in frame 500 of your scripts layer:

    pencil01._visible = true;

    Does that make sense?

  139. Remzi Jobin Says:

    Wow patience pays! Thanks a Lot David, you just confirm everything I needed to know to have fun with the code! :D :D :D THANKS A LOT MISTER! :D

  140. David Stiller Says:

    Remzi,

    Glad to hear it!

  141. Mark Geyer Says:

    Clean stuff David - thanks.

  142. Matt Says:

    Dear Dave,

    I am currently stuck!

    I am designing a re-sizable flash website which uses the same techniques as you have explained in this document to resize and position movieclips.

    Although the problem is that Im trying to create a sliding menu which sticks to the bottom of the stage (out of sight) until a button is clicked. On click the menu will tween from the current_y to show the complete menu - ie.200pixels.

    The menu is then returned to the originating _y by clicking a close button within the sliding menu movie clip itself.

    Do you think you could please help me with the code????

    You’ll be a life save if you can do this!

    Thanks so much in advance.

  143. David Stiller Says:

    To Mark …

    Thanks! Glad to hear it. :)

    To Matt …

    Im trying to create a sliding menu which sticks to the bottom of the stage (out of sight) until a button is clicked.

    I recommend the Tween class for something like that — meaning, to animate the nav clip’s position. Makes it really easy, and I’ll show you that in just a sec. The other aspect is that you need to make your Stage.onResize handler smart enough to adjust itself to cases when the nav is supposed to be hidden versus when it’s supposed to show. Fortunately, you can resolve that as easily as using a Boolean variable. Check it out:

    import mx.transitions.Tween;
    import mx.transitions.easing.*;
    
    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    
    var navShowing:Boolean = false;
    var tw:Tween;
    
    function positionContent():Void {
      mcLogo._x = Stage.width / 2 - mcLogo._width / 2;
      mcLogo._y = Stage.height / 2 - mcLogo._height / 2;
      if (navShowing) {
        mcNav._y = Stage.height - mcNav._height;
      } else {
        mcNav._y = Stage.height;
      }
    }
    positionContent();

    The first to lines import the classes necessary to use the Tween class; namely, the Tween class itself, and the numerous easing classes inside the easing package.

    After that, you’ve got the same Stage.onResize code as shown in the original blog entry … followed by two new variables — navShowing, set to false by default, and tw — and finally the same positionContent() function. Notice the new lines inside the function: if navShowing is true (if (navShowing)), then set mcNav’s _y property to the height of the Stage minus the height of mcNav (which lets it show); otherwise, push it all the way down (which hides it).

    At this point, all your button has to do is toggle isShowing and use the Tween class. Assuming, for sake of discussion, that mcLogo is your button, it could look like this:

    mcLogo.onRelease = toggleNav;
    function toggleNav():Void {
      if (navShowing) {
        tw = new Tween(mcNav, "_y", Strong.easeIn, mcNav._y,
                       Stage.height, 0.5, true);
      } else {
        tw = new Tween(mcNav, "_y", Strong.easeIn, mcNav._y,
                       Stage.height - mcNav._height, 0.5, true);
      }
      navShowing = !navShowing;
    };

    The Tween class takes a number of parameters: a) what object to tween, b) what property of that object to tween, c) what easing to use, d) the start value, e) the end value, f) a timing value (here, 0.5 seconds), and g) whether or not to use the timing value in terms of seconds (true) or frames (false).

  144. Matt Says:

    Hi David,

    Thank you so much for your wonderful work - your a champion. This works perfectly.

    Can you please help me further with the code to do these things - (same situation):

    how can i move the mcNav from a button that is placed in another movie clip named “navRight”?

    I would also like to have a button placed inside “mcNav” which moves the clip to out of sight aswell.

    Thank you so much again for helping this far - if you can help me again it would be amazing! Your an actionscript god!

  145. Matt Says:

    Hi David,

    Im sorry to bother you, I know you have a life. I really need your help, I have a pending deadline - and im really in a bad way in regards to this. The site depends on these sliders to function.

    Please let me know if you can provide some light on my last post : September 26th, 2008 at 12:59 am

    Thank you so much again for helping this far - if you can help me again it would be amazing! Your an actionscript god!

    Thanks so much again and sorry for bothering you! Cheers.

  146. Cris Says:

    Hi David

    I also wish to express my admiration for the time you are dedicating to help people out.

    I am making a photography website where the images scale with the browser window. But the problem with the way I’m doing it now is that the image sometimes gets cropped with the browser window. I would like the images to be displayed as large as possible but without without cropping.

    Thank you so much!

    here is the code I’m using, from your responce to M.A. Turner:

    Stage.align = “TL”;
    Stage.scaleMode = “noScale”;
    Stage.showMenu = false;
    _global._focusrect = false;
    _global._quality = “BEST”;
    this._lockroot = true;

    function set_stage() {
    // SET THE ASPECT RATIO
    original_width = 320;
    original_height = 240;

    scale_width = Stage.width/original_width;
    scale_height = Stage.height/original_height;

    if (scale_width>scale_height) {
    new_ratio = scale_width;
    } else {
    new_ratio = scale_height;
    }

    // THE CLIP YOU WANT TO SCALE
    my_mc._width = original_width*new_ratio;
    my_mc._height = original_height*new_ratio; }

    Stage.addListener({onResize:set_stage});

    set_stage();

    stop();

  147. David Stiller Says:

    To Matt …

    how can i move the mcNav from a button that is placed in another movie clip named “navRight”?

    You bet. Assuming the button’s instance name is myButton (but use whatever instance name you like), and assuming navRight is the instance name of that other movie clip, then all you have to do is path to that button in order to handle its onRelease (or similar) event.

    Instead of this:

    mcLogo.onRelease = toggleNav;

    … which is what I showed before, you could route that event handler like this:

    navRight.myButton.onRelease = toggleNav;

    … and the toggleNav() function wouldn’t change.

    I would also like to have a button placed inside “mcNav” which moves the clip to out of sight aswell.

    In the same way, you would path to mcNav, by way of its instance name, then to the instance name of the button inside it. Assuming myButton, which could just as easily be the instance name of that second button:

    mcNav.myButton.onRelease = toggleNav;

    Both buttons can have the same instance name, because they’re both nested inside movie clips with distinct instance names. And both buttons can be assigned to the same event handler function.

    To Cris …

    I remember that reply, oddly enough. (Gosh, that was quite a while ago!) That sample code was written by M. A. Turner, actually, and looking at it now, I see quite a few errors with it — I’m guessing M. A. noticed that too and (I hope) fixed it.

    The references to _global._focusrect and _global._quality, for example, don’t really do anything. Those properties are members of the MovieClip class, and the _global object doesn’t point to a movie clip, so if those really were necessary to M. A.’s needs — and I’m assuming they were — they should have been routed to the timeline in which the code was written (assuming it was written in the main timeline), which means _global should have been replaced with this, or omitted entirely.

    The meat of the matter is M. A.’s approach to maintaining aspect ratio, which (rightly or wrongly) I never did test.

    If you want want your images to scale to the browser and never crop, it means you will inevitably see letterboxing or pillarboxing when the browser’s aspect ratio isn’t the same aspect ratio of the image. There’s no way around that, and I hope it makes sense to you why. Assuming you’re okay with that, here’s a quick suggestion that will scale the image without cropping:

    Stage.scaleMode = "noScale";
    Stage.align = "TL";
    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);
    
    function positionContent():Void {
      photo._width = Stage.width;
      photo._yscale = photo._xscale;
      if (photo._height > Stage.height) {
        photo._height = Stage.height;
        photo._xscale = photo._yscale;
      }
      photo._x = Stage.width / 2 - photo._width / 2;
      photo._y = Stage.height / 2 - photo._height / 2;
    }
    positionContent();

    The basic mechanics are very similar to my original code prior to any of the comments. In this revision, the width of the photo is set to the width of the Stage. The height (via _yscale) is adjusted by the same value as the width. Then an if statement checks to see if the photo is now taller than the Stage. If so, the same manipulation is performed in reverse. After that, the image is centered (assuming an upper left registration point on the photo movie clip). This means the image will never be cropped.

  148. Matt Says:

    Hi David,

    Im having heaps of trouble with my slider.

    Is it possible to email you the documents to see how I should incorporate the code?

    Thanks so much.

    Matt

  149. otavio Says:

    Hi David!
    I also wish to thank you for the time you are dedicating to help people out. All of those comments helped me doing a lot of things!

    I have 2 questions that I think that wasn’t already questioned here.

    I have as an example this site:
    http://www.stevenkleinstudio.com/www/index.html

    As you can see it uses the same things that you taught.
    But! It has a menu that has a scroll bar that dynamically resizes when you resize the browser…
    I tried doing a lot of different things without success.
    Another thing that you could help me is about the image resizing… I could only do it horizontally (that site resizes the image when you resize your browser vertically too) how can I do this?

    Thanks in advance! ;)
    Otávio.

  150. kahfai Says:

    Hi David !

    I’m facing some strange problem…
    I’m working on a website that’s fit on browser size, every thing is work fine in swf, but using browser to preview, the content is not in the actual position until i resize the browser..why ?

    Below is the link, i haven’t done the loading yet, have to wait for a while :-P
    http://www.soulproject.com.my/summit/

    how to pop up a light box kinda effect when user’s resize the browser smaller then 800×600 px ?

    Hope you can help me on it, thanks !

    kahfai

  151. kahfai Says:

    I realize that the MovieClip do not move to the position from the beginning, it stay still in the position on working fla. Than it will only move while resize the browser .

    what happen?

    hope you can help me ..TQ

  152. Flug Australien Says:

    Thank u very much for taking the time to write this article which is very helpful for me.
    I’m a HTML ; PHP beginner and have the problem that I didn’t suceeded to embed a flash video to my html Website. I have used the this sample code

    :(
    Can u plz help me to fix the problem, I would be very thankful.
    Then I can try To position movie clips based on browser resizing.

  153. nkahfai Says:

    Hi David,

    I have couple question for full screen flash site, how to separate few categorize full flash with html?

    example link http://www.mariafilo.com.br/#/negocios/

    there will always have # in the url and wont affect the full screen script.
    how to do that ?

    Thanks so much.
    kahfai

  154. stephan Says:

    hello dave

    this is my question please

    I have used code below to position a mc inside my main mc and it works when i for example resizes the browser window the mc stays in the same position and in view no matter browser size.

    i wana do the same function this time with an externally loaded mc
    thanks bro

    stephan

    Stage.scaleMode = “noScale”;
    Stage.align = “TL”;
    var stageListener:Object = new Object ();
    stageListener.onResize = positionContent;
    Stage.addListener(stageListener);

    function positionContent():Void {
    mcLogo._x = Stage.width - mcLogo._width;
    mcLogo._y = Stage.height - mcLogo._height;
    }
    positionContent();

Leave a Reply