Archive

Posts Tagged ‘tutorial’

Circular Image Slide with jQuery

April 25, 2009 32 comments

A friend of mine asked me to write a little script for him the other day that would do the following :

1. Slide a list of images from right to left across the screen.
2. When an image moves out of view on the left, it should get appended to the end of the list thus creating the illusion of a never ending or circular procession of images across the screen.
3. Display a “loader” image while the photographs are downloading.
4. You can view a demo of the end result here.

My first impression was that there’s almost certainly a jQuery plugin capable of doing this. Well if there is, I haven’t found it yet. While there are a myriad of “Slide” plugins available, and some come quite close, none could fulfill these requirements.

So I had to go and write my own little script. I haven’t converted the code to plugin form just yet as I need to look a few things up.

If you’d like to just jump straight in, here’s a zipped version of the demo.

First, the HTML:

<div id="slider">
<div id="imageloader">
			<img src="images/ajax-loader.gif" /></div>
<img src="images/sample1.jpg" />
		<img src="images/sample2.jpg" />
		<img src="images/sample3.jpg" />
		<img src="images/sample4.jpg" />
		<img src="images/sample5.jpg" /></div>

Nothing out of the ordinary here, just a div with a bunch of image tags. The only thing to note is the div’s “id”. The real magic happens in the JS and CSS. The pre-loader image is located inside a nested div with an id of “imageloader”. By default, our loader will be visible while our photographs are hidden.

That brings us to the CSS:

#slider {position: relative; overflow: hidden; height:155px;}
#slider img {position:absolute;	margin:0; display:none;}
#imageloader {position:relative; display:block; width: 100%; margin: 0px auto; text-align: center;}
#imageloader img { position:relative; top:70px; z-index:100; width:128px; height:15px; display:inline;}

Firstly, due to the nature of the script we have to make use of relative and absolute positioning. With that in mind, we first set our container div to relative positioning. This allows us to assign an absolute position to each child image, this is critical to the functioning of this script.

Next we set the overflow style to “hidden” – this makes sure that we don’t get ugly scroll-bars when images are moving outside of the containing div’s bounds.

We also need to set a fixed height for the container div. Failing to do so will result in the images not being displayed at all (due to the absolute positioning and overflow setting).

For the nested images, we want to set their initial display attribute to “none”. This is so they don’t display until our DOM is ready and all the images are loaded. We also need to set their positions to absolute.

For the pre-loader we just set some styles to make sure it get’s displayed in the correct position : in this case 70px from the top and horizontally in the middle of the container div. We also make sure to set the display attribute to “inline”, thus making sure the pre-loader img is shown while all other img’s are hidden.

Now for the Javascript/jQuery:

var speed = 50;
var pic, numImgs, arrLeft, i, totalWidth, n, myInterval;

$(window).load(function(){
pic = $(“#slider”).children(“img”);
numImgs = pic.length;
arrLeft = new Array(numImgs);

for (i=0;i

  • We use $(window).load() instead of the standard $(function(){}) or $(document).ready() methods due to a timing glitch in Safari. Safari reports the DOM as finished loading even while images are still downloading – not ideal if we want our pre-loader to work correctly.
  • When the DOM has finished loading, and the images have finished downloading we execute our code.
  • First we read all our images into an array of jQuery objects. We make sure the pre-loader isn’t included in this array by using $(“#slider”).children(“img”) instead of $(“#slider img”).
  • Next we loop through each image in our array and calculate a totalWidth. We need this value so that we know where to append each image when needed. Within this loop, we also set the correct absolute position for each image so that they all line up next to each other. Otherwise they’d all just sit on top of each other.
  • Once our loop is complete and we have all the initial positions setup, we create a standard javascript interval. Using this interval we can call a function every x milliseconds. We use the “speed” variable to make this configurable.
  • Now that everything’s set up, we hide our pre-loader, unhide our images and wait for the interval to fire.
  • The “flexiScroll()” function simply moves each image to the left by 1 pixel, recalculates the totalWidth and if necessary, moves the left-most image to the end of the list. Since the end of the list is currently outside of the viewable area, this gives the illusion that the list never ends.

    And that’s all there is to it.

    There of course must be a more efficient way of doing this, so if you would like to contribute, please leave a comment or contact me.

    6 jQuery snippets you can use to manipulate select inputs

    March 29, 2009 50 comments

    When it comes to manipulating the DOM, fewer elements are more tiresome than the good old select input. Fortunately for us, jQuery makes what was once a headache, a walk in the park.

    Listed below are 6 snippets which should make manipulating those selects more pleasant than say, pulling your own teeth.

    1. Getting the value of a selected option.

    $('#selectList').val();
    

    This couldn’t be simpler. Remember how before jQuery, you had to use selectedIndex and all those lovely javascript methods. I do, and I don’t miss it one bit.

    2. Getting the text of a selected option.

    $('#selectList :selected').text();
    

    Similar in concept to the first snippet with one difference. Where the first example gives you the “value” of the selected option, this example gives you the actual text contained inside the option tag.

    3. Getting the text/value of multiple selected options.

    var foo = [];
    $('#multiple :selected').each(function(i, selected){
    foo[i] = $(selected).text();
    });
    // to get the selected values, just use .val() - this returns a string or array
    foo = $('#multiple :selected').val();
    

    Once again, the same concept as the first two examples, except we’re now using jQuery’s “each()” method to loop through all selected options in a multiple select list. Each value or text value is read into an array for later use.

    4. Using selected options in conditional statements

    switch ($('#selectList :selected').text()) {
    case 'First Option':
    //do something
    break;
    case 'Something Else':
    // do something else
    
    break;
    }
    

    Much like example 2, we’re getting the text() value of a selected option, only this time we’re going to use it inside a switch statement.

    5. Removing an option.

    $("#selectList option[value='2']").remove();
    

    Using an attribute filter, we can find and therefore manipulate specific options within a select list. In this example we’re telling jQuery to find the option with value=”2″ and then remove it from the select list. We can similarly add options to a select list as we’ll see in example 6.

    6. Moving options from list A to list B.

    $().ready(function() {
    $('#add').click(function() {
    return !$('#select1 option:selected').appendTo('#select2');
    });
    $('#remove').click(function() {
    return !$('#select2 option:selected').appendTo('#select1');
    });
    });
    

    Originally posted by Jeremy Martin, here we have 2 select lists and 2 buttons. If you click the “add” button, we remove the selected option from select1 and add that same option to select2. The “remove” button just does things the opposite way around. Thanks to jQuery’s chaining capabilities, what was once a rather tricky undertaking with JS can now be done in 6 lines of code.

    And there you go. That wasn’t so bad now was it ? If you have any other handy snippets, or you’ve found an easier way to do something already covered here, why not leave a comment and share the love!

    Update:

    Incidentally, a few hours after first publishing this post I came across the following “select element cheat sheet”. Technically speaking, it may be a little big to be called a cheat sheet, but the author has given a very thorough and practical guide which I’m definitely going to be making use of.

    How to use jQuery to select a radio button from parent element

    January 9, 2009 4 comments

    A friend asked me for some help on doing the following :
    1. You have an unordered list – within each list item you have a radio input.
    2. When you click on the list item (i.e. the entire container), it must a) select the radio input and b) add a css classname of “selected” to the list item.

    You can find a demo here.

    First, the html :

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    	<!-- include our jquery scripts -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
        <script src="js/radio.js" type="text/javascript"></script>
        <style type="text/css">
        	li { color: #000; }
        	li.selected { color: #FF0000; }
        </style>
    </head>
    <body>
    	<div>
    		<ul>
    			<li class="test">Test 1 <input type="radio" name="test" /></li>
    			<li class="test">Test 2 <input type="radio" name="test" /></li>
    			<li class="test">Test 3 <input type="radio" name="test" /></li>
    			<li class="test">Test 4 <input type="radio" name="test" /></li>
    			<li class="test">Test 5 <input type="radio" name="test" /></li>
    		</ul>
    	</div>
    </body>
    </html>
    

    There is nothing out of the ordinary here – just a simple unordered list of radio inputs.

    Next, the js (radio.js) :

    $(document).ready(function(){
    	$('li').click( function(){
    		$('li.selected').removeClass('selected');
    		$(this).addClass('selected');
    		$(this).children("input[type=radio]").click();
    	});
    });
    

    1. First – we tell jQuery to execute the following code once the document has finished loading, ensuring that the DOM has been registered successfully.
    2. Next we bind a click event to all list item elements on the page – you can of course change this to all list items with a class of “myselection” for example ( $(“li.myselection”).click… )
    3. When a list item is clicked – we first need to remove the “selected” class from all other list items.
    4. Now we need to add the “selected” class to the list item which fired the event ( $(this) ).
    5. Finally, we need to make sure that the radio button inside the list item is “clicked” : we do this by using the .children() selector and executing a click() event on the input.

    The important bit is the $(this).children(“input[type=radio]”) selector. What we’re doing here is telling jQuery to find all inputs of type radio (i.e. all radio inputs) inside “this” list item (i.e. the list item which was clicked on). We then use .click() to..as you guessed it… execute a click event on the returned element (in this case the radio input).

    And that’s all there is to it. You can read up some more on jQuery selectors here.
    I would also highly recommend reading the following article : Improve your jQuery – 25 excellent tips.

    Writing dynamic classes with PHP

    October 13, 2008 Leave a comment

    I recently had the necessity to write a dynamic class (i.e. where methods, or properties of the class are determined during runtime) and in doing some research, stumbled on to this very helpful article :

    Going dynamic with PHP

    The author (Jack Herrington) goes to a lot of trouble explaining how the magic __get(), __set() and __call() methods work and how best to use them.

    It does get a little bit complicated towards the end, but is a good example of a)why one should or need to use a dynamic class/object and b)how to implement it successfully within your application.

    Beginners tips for form processing with PHP

    September 9, 2008 Leave a comment

    I remember when first starting with the whole PHP / Web development scene that processing forms was a real hassle. This was back in the day when php_global_vars was still accepted as the “in” thing and you had to use each form variable as php variable. I only found out about $_GET (or as it was $HTTP_GET_VARS) later on, much to my consternation.

    I did however, come up with a workaround at the time, and it’s stuck with me ever since. I fully realise that the PHP superglobals make this method somewhat redundant, but I still find it useful in larger forms, especially when you’re trying to group related form variables.

    The basic idea is to add each form variable to an array. In my case this array is usually called “items”. For instance, I have a standard login form with the usual login and password fields. I define each field using the following method : <input type=”text” name=”items[login]” value=”” />  – for the novices out there, notice the “items[login]” bit. What this does is assign the value for “login” to the “items” array. This array is then accessed via the $_GET[“items”] or $_POST[“items”] superglobals. Of course you can have multi-dimensional arrays – for example : <input type=”text” name=”items[user][login]” /> and so on and so forth.

    Now the really useful part comes in when you are looking to sanitize only certain parts of your user input (yes I’ve had instances where I purposely didn’t want to sanitize incoming data). For a good tutorial on how to sanitize user input  – try this one . You can also assign input data to a session variable more easily. I.e $_SESSION[“userdata”] = $_GET[“items”][“user”].

    Lately, I’ve found this method extremely useful when binding form data to my MVC model data. So lets say we have a form where a user can edit his/her profile. In addition, this form also has space for the user to edit his password. Usually, password and profile information is stored in 2 separate tables. Which means that I would use “user[]” for the password fields (since you need a “confirm password” field aswell) and I would use “profile[]” for the user’s profile data. Then once inside the PHP script, I can then bind $_GET[“user”] to my user model, and $_GET[“profile”] to my userProfile model. The only constraint then is making sure the form field matches a model field.

    I admittedly haven’t seen this method being used all that often, and it does make me wonder if it goes against some “best practice” that I’m ignorant of, or perhaps I’m just way ahead of my time 😉

    Either way, hopefully it can be of some help to someone out there. I do promise though, that when I’ve improved my blogging and therefore writing skills, I’ll revisit this post and make it more “noob” friendly.