Showing posts with label How To. Show all posts
Showing posts with label How To. Show all posts

Thursday, 9 September 2010

How To Create A Website With Changing & Fading Background Images

So a client asked me to create a website which used changing & fading background images, and I said that sounded fine and I would check out how it worked, and then I looked it up on t'internet, and no one seemed to know how to do it.  Which surprised me because I'm sure I've seen it done, but maybe they used Flash or something.

So, not be be defeated (even when I read a thing that said it can't be done), I set myself to it, and now it works, which is rather marvellous.  I gave myself a small round of applause.  Then I figured that I should share it, because some people might want to do it but then give up when they read that it's awkward to do.

And so I present:

How To Create A Website With Changing & Fading Background Images
As ever, I deny all responsibility for this going wrong, if you try it and it does.

What we are trying to do:  the website should have a background image which fills the screen.  When the user scrolls, the background should remain fixed in place and the page content should scroll.  Every now and then, the background image should fade into another one.  This is to be achieved using HTML, CSS, Javascript and PHP, as required.

Caveats: this is basically not going to work on IE6, because it just doesn't like these things.  For IE6, just use a fixed background.  The fading effect will be ignored.  Anything below IE6, you probably have no chance.

The problems: having a rotating background image is not hard.  It just involves some css and javascript.  Fixing it in place is also fine.  The problem arises when you want to fade the background, because you can't do that without fading all the child elements... in other words, your page content will fade too.  So, we have to have 2 layers, one with the fading background, and one with the content.  But also, you can't fade one image into another if they're both in the background.  And also as well, sometimes the extra layer gets in the way and all your content moves to after the image.

But do not despair, for it can all be fixed, and here's how:

Step 1: The HTML
The basic idea is that we set 3 layers.  The top one is the page content, which moves when we scroll.  The middle one is the background image.  The lowest layer is the new image, which we fade to.  When the fade is complete, the middle layer gets this new image as well, and the background then gets the next one.  And so on.
Thus we have (I've done the opening pointy brackets the wrong way round, otherwise your browser won't show it):

>body>
    >div id="opacity-background">
       >div id="opacity-layer">
       >/div>
    >/div>
    >div id="mainBody"> Your main page content (header, navigation etc.) goes here
    >/div>
>/body>

'opacity-background' and 'opacity-layer' will handle the images.  If you have an existing site, you can just put a 'mainBody' wrapper round the current content, and then add these 2 divs above it.

Step 2: The CSS
Your CSS should contain the following:

body {
 margin: 0;
 padding: 0;
 position: relative;
}
#opacity-background {
  margin-top: 0;
  width: 1700px;
  height: 1100px;
  z-index: 0;
  position: fixed;
  background-image: url(../img/backgrounds/background1.jpg);
  background-position: top left;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
#opacity-layer {
  margin-top: 0;
  width: 1700px;
  height: 1100px;
  z-index: 0;
  position: fixed;
  background-image: url(../img/backgrounds/background1.jpg);
  background-position: top left;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
#mainBody {
  position: absolute;
  margin-top: 0;
  z-index: 1;
}

Obviously the width and height of the image should be set to whatever size your image is.  And also the background-image url for opacity-background should be set to your own value.  Put this somewhere in your CSS file.

The Javascript
And finally, the javascript.  I used mootools for the fading effect, but you could code it yourself.  I considered this, because I was scared that I wouldn't understand mootools, but actually it's very very easy.  You just get the code (we will come to this presently) and then put it in a file and link to it.

So, let's assume you have a folder called 'scripts', which your javascript files (if you have any) are in.  So you go get mootools, which will give you a file called mootools.js, and you put it in 'scripts', and the in the head section of your page you put (again, I have swapped the pointy opening brackets so that this shows up in your browser):


>script language="javascript" src="./scripts/scmootools.js"> >/script>


so that's it all linked in and everything.  You don't have to have a folder called scripts.  You can just put it in the same place as your head file.

Now you need to add your own bit of javascript. I guess you could put this in an external file as well, but I didn't (I apologise that this is all jumbled up - the line breaks have not, as we say, propagated).


 
  >script type="text/javascript">
 
   var bgImages = new Array();
   bgImages[0] = '../img/backgrounds/background1.jpg';
   bgImages[1] = '../img/backgrounds/background2.jpg';
   bgImages[2] = '../img/backgrounds/background3.jpg';
   bgImages[3] = '../img/backgrounds/background4.jpg';
   var inc=-1;
 
   function backgroundChange() {
    inc++;
    if (inc==4) inc=0;
    // Set background to new image
    var bgDiv = $('opacity-background');
    bgDiv.setStyle('background-image','url(' + bgImages[inc] + ')');
    // Set up fade
    var m = $('opacity-layer');
    var fx = new Fx.Tween(m,{
        duration: 1500,
        onComplete: function(){
                // After fade, show new image on this layer
                m.setStyle('background-image','url(' + bgImages[inc] + ')');
                m.fade('in');
       }
    });
    // Fade out current background
    fx.start('opacity',1,0);
   }
  
   // Navigation sliders and fade effects
   window.addEvent('domready', function(){
    // Add fade effect to all items in navigation menu
    var menuLinks = $$('a').filter(
                           function(item, index){
                            if(item.className == 'toplevelLink') return true; // Top level links
                            if(item.className == 'loneLink') return true; // Top level links
                            if(item.className == 'menu_sub') return true; // Submenu links
                            return false;
                           });
    menuLinks.each(
     function(el,index){
      // Set up morph
      var original = el.getStyle('color');
      var morph = new Fx.Morph(el, { 'duration':'500', link:'cancel'});
      // Attach event handlers
      el.addEvents(
       {
        'mouseenter' : function() { morph.start({'color':'#999999'})},
        'mouseleave' : function() { morph.start({'color':original})}
       }
      );
     }
    );
    // Get top level menus; hide submenus
    $$('a[class=toplevelLink]').each(
     function(el,index){
      // Sliding menus
      var submenu = el.parentNode.getElementsByTagName('ul')[0]; // get sub menu
      var submenuSlide = new Fx.Slide(submenu); // turn submenu into slider
      if(submenu.className != 'this') { // hide submenu for now, unless a page from it is currently shown
       submenuSlide.hide();
      }
      // Attach event handlers
      el.addEvents(
       {'click': function(e){
                     var submenu = el.parentNode.getElementsByTagName('ul')[0]; // get sub menu
                     var submenuSlide = new Fx.Slide(submenu); // turn submenu into slider
                     var thisid = el.id;
                     // Close all other submenus
                     var otherMenus = $$('a').filter(
                           function(item, index){
                            if(item.className != 'toplevelLink') return false;
                            if(item.id != thisid) return true; // Other menus
                            return false;
                           });
                     otherMenus.each(
                             function(el,index){
                               // Set up slide on submenu
                               var slide = new Fx.Slide(el.parentNode.getElementsByTagName('ul')[0]);
                               slide.hide();
                           });
                     // Show or hide this menu, as appropriate
                     submenuSlide.toggle();
                     e.stop();
                 }
       }
      );
     }
    );
    backgroundChange();
   });
   window.addEvent('load', function(){
    var pic = new Array();
    for(var ii=0; ii
     pic[ii]= new Image(100,25);
     pic[ii].src=bgImages[ii];
    }
    setInterval('backgroundChange()', 5000);
   });
  >/script>


So in the head section of your page, after the bit where you put the link to mootools, put the following:

You can play around with this a bit.  Make sure the paths to the images are right.

Basically that's all there is to it.

Appendix: How to get Mootools
I'm always scared of new things, because I'm always certain they won't work, but mooTools is very easy and lets you add lots of nice effects to your site.  It doesn't come with a lot in the way of examples, but it's not hard to figure out.

To get mooTools (it's free, by the way), go to http://mootools.net/download and click one of the links in the first section (I went for the uncompressed one, but as long as you can uncompress them, the others are fine).  That gets you mootools.js.

Friday, 30 July 2010

On Changing the Authentication Key for an Amazon Web Service EC2 Instance

You'll be pleased to hear I got the panniers sorted.  Well, not totally sorted, but, you know, I can see now what I need to do.

Today I had a whole new problem.  I'm doing some work on a website which is hosted on Amazon Web Services, and I had to change the password so that someone who previously had access no longer has access.  Now, to begin with, until about 2 days ago, I thought Amazon sold books.  So when I typed all of the above into Google, and got back a list of pages which said things like 'what you need to do is configure the blah blah blah FXPTWH server and launch a new BlahBlahBlah and terminate the BlahdyBlah', I had as much of a clue as... well... as you would, frankly (I don't really mean that.  Love you. xo).

So, I spent some time looking at the 'EC2 Dashboard' and being a bit scared to click on things.  And then I asked in the forum, and people said things like 'what you need to do is configure the blah blah blah FXPTWH server and launch a new BlahBlahBlah and terminate the BlahdyBlah'.  But then someone helpful explained it a bit better, and now I know, so I thought I would put it on the internet, so that if anyone else comes along who knows as little as me (which is unlikely, but always possible), then they will be able to do it right away, and not spend hours feeling dumb.

And so I present the WhyNotSmile Guide to Changing the Authentication Key for an amazon Web Service EC2 Instance.

Please note that this guide is for Windows.  If you are on Linux, you probably know more than I do.

Please also note that all or any of this guide may be wrong, and WhyNotsmile accepts no liability for anything bad that happens.  You may wish to create a test instance to try this out.  If your site is important, then it would be wise to find a guide written by someone who knows what they're talking about, or you could end up locked out of your site forever.  I'm just saying this worked for me; this is what I remember doing, and I may have forgotten bits.

Things you need before you start:
  • A browser
  • An account with Amazon Web Services, with at least 1 running instance (do not ask me how to do this.  I do not know).
  • Something which lets you SSH into servers and stuff, such as FireFTP (you can also use PuTTY, but in this guide I will use FireFTP because that's what I have and I can't be bothered typing everything in twice).

Step 1: Log in to your dashboard (or 'Management Console').  Observe that Amazon use the same 'Sign in using our secure server' button on this as they do on the book-selling thing.  No reason why, I just noted it.

2. Down the left hand side, click 'Key Pairs'.  You will now see a list of one or more key pairs.  These are critical, because they give you security on your system.

3. Above the list, there is a box labelled 'Create Key Pair'.  Helpfully, this also has a picture of 2 keys.  Click this box.  Give your key pair a name.  This can be anything, as far as I can tell.  Also, it does not appear to be of any subsequent use.  Click 'create'.

4. After a few moments, you will see a pop-up thing saying that you are downloading a thing.  This is your new key, and is Very Important.  Save it somewhere where you can find it later, because we'll be coming back to it soon.

5. Now, go to FireFTP and log into your site from there.  Find the file '/root/.ssh/authentication_key', and copy it across to your local machine.

6. Now click on 'Edit' to edit the settings for this account.  Go to the second tab, which is called 'Connection', and go to 'Private Key'.  Click 'Convert', and a navigate thing pops up.  Navigate to where you saved the thing you downloaded earlier, and click 'Open'.  Now you get a popup PuTTY thing which has an insane amount of letters and numbers at the top.  Those are what you need.  Copy the contents of the top box to a blank text document.  Click 'Save private key', and save it somewhere sensible, as newkey.ppk (this should be saved in the same place as the original ppk file, if you know where it is.  If you don't, look at your account settings in FireFTP and it will tell you.  You can call it anything you like as long as it ends in .ppk, I think).  Do not overwrite the original key.

7. Open the file authentication_key, which you downloaded in step 5.  First, make a backup copy.  Now copy the contents of the PuTTY window with all the letters and numbers in it (you should have copied these to a blank text document at step 6, so they are now To Hand).  Now paste it into the authentication_key file, instead of what's there already.

8. Upload the authentication_key file to where you got it in the first place (/root/.ssh/).  You have now replaced the old key with the new one, and you can't log in with the old one any more.  Log out.

9. Now you can't log in because FireFTP is using the old key.  You have to tell it to use the new one.  Open the account manager again, and go to the 'Connection' tab that you were at before.  Click the 'Browse' button next to 'Private Key'.  Navigate to the file newkey.ppk, as discussed in step 6.  Select it, and click 'OK'.

10. Log in again.  This time FireFTP is using the new key, so it should be fine.

If it doesn't log you in, Something's Gone Wrong.  I have no idea what.  Good luck with that.

You do not need to delete the old key pair from the Management Console.  But I suppose you can if you want.  Just make sure it's not being used for anything else.

Tuesday, 20 April 2010

How To: Fry an Egg in a Sandwich Toaster

I don't know if this ever happens to you (and if there's one thing I've learned as I've proceeded through life, it's that an alarming number of things are unique to me), but the other week I took a craving for something, and couldn't work out what it was.  I knew what it tasted like, roughly, and I knew that it wasn't a healthy thing, but beyond that I couldn't figure out what it was.  Anyway, long story short, it turned out I was craving a fried egg sandwich.  Which is odd, because I'm fairly sure I've never had  a fried egg sandwich before.  Go figure.

By what can only be described as fortuitous coincidence, my sister had just that week bought a box of eggs entirely to take a photo of them (because she's doing teacher training), and they were still in the fridge.  So I toyed with frying one of them, but realised I couldn't be bothered getting the frying pan out, heating it blah blah blah oh the hassle.

So life moved on, the craving went away, and in all honesty I'd almost forgotten the incident entirely, when I perchanced to be listening to the excellent Dave Gorman podcast, which you should probably all subscribe to.  They had a discussion about things that could be used as other things, and hark! if one suggestion was not about using a toasted sandwich maker to fry eggs. 

So I thought I'd give this a go, because it sounded a lot less messy and less hassle than the regular frying pan method, and although the fried egg sandwich craving had long since been replaced by the more regularly-scheduled chocolate craving, it still seemed a worthwhile way to spend a few minutes, in the interests of journalistic research.

And so it is that I can now proudly explain the ins and outs of frying eggs in sandwich toaster.

Step 1: Retrieve sandwich toaster from back of cupboard.  Recoil in disgust at caked-on dirt from last time it was used and you didn't bother cleaning it.  Spend some time removing an amount of surface dirt.  Decide it'll do.  Switch it on and wait for it to heat up.


Step 2: Break eggs into sandwich toaster.  If possible, and assuming you have the option, you should use the grill plates with edges to prevent the egg running out the sides.  Also, you may find you can fit 2 eggs into one side of the toaster, thus allowing you to cook 4 eggs at once.


Step 3: Close the lid, and wait for a while.  After several minutes, lift the lid and poke the eggs a bit to see if they're cooked.  Repeat until they are.


Step 4: Remove eggs from sandwich toaster and eat.


Step 5: Clean sandwich toaster.  Wish that, at step 2, you had thought to add a little oil or grease or something.

Tuesday, 9 March 2010

How To: Make Butterfly Cards With Small Children

Last week posed a dilemma: a roomful of small children, aged 12 months - 3.5 years, who have been promised Craft. Of course, once can assume that those under the age of 2 have no concept of what that means, but those older than that will remember for time and eternity, and it's not worth not doing it. Plus, it is bad to fail to keep promises to children, even if they don't remember.

And so, it behoved me to come up with something we could make which the older ones would like, the middle-aged (in toddler terms) ones could manage, and the babies couldn't eat. Essentially, it needed to involve colouring in and stickers, but not actually BE colouring in, because that's not exciting enough.

I am quite proud of what I came up with, which is why I'm sharing it. Here's what we did, and how we did it:

Butterfly Cards

You will need:
  • Thickish paper (based on experience, which we will come to presently, regular paper is not the best choice of material)
  • Paints, colouring pencils, felt tips or anything which will make patterns on the paper (based also on experience, if you have limited time, do not use paint)
  • Bendy drinking straws
  • Blank greeting-type cards (or make them from card yourself)
  • Ribbons (thickish, like at least 1cm thick. If they can match the straws, so much the better)
  • Flower stickers
  • Scissors and sellotape
What you do:

1. Get child to draw on paper with paints, felt tips etc.

2. If you have used paint, wait for the paper to dry, and then proceed to step 3, with a hyperactive/grumpy/lost interest child in tow. If you have not used paint, proceed immediately to step 3 with a happy child.

3. (Child) Attach flower stickers to card. Or draw flowers on.

4. (Adult, while child is doing 3.) Draw a butterfly on the decorated paper. Attempt to cut it out.
Note: potential pitfalls
i) If you did not previously explain to the child that you would be cutting their picture up, they may cry at this point. Unlucky.
ii) If you used paint on regular paper, this will be like cutting through mud. Return to the instructions above where I said to use thick paper.

5. (Adult) Cut straw to same length as butterfly, but with bendy bit sticking out the top. Cut into bendy bit so you can bend it outwards, to make feelers.

6. (Adult, with child hindering) Thread ribbon through straw; tie a knot in the end that's below the straw. If ribbon is thin, you may need to add a bead. The aim is to ensure that the straw can't fall off the ribbon; achieve this however you see fit.

7. Stick straw to middle of butterfly, so you have a butterfly on a ribbon.

8. Tape ribbon to card, and you have a card with a butterfly flying over flowers.

Of course, if you have many children, bear in mind that the younger ones are perfectly happy to go home with a sheet of decorated paper and a card with flowers on it, so you can stop after 3., and only proceed onward for the older ones and those with reasonable attention spans.

I would attach a picture, but someone destroyed the prototype.

Wednesday, 21 May 2008

How To Be Happy

When you are having a hard time, there are many people who can tell you what you should do in order to be happy, and how you should do it.

The key to happiness is to identify such people, and then avoid them like the plague.

Wednesday, 27 February 2008

How To: Knit Mittens

So while I have been away, smallcorner has taken up knitting - a noble pursuit, and one which will guarantee years of satisfaction.

You may recall that over the festive period, I made myself stripey mittens. I thought I would share the instructions for this with the world, so that you can all have stripey mittens too, but especially it is for the benefit of smallcorner.

I decided to do it diagramatically, because it is too hard to explain. Proceed as follows: