Griffiths web design based in Royston, Hertfordshire, United Kingdom


Javascript Tutorial

Exploring JavaScript’s setTimeout and setInterval methods – Example’s and Explanations.

[postpic=stopwatch.jpg class=img-responsive title=settimeout-vs-etinterval alt=set timeout and set interval style=STYLE][/postpic] [l]I would like to discuss with you today JavaScript’s setTimeout and setInterval methods. I will attempt to explain them and I will also be providing some examples. To follow along with the examples you won’t need much prior knowledge as all the JavaScript code will be explained and all HTML and CSS will also be provided and given limited explanation.[/l] [hdmd]setTimeout vs setInterval – the difference.[/hdmd] [l]One thing that many newcomers to JavaScript get mixed up is when to use setTimeout and when to use setInterval.[/l] [l]The key thing to remember is that setTimeout executes the function once when the timer runs out. Whereas setInterval executes the function when the timer runs out but then restarts the timer and loops continuously until clearInterval() is called.[/l] [hdmd]setTimeout[/hdmd] [l]I would like to start with setTimeout[/l] [hdsm]The syntax[/hdsm] [code] var timerOne = setTimeout(function|code, delay);[/code] [def] [term]Function | code[/term] [desc]The function or piece of code you wish to execute when the timer runs out. [/desc] [term]Delay[/term] [desc]How long you wish to wait before executing the function or code previously specified. Please note that time is counted in milliseconds. [/desc][/def] [l][b]An example:[/b][/l] [code] [/code] [l]This code will execute an alert after 5 seconds which will read ‘hello’. We wrapped our alert in a function declaration. This is not always necessary, as you will see from the next example you can also use functions that have already been declared elsewhere.[/l] [code] function exOne() { var timerOne = setTimeout(trythis, 5000); } function trythis() { alert("hello"); } [/code] [l]In this example we performed exactly the same task except we put our alert in a function then called that function from within the setTimeout method. In this example I have omitted the html as that has remained unchanged from the previous example. Calling an alert on a time delay may not seem all that useful out in the real world but the principle remains the same no matter the complexity of the function being called. In the interest of providing a more usable real world-ish example we will be creating a div which will have different css classes applied to it which will change the colour of the div we will also update the label text. It will cycle through three different colours after a set amount of time. [/l] [l]First of all we will add some HTML.[/l] [code]

[/code] [l]As you can see all we need is a div, a label to contain the text and a button to start the process. In the ‘onclick’ event declaration of the button you will see ‘StartTimer()’, this is the name of the function we will be creating in our JavaScript. This function is where the magic is.[/l] [l]Next we need to add some CSS.[/l] [code] #traffLight{ border-radius:100px; width:200px; height:200px; margin:0 auto; } #status{ position:relative; top:50%; display:block; margin-left:auto; margin-right:auto; text-align:center; color:#808080; } .red{ background:#ff0000; } .yellow{ background:#ffd800; } .green{ background:#00ff21; } [/code] [l]First we made the div a circle by using the border-radius property. We set the border radius to half the height of the div which makes the div a circle shape. We also set the height and width of the div and we centred the div. Next we set some styles on the label. We set its position to relative so that its position is relative to its containing div. we also centred it vertically and horizontally, centre aligned the text and we set the colour of the text. Finally we created 3 classes: red, yellow and green. These classes will be responsible for changing the background colour of the div.[/l] [l]Now we have the CSS in place it’s time to bring it all to life with some simple JavaScript.[/] [code] function StartTimer() { var traffLight = document.getElementById("traffLight"); var status = document.getElementById("status"); if (traffLight.className === "red") { traffLight.className = "yellow"; status.innerText = "Ready?"; window.setTimeout(StartTimer, 3000); } else if (traffLight.className === "yellow") { traffLight.className = "green"; status.innerText = "Start!"; window.setTimeout(StartTimer, 12000); } else { traffLight.className = "red"; status.innerText = "Stop!"; } } [/code] [l]That is all there is to it, just that one tiny function. First we searched the DOM for our div and our label, we stored them in variables. Next we check which of our colour classes is already in place on the div. Once the correct class name has been found the code overwrites it with a new class, i.e. if the class already present was red then it overwrites it with yellow. Our code then updates the text of the label. In the next line of code we call window.setTimeout(). Within that method we feed it 2 parameters, one is the function to be called when the time runs out and the second parameter is how long to wait before calling the function. Please note time is counted in milliseconds. If you run the page in your web browser you’ll see that the circle starts out life red. When you click the button it then turns to yellow for 3 seconds then changes to green for 12 seconds and finally change back to red. As you can see from this example setTimeout only executes the function once, and only when the timer has depleted.[/l] [hdmd]setInterval[/hdmd] [hdsm]The syntax[/hdsm] [code] var intervalOne = setInterval(function|code, delay);[/code] [def] [term]Function | code [/term] [desc]The function or piece of code you wish to execute when the timer runs out.[/desc] [term]Delay[/term] [desc]How often you wish to wait before executing the function or code previously specified. Please note that time is counted in milliseconds.[/desc][/def] [l][b]An example:[/b][/l] [l]First a little bit of html.[/l] [code]


[/code] [l]We have created 2 buttons and a set of paragraph tags. Nothing fancy here![/l] [l]Now we need to add some JavaScript:[/l] [code]var int01; function exTwo() { var text = document.getElementById("textHolder"); int01 = setInterval(function () { text.innerText += "hello "; }, 3000); } function endExTwo() { clearInterval(int01); } [/code] [l]In this code we have created a variable which will hold our setInterval method. Next we created two functions; the first function finds our p element, once it has done that it add the word hello to our p element. It does this every 3 seconds. In our second function we call the clearInterval method to cancel the execution of our setInterval method. The clearInterval methods takes one parameter, which in this case is the name of the variable that contains our set interval method.[/l] [l]Now we will go through one more example. Remember the traffic light effect from our set timeout method example? We will be creating something similar to this, but not quite identical. I will show you the HTML and the JavaScript but you can use the CSS from our setTimout example.[/l] [l]The html:[/l] [code]

Traffic light effect demo

[/code] [l]As you can see the HTML is almost the same as the HTML we used in the setTimeout example, except in this HTML we call our function on the body tags onload event. This means our code will run as soon as the page is loaded, therefore eliminating the need for a button.[l] [l]Now we can move on to our JavaScript:[/l] [code] function loadTraffLight() { var traffLight = document.getElementById("traffLight"); var status = document.getElementById("status"); var timer; timer = setInterval(function () { if (traffLight.className === "red") { traffLight.className = "yellow"; status.innerText = "O.K"; } else if (traffLight.className === "yellow") { traffLight.className = "green"; status.innerText = "Authorised"; } else { traffLight.className = "red"; status.innerText = "Stop Working"; } }, 1000); } [/code] [l]First we find our div and our label and store them in variables. We also create a variable which will hold our set interval method. Next we call the setInterval method. The function parameter of the setInterval method checks to see which class name is currently attached to the div and then updates accordingly. This will continue to loop like this forever. To stop the loop you will need to call clearInterval as previously discussed.[/l] [l]Now you are an expert in the use of setInterval and setTimeout. Both methods have their merits and are extremely common place in the world of front end web development. I hope you found this guide to be helpful. If you have any comments or questions then please do not hesitate to leave a comment below or get in touch via the contact page of my site [/l]

Hide header on scroll down and show on scroll up - using jQuery

[l] Fixed headers are everywhere you look these days, for example; Facebook uses a fixed header as do thousands (if not millions) of other sites. It’s a wonderful thing and, if used correctly, can massively enhance the user’s experience of your site. However there are cases where it is just plain annoying and gets in the way. One site I visited recently, which shall go unnamed, had a beautiful background image of a lovely yellow orchid on the header which is permanently stuck to the top of the screen. On the desktop this was not an issue but on the mobile it took up quite a bit of valuable on page real estate and made the content difficult to view and really appreciate.[/l] [l]In light of this I have decided to share with my wonderful readers a technique that expands on the idea of a fixed header. What we will try to achieve is to hide the header on scroll down and reveal it on scroll up. To do this we will be using a combination of HTML, CSS (css transitions is where the real magic will be performed) and JavaScript (specifically jQuery).[/l] [l]So our first step, assuming you have an html file already created, is to add in a reference to the jQuery library. We will do this just before the closing ‘body’ tag.[/l] [code] [/code] [l]Next we need to add some mark up. For this example all we need is a header, a div and a footer.[/l] [code]
[/code] [l]Note – Feel free to add some content into the elements we just created, in fact if you don’t you won’t be able to view the effect we are trying to create as there will be no content to scroll.[/l] [l]Next we need to add some css:[/l] [code] body { padding-top: 65px; /* same as header height; */ } header { background: #808080; color:#ffffff; height: 65px; position: fixed; top: 0; width: 100%; -o-transition: top 0.2s ease-in-out; -webkit-transition: top 0.2s ease-in-out; -moz-transition: top 0.2s ease-in-out; transition: top 0.2s ease-in-out; } .nav-up { top: -65px; /* same as header height */ } [/code] [l]First we added some padding to the top of the body, the same as the height of the header. This makes sure the content is not moved down by the header being displayed. Next we added some styles to the header. As you can see we have given the header a ‘height’ of ‘65px’ and a ‘width’ of ‘100%’ and also set its ‘position’ to ‘fixed’. We also set ‘top’ to ‘0’ so that it sticks to the top of the viewport. Next we set up the transition effects. As you can see there is 4 similar lines of css, the first three have vendor prefixes attached and the last one is the standard non-prefixed declaration of the style. You’ll notice that I have not included a vendor prefix to support internet explorer. That is because IE10+ has stable support for transition, earlier versions of IE however are about as capable as a paper umbrella in a monsoon.[/l] [l]We have also created a class called ‘nav-up’. This class sets the ‘top’ css property of the header to ‘-65px’, which is the same as the height of the header so I’m sure you guessed that this will hide the header from view. This class will be added and removed by JavaScript as required.[/l] [l]Now we can get on with the fun stuff, the JavaScript. Just a quick note before we start the JavaScript – attaching functions to the scroll event can have a horrendous impact on your site performance. To combat this we will be if the user has scrolled on an interval of 250 milliseconds rather than executing our code for each pixel has been scrolled.[/l] [l]If you are adding the script directly into your HTML page then add it in just before the closing ‘body’ tag but after the jQuery reference. If instead of writing it on the HTML page you are adding it into an external JavaScript file then add reference to that file in the same place (before the closing ‘body’ tag but after the jQuery reference). So our first bit of JavaScript will be to create a variable called ‘doneScroll’, you may name your variable what ever you wish but whatever you call it remember the name. This variable will hold a Boolean value (true or false) this will be used to tell our code whether the user has scrolled or not.[/l] [code] var doneScroll;[/code] [l]Now we have created our variable to hold our Boolean value we need to assign it a value. To do this we need to listen for the scroll event and then once the event has fired we need to add our value.[/l] [code] $(window).scroll(function (event) { doneScroll = true; });[/code] [l]After this an interval checks every 250 milliseconds to see if the value of ‘doneScroll’ has changed. If so it runs our function, ‘hasScrolled()’, then resets the value of ‘doneScroll’ back to false. Leave the contents of the function ‘hasScrolled’ empty for the time being, we will get to that in a moment. Your code should look something like the following:[/l] [code] setInterval(function () { if (doneScroll) { haveScrolled(); doneScroll = false; } }, 250); function haveScrolled() { } [/code] [l]Now we need to add the guts into our function, ‘haveScroilled’. But before we do that we need to add some more variables to the top of our script, underneath our ‘doneScroll’ variable.[/l] [code] var lastScrollTop = 0; var delta = 5; var navbarHeight = $('header').outerHeight(); [/code] [l]Inside our function ‘havescrolled’ we need to add some code to store our scroll position in a variable. We also need to check if the user has scrolled more than delta.[/l] [code] var st = $(this).scrollTop(); if (Math.abs(lastScrollTop - st) <= delta) return; [/code] [l]Now we need to check if the user has scrolled past the header and which direction they have scrolled in.[/l] [code]if (st > lastScrollTop && st > navbarHeight){ // Scroll Down $('header').removeClass('nav-down').addClass('nav-up'); } else { // Scroll Up // If did not scroll past the document (possible on mac)... if(st + $(window).height() < $(document).height()) { $('header').removeClass('nav-up').addClass('nav-down'); } } [/code] [l]And finally we need to set ‘lastScrollTop’ to the current position, as follows.[/l] [code] lastScrollTop = st; [/code] [l]That is all there is to it, I know easy wasn’t it? Below you will see the complete JavaScript, in case you want to compare yours to mine.[/l] [code] [/code] [l]Try running your page in a web browser and hopefully you will be pleased with the result. If you have any problems with the code then please let me know and I will be happy to help. If you found this article helpful or informative at all then I would really appreciate a share on the social media platform of your choice. Please pass it around so we can help as many people as possible. If you have any comments, queries, suggestions, complaints etc. then please let me know in the comments below or send me an email, [/l] [l]Good luck in all future endeavours, whether they be web development related or not :) [/l]

Simple user controlled plain JavaScript slideshow

[l]Today I would like to share with you a simple method of creating a JavaScript slideshow. The slideshow I am going to show you is as simple as it gets. It will display some images and the user will be able to click on the buttons to cycle through the images. There are many situations where a slide show such as this is required, it’s a very common web development requirement. There are many different tutorials and guides out there instructing you how to build a slide show but most of them are vastly more complex than what we are going to build today. In a previous article we discussed adding / attaching events in a way that works cross-browser. We will be using that today (If you haven’t had a chance to check it out please go to [url=] JavaScript Generic Attach Event Handler[/url]). In this article I discussed a light weight cross-browser solution for adding JavaScript events. Head over to the post and have a quick read and grab the code. If, for whatever reason, you are unable to visit that post here is the code: [/l] [code]window.addingEvent = function (event, target, method) { if (target.addEventListener) { target.addEventListener(event, method, false); } else if (target.attachEvent) { target.attachEvent("on" + event, method); } } [/code] [l]Take that code and put it in a JavaScript file to include in our project, mine is called genericEventHandler.js. [b]Note –[/b] I highly recommend reading the post as it explains the code and also how to use it. Now we need to create a couple of files, one of which is an html page (index.html) and the other is a JavaScript file (imgGal.js) Open your html page and in the head tags add: [/l] [code] [/code] [l]These script tags link to our JavaScript files. Next we will add some mark-up in between the body tags: [/l] [code]
Plain vanilla js slide show
[/code] [l]This html mark-up displays an image and sets it’s ID and name to specific values that the JavaScript will use. It also creates a form which contains the back and forward buttons. Now that we have written our html we can get onto the interesting stuff, the JavaScript. Open up imgGal.js and add the following array: [/l] [code]var pics = ['images/cent.jpg', 'images/chick.png', 'images/spaceStation.jpg', 'images/rockandironman.png'];[/code] [l]Note – the ‘images/’ part of each item in the array is the folder in which the images are stored and then comes the file name. Next we will create the function that moves us forward through the slideshow.[/l] [code]xt we will create the function that moves us forward through the slideshow. function nxtImg() { var img = document.getElementById("slideimage"); var imgName ="_"); var index = imgName[1]; if (index == pics.length-1) { index = 0; } else { index++; } img.src = pics[index]; = "image_" + index; } [/code] [l]This function will be added to the click event of the next button, I’ll show you in a moment. When the function is called it retrieves the image object from the HTML img tag, by using document.getElementById(). Next, it splits the name attribute of that image at the underscore character, so the function can obtain the number from the ending characters of the name attribute. It stores that number in the index variable. The next part of the code performs a conditional test that checks whether the value of the index variable is equal to the length of the pics array minus 1. If this condition is true, which means the user has reached the end of the slideshow, then the script sets the value of the index variable to 0, taking the user back to the first slide. If this condition is not true then the coide increments the value of index by 1. The last 2 lines of our function set the src attribute to the new image and it also sets the name attribute appropriately so that next time the code goes through the function the current index can be determined. Now that we have discussed the function we need to implement it, so go into your html page and somewhere near the closing body tag add a set of script tags: [/l] [code][/code] [l]In between the opening and closing script tags we need to add our function to the click event of the next button. To do that we need to call our little helper, window.addingEvent. We need to tell our function what event we want to add, the element which we want to add the event to and then we tell it what to do when the event has been raised:[/l] [code]var nxt = document.getElementById("nextbtn"); window.addingEvent('click', nxt, function () { nxtImg(); });[/code] [l]If you run your page in a browser you’ll see that you can go forward through the slideshow all the way until the last slide at which point it takes you back to the beginning again. As you can see the previous button currently does nothing, but that is all about to change. We will create a function that is similar to the nextImage() function. We will add this function to the click event of the previous button. Open up imgGal.js and have a go at creating your prvImg() function. The code will be similar to the nxtImg() function except the conditional. If the index = 0, the slide show is at the first image; therefore, the function needs to loop back to the last image. Otherwise the code moves backward by one index, showing the previous image. Here is the code to move backward through the slide show:[/l] [code]function prvImg() { var img = document.getElementById("slideimage"); var imgName ="_"); var index = imgName[1]; if (index == 0) { index = pics.length - 1; } else { index--; } img.src = pics[index]; = "image_" + index; }[/code] [l]As before we also need to raise the event when the button has been clicked. So go into your html page and find the script block that we used to add the event to the next button. We need to do the same as we did with the next button except with the corresponding button and function, like so:[/l] [code]var prv = document.getElementById("prevbtn"); window.addingEvent('click', prv, function () { prvImg(); });[/code] [l]Now run your page in a browser and you’ll see that you can cycle through the slide show in whichever direction you wish. I hope this article was helpful. Thank you for enduring it until the end :) If you have any comments or questions then as always I would love to hear them. [/l]

JavaScript Generic Attach Event Handler

[postpic=cap.png class=img-responsive center-block title=Attaching events like a super hero alt=Attaching events like a super hero style=STYLE][/postpic] [l]JavaScript is an event driven language and it is wonderful. However it is plagued by a problem that server side languages are not. The JavaScript ‘standard’ is not very standard at all. The problem is that it is down to the developers of the web browsers to implement the JavaScript standard in the same way. Easy right? No, unfortunately the real world and an ideal world are two completely separate beasts. In JavaScript a very common requirement is to be able to use addEventListener and as time goes on this task is becoming less and less hassle. However if you require your site to support older versions of that pesky Internet Explorer you need use attachEvent. What a Hassle! As I’m sure you know there a seemingly endless number of JavaScript Libraries out there that take the pain out of attaching events in JavaScript. However, as awesome as these libraries are, sometimes you don’t require all of the extra features that come packed in with them. There are times when all you want to do is to add event listener but it’s such a pain in the you know what writing code every time that checks for addEventListener / attachEvent and use accordingly so I decided it would be a good idea to create a handler for this specific task that can be reused and therefore make life a little easier without the overheads of an entire JavaScript library. First I will share with you the handler then I will show you how to utilise it in your code. First you need to create a new JavaScript file. So in visual studio go to File > New > File (or ctrl + shift + N) and select JavaScript file from the list. Then in that JavaScript file add the following code: [/l] [code]window.addingEvent = function (event, target, method) { if (target.addEventListener) { target.addEventListener(event, method, false); } else if (target.attachEvent) { target.attachEvent("on" + event, method); } } [/code] [l] Our function that we have created takes three parameters; a string of the event, the target element and the function to execute. We check which function exists in the web browser and it also adds the ‘on’ to the start of the event for Internet Explorer. Make sure you save your file, I called mine handler.js but you can call yours whatever you wish. Now we are going to test the function. First you need to create a html page. If you are using visual studio you can create an html page by going to File > New > File (or ctrl + shift + n). As with JavaScript files you can use a text editor such as notepad. If you go with this option then create a new file and add the following mark up: [/l] [code] Testing Handler.js [/code] [l][b]Note:[/b] When using visual studio it adds that very same mark-up on page creation. Now between your body tags add the following mark-up: [/l] [code]
[/code] [l]Then after your title tags, in the head tags add the following css in a set of style tags:[/l] [code] [/code] [l] These styles are just to make the button nice and big and in the centre for demonstration purposes but are nothing to do with want we are trying to achieve. Now we want to call our function to add the click event to our button. Just before the closing body tag we need to add 2 script tags like the following: [/l] [code] [/code] [l]The first script tag makes reference to our external JavaScript file in which we created our handler. Inside the second script tag is where we are going to add our script to test our function. To start off we need to create a variable to represent our button, like so: [/l] [code] var theEl = document.getElementById("btnTest"); [/code] [l] Then we need to call our function, to do that we need to call window.addingEvent(). We need to add the parameters to it, we will be adding an alert on the click event of our button. Your function call should look like the following: [/l] [code] window.addingEvent('click', theEl, function () { alert("Hello World"); }); [/code] [l] Save your page and try it out. If you followed the steps correctly you should have when you click the button an alert box that reads ‘Hello World’. Thank you for taking the time to read, I hope you found this article helpful and informative. What do you do when you want to handle such a situation without a framework? I’d love to hear from you about your cross browser issues and resolutions’. Any suggestions for improvement? [/l]

Displaying and Hiding menu’s with JavaScript and CSS

[l]Recently I was asked how to create a simple JavaScript hidden menu. Such a menu could be required for any number of reasons and is a common task in the world of web development. There are many ways in which this task could be performed and the right solution for your needs may not be the same. The menu I will share with you today is the simplest way. The question posed to me was this; What is the simplest way to show and hide a menu in the JavaScript onclick event that won’t move my content?” Upon pondering that question I came up with what I am going to show you below. First we need to write some HTML. There is nothing in the HTML that is complicated in any way, just a button and an unordered list. Then we will write some basic css classes that will set the position of the elements, the button and the list. We will also set the [b]display[/b] property in the css. We will do this in two separate classes one that sets [b]display[/b] to [b]none[/b] and one that sets [b]display[/b] to [b]block[/b]. After we have written the css we will move on the JavaScript. We will use the JavaScript to overwrite the class associated with the list. [/l] [code]
[/code] [l]As you can see it is an Html button and an unordered list, nothing exciting here. The list items are just links and can be styled in any which way you like. Now we will write some CSS First we will set the [b]position[/b] of the button and set the [b]height[/b] & [b]width[/b], like so [/l] [code]button { width: 100px; height: 30px; position: absolute; top: 10px; left: 1px; } [/code] [l]Now we need to set the [b]position[/b] of the list and we also want to set it’s [b]z-index[/b] property so that it will sit over the top of anything underneath rather than disturbing the layout of the page.[/l] [code]#menu { position: absolute; top: 10px; left: 101px; z-index: 50; } [/code] [l]Our next step in writing the CSS is the most important step of them all, which is to create the classes the switch the [b]display[/b] property from [b]none[/b] to [b]block[/b] and back again.[/l] [code].menuOff { display: none; } .menuOn { display: block; } [/code] [l]Before we proceed to the JavaScript go back to your HTML and modify your opening [b]ul[/b] element. The additions are highlighted in yellow[/l] [code]

Super Simple Slideshow

[l]Today I would like to discuss with you a really simple way of creating a slideshow. Hopefully by the end of this tutorial you will have some idea of how to implement your own slide show. Feel free to use my code in your projects. If you do use my code then please show your appreciation by placing a little link ( to my site somewhere in your page with the slideshow. If you have any comments or suggestions I would love to hear from you. [/l] [l][b]What we will use[/b] We will use a combination of Html, CSS and JavaScript; specifically jQuery. [b]How it will work[/b] The slideshow will slide through the images at a set interval and will also have back and forward buttons. Most of the magic is in the CSS. So if you’re a CSS pro then this will be a breeze. The jQuery is used to add and remove style elements and to animate between the changes. The slideshow works by lining the images up horizontally by using the float attribute and viewing them through a window that has the ‘overflow’ property set to ‘hidden’. The jQuery moves the slides back and forth by adjusting the left margin of the div that contains all the images. Let’s make a slideshow The first stage is to set up the html as follows:[/l] [code]

The Slide Title

This is the slide text

[/code] [l][b]Next we will write the CSS, which is as follows: [/b] [/l] [code]img { display: block; width: 100%; height: auto; } p{ background:none; color:#ffffff; } #slideShow #slideShowWindow { width: 650px; height: 450px; margin: 0; padding: 0; position: relative; overflow:hidden; margin-left: auto; margin-right:auto; } #slideShow #slideShowWindow .slide { margin: 0; padding: 0; width: 650px; height: 450px; float: left; position: relative; margin-left:auto; margin-right: auto; } #slideshow #slideshowWindow .slide, .slideText { position:absolute; bottom:18px; left:0; width:100%; height:auto; margin:0; padding:0; color:#ffffff; font-family:Myriad Pro, Arial, Helvetica, sans-serif; } .slideText { background: rgba(128, 128, 128, 0.49); } #slideshow #slideshowWindow .slide .slideText h2, #slideshow #slideshowWindow .slide .slideText p { margin:10px; padding:15px; } .slideNav { display: block; text-indent: -10000px; position: absolute; cursor: pointer; } #leftNav { left: 0; bottom: 0; width: 48px; height: 48px; background-image: url("../Images/plus_add_minus.png"); background-repeat: no-repeat; z-index: 10; } #rightNav { right: 0; bottom: 0; width: 48px; height: 48px; background-image: url("../Images/plus_add_green.png"); background-repeat: no-repeat; z-index: 10; }[/code] [l] As you can see there isn’t anything exciting or complicated about this CSS. In fact it doesn’t get more basic, but I promise that’s all that’s needed. Next we will create the jQuery: [/l] [code]$(document).ready(function () { var currentPosition = 0; var slideWidth = 650; var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval; var speed = 3000; //Assign a timer, so it will run periodically slideShowInterval = setInterval(changePosition, speed); slides.wrapAll('
'); slides.css({ 'float': 'left' }); //set #slidesHolder width equal to the total width of all the slides $('#slidesHolder').css('width', slideWidth * numberOfSlides); $('#slideShowWindow') .prepend('Move Left') .append('Move Right'); manageNav(currentPosition); //tell the buttons what to do when clicked $('.slideNav').bind('click', function () { //determine new position currentPosition = ($(this).attr('id') === 'rightNav') ? currentPosition + 1 : currentPosition - 1; //hide/show controls manageNav(currentPosition); clearInterval(slideShowInterval); slideShowInterval = setInterval(changePosition, speed); moveSlide(); }); function manageNav(position) { //hide left arrow if position is first slide if (position === 0) { $('#leftNav').hide(); } else { $('#leftNav').show(); } //hide right arrow is slide position is last slide if (position === numberOfSlides - 1) { $('#rightNav').hide(); } else { $('#rightNav').show(); } } //changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked function changePosition() { if (currentPosition === numberOfSlides - 1) { currentPosition = 0; manageNav(currentPosition); } else { currentPosition++; manageNav(currentPosition); } moveSlide(); } //moveSlide: this function moves the slide function moveSlide() { $('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) }); } }); [/code] [l]I have commented the jQuery code so that it is easier to understand. And there you have it, a super simple slideshow that could be built by anyone. If you have any comments then please feel free to contact me  [/l]
Previous 1 Next 
Griffiths Web Design Logo by Michael Griffiths
Griffiths Web Design Logo by Michael Griffiths