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.

Saturday, 4 September 2010

The WhyNotSmile Guide To Spelling, Punctuation and Grammar On The Internet

I don't want to come over all Lynne Truss on you all, but it has become clear of late that the quality of writing on the internet has slipped alarmingly in recent times, and if I don't take it in hand, frankly, who will?  With this in mind, I set to thinking, and it is thus with great pleasure that I present:

The WhyNotSmile Guide To Spelling, Punctuation and Grammar On The Internet

Introduction
The rules of spelling, punctuation and grammar on the internet (SPAGOTI) are generally more relaxed than those in real life, and it pays little to get worked up over simple typing mistakes (hte, adn etc.). Indeed, the internet (and other modern technology) has birthed new language of its own, from the smilie, which we like, LOLspeak, which we like in its own domain (we shall return to this presently), and abbreviations like 'ur l8' ('You appear to be running behind schedule') which is ok (but not necessarily to be encouraged) on a mobile phone, but is intensely irritating anywhere else.

In general, it is fair to say that the internet is a fast-moving medium, and to this end, one does not wish to be pedantic about those instances when the spellchecker was an unnecessary hinderance; it is, however, reasonable to expect that communication be understandable and that it show signs that the communicator has put in some effort. With this in mind, we now consider the various elements of the Rules of SPAGOTI.

Spelling
1. Bad typing. As stated above, there is a difference between bad spelling and bad typing, and this should be respected. We all miss a letter from time to time, and sometimes we mix letters up because one finger paused for thought and another overtook. This is acceptable, and, unless it is excessive, it does not do to be churlish about it.

2. You're, your and ur; there, their, ther and they're etc. The following is a comprehensive guide; please memorise it:
  • You're = You are. The apostrophe indicates that a letter has been omitted, as in 'phone for telephone, wasn't for was not, and 'ee by gum, which has omitted both some letters and any semblance of meaning. Example: You're learning fast
  • Your indicates 'belonging to you'. Like 'our', but it's yours. Example: 'Your toothbrush'.
  • Ur is text speak, and can be used IN TEXT MESSAGES ONLY to replace either of the above. This is an inappropriate place to give an example, as this is not a text message.
  • Use = put into service, as in 'I would like to use your bicycle tomorrow'.  It is not the plural of 'you'.  Neither is 'youse'. Also, you write 'youse', I think 'louse'.
  • There = in that place. Like 'where' and 'here'. It specifies a location. Example: The book is over there.
  • Their indicates 'belonging to them'. Like 'your', but theirs. Example: Their spelling is excellent.
  • They're = They are. Again, the apostrophe indicates that a letter has been omitted. It's really not that complicated. Example: They're starting to get the hang of this.
  • Ther is not a word.
  • It's = It is.  It's the apostrophe = missing letter thing again.
  • Its = belonging to it.  Like his or hers.
  • Its' is not a word
3. LOLspeak. It is possible that you have come across something which appeared to be badly spelt, but which you were able to understand when you said it out loud. If so, it is likely that this was either Ulster-Scots, or LOLspeak. LOLspeak is the language used on the Lolcats/Cheezburger sites. For those who have not come across this site before, it is essentially a worldwide, ongoing caption competition (with no prizes), in which anyone ('hoomans') can submit a humourous ('funneh') (or, indeed, non-humourous ('non-funneh')) caption ('capshun') to accompany a picture ('pictur') of a cat ('kitteh'). In many cases the humour is derived from the juxtaposition of the cat's seriousness with the incorrect spelling which goes along with it.
This is fine as far as it goes; the difficulty arises when the langauge of LOLcats is taken outside of its natural habitat and smattered disregardingly across the rest of the internet, or even (horror of horrors) onto actual, physical paper. At this point, a boundary has been crossed, and not for the better.

4. Abbreviations. It is perfectly acceptable to shorten 'later' to 'l8r' in a text message.  It is not acceptable to do this in an email, particularly if you are trying to convey a serious point.  On the other hand, there is no sense in doing everything in longhand; for instance, do not feel you must refer to 'Compact Discs', 'Personal Computers' or 'Automated Teller Machines'.
As a rough guide, if your father would understand it, then it's fine.  Your mother should not be used as a guide, as they are ferocious for picking up abbreviations and using them like crazy.

5. Please learn to differentiate the following words:
  • chose = past tense (Last week, I chose strawberry ice cream).  choose = present tense (I choose tea, in general).
  • lose = become unable to find (where did you lose it?).  loose = not tight

Punctuation
Contrary to what appears to be an alarmingly popular opinion, punctuation is as important on the internet as it is anywhere else.  'Punctuation' is all those little dots, dashes and wavy lines that are used to create smilies.  It appears to be unknown to some, but these all have value in their own right, as we shall now consider:

1.The 'Full Stop', or 'Period'.  That's the little dot which you may have noted at the end of all my sentences.  The full stop virtually exists to end sentences.  Because sometimes, no matter how important your point is, you have to stop talking.  At that point, you should enter a full stop.  For instance, the following are correct uses for full stops:
  • The cat sat on the mat.
  • I ran a marathon today.
  • He went to the shop; I do not know when he will return.
The following are incorrect:
  • The cat sat on the mat then he ate lunch then it went outside lol
  • He laughed. at me because I can't spell
From time to time it is acceptable to omit the full stop; for instance, in headings, or when the sentence ends with a question.
The other main use of a full stop is to denote an abbreviation.  E.g., e.g., i.e., etc., ibid. and so on; while there are rules about this on paper, I think we can safely say that in the online world one need not be too concerned.  Some abbreviations, such as Dr, NATO and CD do not require full stops, although I am not sure why.


2. The Comma.  The comma may well be the most abused punctuation mark in existence.  Partly this is because insertion of a comma is often a matter of personal preference, and partly it is because the comma has begun to be some sort of catch-all punctuation mark which is used by the uninformed as a short-cut.
Theoretically, it is possible to construct reasonably intelligible sentences without the use of a single comma, particularly in text messages and Facebook stati, and in many cases of uncertainty this is the best course of action.  Of course, one must take care to avoid such situations as the now well-known "Let's eat Harry!" in place of "Let's eat, Harry!", but in general one can get away with leaving a comma out.
One trend which has troubled me of late is the tendency to use commas in place of apostrophes, leading to sentences like "The man,s tie had become worn".  This makes no sense.  Please don't do it.
An even more disturbing trend is the multiple comma, particularly when it is used in place of a full stop.  On more than one occassion in the recent past, I have seen my Facebook feed littered with things like the following: "Just watchd the footie,,, Can't believe it [player name] was sent off!!!, , , lol whydo they do dat av nevr seen a ref so bad,", which, frankly, I do not believe I should be forced to read.

3. Brackets.  I don't have a lot to say about brackets, except that, for every open bracket, there should be a matching close bracket.  Brackets are for sidelines, extra information, and tangents; one should be able to remove them and still understand the sentence.  For instance: "The unicorn (which was white, with a golden mane) chewed the grass thoughtfully for some time".  It still makes sense if you remove the bit in brackets.  The difficulty here is that some of us make a mental note that we have entered a bracket, and take our thought volume down a notch every time we do.  We then ratchet it back up when the closing bracket is found; if it does not appear, we end up in silence, and confused.

4. The Colon.  Essentially, this should be used to introduce lists, viz: "I bought three things: a basket, a ball of wool, and a pair of scissors".  On the internet, if you're not sure, do not use it outside this context.

5. The Semicolon.  Like the colon, should only be wielded by those who know what they're doing.  With the more casual approach to punctuation allowed online, if you're not sure whether to use a semi-colon, it is best to use a comma instead.

6. The Question Mark.  This indicates that you asked a question.  It ought, in many ways, to be the simplest form of punctuation to master, but it appears that the internet is no friend of the simple, and far too many times have I seen questions without question marks, and question marks without questions.  The pairing should be as natural as yin and yang, Torville and Dean, or strawberries and cream (and just as pleasant), but (sadly), too often the two are torn asunder, and the rent halves are left alone, bereft.

7. Quotation Marks.  These are the vertical double dash thingies, not the vertical single dash, although the latter can also be used for quotations. They indicate that someone has said something.  For example: 'Right in the middle of the room, she stood up and said "Well, I have never heard the like!"'.  They can often be omitted in text messages.  The important thing to understand, however, is that they can be used to imply that someone has said something which isn't true; they are frequently employed by journalists to quote sources and indicate that some truth is being concealed.  So, one could say 'She told me she was "going to bed"', to imply that perhaps she was doing something other than sleeping.
Now the point here is that, if you put a word or phrase in quotation marks, particularly if you are trying to promote something, you end up making it look untrue.  For instance, 'Shop here!  We have the "best" prices in town!' may be intended as an advertisement, but what it means to the grammarian is that someone once said the prices were the best, but probably that was the owner's mother.

Grammar
Grammar is (and I quote Wikipedia) the set of structural rules that govern the composition of sentences, phrases, and words in any given natural language.  In other words, it tells you how to put words together so that sentences make sense.
Now, I have a number of bugbears here (as you might expect).  Most of these apply to real life as well as the internet; but whereas in real life you can generally disguise them with a bit of an accent, their use online is inappropriate.

1. 'I saw' and 'I have seen'.  Not 'I seen', and not 'I have saw'.  Yes, it matters.  Other examples include:
'I went' and 'I have gone'; 'I did' and 'I have done'.  It's all to do with past participles; you do not need to be familiar with the technicalities (although it's worth it for the sheer joy of knowing), but please take a few moments to memorise the rules.

2. 'I would have', not 'I would of'.  It's an accent thing.  People sound like they're saying 'of', but really, it's 'have'.  Trust me.  You get away with more in conversation.  You could say "I carried on disregardless" and the other person will think "disregardless?", but you will have moved on disregardless and it will all blow over.


3. Text messaging is a special case; email and Facebook stati are not.  In texting, you don't always have the time and space for the full 'subject-verb-object', and it is sometimes acceptable to omit one or more elements.  For instance 'I have your pen and I will bring it round to you later' can justifiably be texted as 'Have ur pen, will bring 2u l8r' (although if you have a pen, the preference would, naturally, be to write a letter).  Likewise 'I will be there in 10 minutes' can be shortened to 'Wiv u in 10'.  These are fine.
However, in emails, please use full sentences (possible exceptions can be made for emails sent from mobiles, as one can only type on those wee keypads for a short time before one gets Carpal Issues).

Conclusion
I trust the above guide has clarified some things for you all.  As we said at the beginning, the aim is not to start getting sniffy over every typing error and omitted article, but it is to be hoped that communication can be made increasingly clear (note: not increasingly clearer, which is a second order derivative and does little to add meaning, and much to make the user look a bit dense, or pompous).

Thursday, 26 August 2010

Gardening

I'm sorry I haven't posted much of late.  I've been very, very busy.  Like, not just regular old busy.  Really, really crazy busy.  Working all day and then some in the evening busy.

Also, I decided to dig up my garden.  This is all part of a vastly overambitious and, undoubtedly, ultimately doomed (but what is the blog for if not to tell you about things going hilariously wrong?) plan to landscape my garden.  After spending quite some time digging up the grass (with my sister saying things like 'Why are you doing it yourself?  Should we not get someone in?  What if you do it wrong?' - to which I responded 'Because it's about 2 ft sq of grass, and if we got someone in they'd laugh at us for being pathetic, and then charge us, like, £400, and anyway, how hard can it be, and what's the worst that can happen?') the plan has been slightly scaled down, and is now more of the order of making a place for the bins to sit.

I initially had a mind to put up a new fence as well (the old one is going to just fall over some day soon), but this was roundly decried by the naysayers who don't think I could construct a fence, so we're getting someone in to do it instead (of course, when they said I'd never be able to do it, I wanted to try even more, but then I realised the materials would be quite expensive and I don't want to go wrong with expensive things).  Our current options for the Fence Constructor are as follows:

1) A man who did my aunt's fence.  Having been quoted £600 from everyone else, this guy charged about £100 (these figures may not be literally correct, but they give an idea of the relative gulf between the quotes).  Now, ordinarily, this would worry me (you will recollect that The Builder wasn't the most expensive guy in the... um... place where builders are), but my dad was already leaning towards hiring him, and then heard that he works hard all day and doesn't accept any offers of cups of tea, and this seemed to clinch it.  You may recollect that The Builder didn't accept offers of cups of tea either, and look how that turned out.  Also, there was the guy who did the windows a few years ago.  He was cheap and didn't drink tea, and is now in jail, which may have invalidated my warranty.

2) Sister's friend Lucy's cousin who is a gardener.  This was going well until I pointed out that what we really need is not so much a gardener as someone to build a fence.  Anyway, he's coming round on Monday to give us a quote.

In any case, I'm perfectly certain it will be a merry disaster, as these things always are, but you will, of course, be kept informed.

Friday, 6 August 2010

On Having A Television Again: Again

There are some further points I wish to raise about having a television again

1) I'm used to watching TV programmes at my parents' house, but these are inevitably ones which my mum recorded weeks, or, indeed, months ago.  I takes some getting used to when you watch TV live, and have to keep reminding yourself that news reports and weather forecasts are all new.  I keep watching the news, and thinking 'I never heard about that!', and then remembering that that's the whole point of news, and, when watched in real time, it is not supposed to refer to things you already knew.
Likewise for adverts: at my parents' house, the 'special offers' always ended months back; I could only watch and ponder what might have been.  I have to keep reminding myself that I can now avail myself of these things, because they wouldn't be telling me otherwise.

2) I had forgotten about my habit of flicking channels without thinking.  This leads to mass confusion, in my head at least.  Not so much if I was watching Wimbledon, and flick unconsciously to Have I Got News For You: in that case I can generally figure out pretty quickly that I must have changed channels without noticing.  But when you flick from Coronation Street to, say, Holby City, it can take a wee while to figure out why Fizz is wearing scrubs and operating on people.
Of course, confusion is only heightened when you flick between programmes starring the same people.  How did Juno's step mum end up being White House Press Secretary?  Since when has Father Dougal been a teacher?  I didn't know Miss Trunchbull was Smithy's mum!

So, as you can tell, it's going to take some time to get used to all this.

Tuesday, 3 August 2010

On Having a TV Again

I may have mentioned before that I have not had a TV license for about 7 years.  This has meant that I can watch things on iPlayer, as long as they're not live, but I can't watch anything live.  Now this was all well and good, but now that Sister Smile has moved in, it has become An Issue.

Until today, we basically worked our way through our DVD collections, and those of our friends, which meant: Friends, West Wing and Cold Feet.  Sister Smile limited herself to Friends, and, as you can imagine, after a year of nothing else, was fairly fed up with it.

So she got a TV license.

So now we have Freeview.  I came in yesterday, and Big Brother was on.  I'm fairly sure that was one of the shows which prompted me to get rid of the tv in the first place, so to discover (1) it's still on, (2) it's what we're chosing to watch, and (3) it hasn't got any better, was, as should be painfully clear, a Surprise.  Then we watched some adverts.

Then this evening we watched Friends.

So that's been worth 140 quid.