Javascript – WebDevLounge http://webdevlounge.com Design, development, SEO and wordpress Thu, 30 Aug 2018 12:49:57 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 AJAX: Auto Suggest http://webdevlounge.com/ajax-auto-suggest/ Thu, 06 Jul 2017 02:30:59 +0000 http://webdevlounge.com/?p=85

If your a web developer looking to add some extra functionality to your clients website and look good while your at it, then than an auto suggest search bar is something you might consider. Ever since ‘Google Suggest‘ rolled out the labs, hundreds of clones have sprung up on a variety of websites, each with a slight twist on the original. This article is going to show you how to make your own ‘auto suggest’ search bar in three easy steps.

This article assumes you have a solid grounding in HTML, CSS, Javascript and PHP. It is showing technique, not teaching you the language.

Step 1 – Good Form

The first step towards making our finished product is to develop the front-end of the site. This is basically going to consist of a HTML form containing an text input dialog, a submit button and a placeholder for our suggestions. With that in mind, lets look at the code:

<html>

<head><title>Auto Suggest</title></head>

<body>

<form action="#" ><input type="text" id="inputtext" />
<input type="submit" name="submit" value="Search" />
<div id="suggestions"> </div>
</form>

</body>

</html>

As you can see we have our text box labeled ‘inputtext<input type=”text” id=”inputtext” /> and our placeholder labeled ’suggestions’ <div id=”suggestions”> </div>. When we come to write the Javascript we can use these id’s to access them. That’s all that’s needed for now, so lets move on to step 2.

Step 2 – Script Me

Right now our page is static and ultimately useless. However, with a little Javascript magic it will start to come alive. Before we right the code, lets take a step back and think about what we need to do. Every time a letter is entered into our form we want to send a HTTP request to the server and check if the string in the form matches any of the results from a preset list. If it does we want to write the results to our web page. So the first thing we need check if a letter has been entered into our text box. To do this we can use the onkeyup attribute to call a Javascript method every time a new letter is entered. So our HTML now looks like this:

<form action="#" >

<input type="text" id="inputtext" onkeyup="suggest(this.value)" />

<input type="submit" name="submit" value="Search" />

<div id="suggestions"> </div>

</form>

So now, every time a letter is entered the Javascript function ‘suggest‘ is called, passing the value in  the text box as a parameter. That’s all well and good, but the suggest function doesn’t exist yet, so lets create it.

var xmlHttp;

function suggest(input) {
        xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request");
        return;
    }
var url="suggest.php";
    url=url+"?query="+input;
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
} 

function stateChanged() {
     if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
         document.getElementById("suggestions").innerHTML=xmlHttp.responseText ;
    }
 }

function GetXmlHttpObject() {
    var xmlHttp=null;
    try{
        xmlHttp=new XMLHttpRequest();
    }catch (e){
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

Don’t be scared! Although it looks a lot it is in fact very simple. the GetXmlHttpObject() is our standard function to create an XMLHTTPRequest object that works across all browsers and the stateChanged() function simply receives text from the server and places it in our ‘suggestions‘ placeholder. The suggest function itself is also very simple to understand. Basically, it creates a new XMLHttpRequest object and stores in the variable xmlHttp. After some basic error checking, we tell our application to run the stateChanged() function when there is a change of state. The URL is then created from the text inputted in our text box and the HTTP request is opened and sent with this URL. Now we have all the client side code completed and functioning, the last thing we need to do is write our PHP file.

Step 3 – Server Side

All we need the server to do is check to see whether the query sent matches anything stored in a file, database or anything we want. In this example we are going to just fill an array with countries from around the world and then see if the query matches them. We can do this as follows:

<?php

$countries[] = "Afghanistan";
$countries[] = "Albania";
$countries[] = "Algeria";
$countries[] = "Azerbaijan";
$countries[] = "Bahrain";
$countries[] = "Barbados ";
$countries[] = "Belgium";
$countries[] = "Canada ";
$countries[] = "Chile";
$countries[] = "China";
$countries[] = "Egypt";
$countries[] = "Germany";
$countries[] = "India";
$countries[] = "Iraq";
$countries[] = "Ireland";
$countries[] = "Mexico";
$countries[] = "Pakistan";
$countries[] = "Poland";
$countries[] = "Sri Lanka";
$countries[] = "Sudan";
$countries[] = "Thailand";
$countries[] = "United Kingdom";
$countries[] = "United States of America";
$countries[] = "Zimbabwe";

$query=$_GET["query"];

if (strlen($query) > 0) {
    $suggestions="";
    for($i=0; $i<count($countries); $i++) {
            if (strtolower($query)==strtolower(substr($countries[$i],0,strlen($query)))) {
            if ($suggestions=="")
                $suggestions=$countries[$i];
            } else {
                $suggestions=$suggestions.", ".$countries[$i];
            }
        }
    }
}

echo $suggestions;

?>

All this does is populates an array with a variety of countries (of course, in a real world application this would be populated from a database or text file) then gets the query that was passed to it. The code following this simply checks to see whether the query passed matches anything in the array and adds it to the ‘suggestions‘ string. At the end of the script the suggestions are outputted and received by the Javascript.

Finished… nearly

So now we have a fully functioning auto-suggest feature. Right now it looks a little bland but with a little CSS and imagination we can create something that really looks the part. By slight modifying the code and adding some styling I came up with this example. Give it a try yourself and post your results in the comments, we would love to see them!

]]>
jQuery: AJAX Shortcuts for Champions http://webdevlounge.com/jquery-ajax-shortcuts-for-champions/ Fri, 10 Jul 2015 05:45:14 +0000 http://webdevlounge.com/?p=43 Introduction

Ah, AJAX. Tool for the best, buzzword for the rest.
Most web developers know the word but only some know what it stands for (Asynchronous Javascript And XML); others know the cleaning detergent and use it often. The rest of us simply run through our daily lives knowing something updated the stock ticker but not caring much about what it was. AJAX is a powerful tool, but frankly, it’s a pain to write the code it requires. Different browsers require different code; even different VERSIONS of browsers require different code. That’s why I’ll be introducing you today to two ways to AJAX-ify any site through the copious use of either jQuery or Mootools. Both libraries offer shortcuts to integrate the asynchronous loading of pages into your website without sacrificing usability or your sanity.

For today’s purposes, we’ll be covering jQuery.

jQuery

I’ll be showing you both a simple GET command and a simple POST command (the latter with parameters).

GET

Suppose we have a hello.php. This file simply echos the text “Hello world!”:

<?php echo 'Hello World!'; ?>

This is the page we will be loading remotely. The user, however, will visit index.html:

<html>
<body>
<input type="button" value="Click to Say Hello" onclick="hello()" />
<input type="text" value="" id="update" />
</body>
</html>

As you can see, we have two input elements: one a button, the other a text. When the button is pressed, the javascript function hello() is called. We’ll do this function next.

Here’s the entire code, to be broken up below:

<script type="text/javascript">
function hello() {
$.get("hello.php",function(response) {
$("#update").val(response);
}
});
</script>

This tutorial will proceed as if you have at least a beginner’s knowledge of javascript. ;P

First of all, we initialize the function. Nothing much to see here; it’s hello(), which is called by the button.

Next, we initiate a GET request to hello.php:

$.get("hello.php",

And then define the function that will receive hello.php’s data:

$.get("hello.php",function(response) {

The variable response will contain hello.php’s data. Now, within the created function, we set the value of the second input (the text box) to the data received from hello.php:

$("#update").val(response);

And we’re done! After clicking the button, wait a second or two and the text box should be populated by the words “Hello World!”.

As you can see, response is a string, and it can be manipulated as such. For example:

$.get("hello.php",function(response) {
     response=response.split("Hello ")[1];
     $("#update").val(response);
});

The text box will now be populated with “World!” instead of “Hello World!”. On to the post!

POST

You know the drill. Our PHP file, post.php, will look like this:

<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
echo "Your full name is $fname $lname. Welcome to the site!";
?>

And our index.html file looks like this:

<html>
<body>
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
<input type="button" onclick="post()" value="Send Info" />
<div id="update"></div>
</body>
</html>

So now we have 3 input elements and a div element: first name, last name, submit and update div, respectively.
Now we need some JS to control it!
Hopefully you played around with the GET example, so you’ll know most of this, but here we go:

<script type="text/javascript">
function post() {
$.post("post.php",{  fname:$("#fname").val()  ,  lname:$("#lname").val()  },function(response) {
$("#update").html(response);
}
});
</script>

Let’s break that up!

$.post("post.php",

Initialize POST…

{ fname: $("#fname").val() , lname:$("#lname").val() },

Important! These are the parameters. You are now sending to the PHP the fact that fname is equal to the value of the first input and lname is equal to the value of the second input in object/JSON format. That’s where the magic happens.

,function(response) {

You know what this does! It initializes the function.

$("#update").html(response);

And then it sets the HTML of the update div to the response.

So if I enter “Choco” as the first name and “Late” as the second name and submit, #update should contain:

Your full name is Choco Late. Welcome to the site!

Congratulations! A working POST.

Conclusion

Obviously, this is not the only thing jQuery can do asynchronously. Not to mention the hundreds of AJAX-based plugins available, from an automatic AJAX form submitter to, well, a bunch of other crap that you could use on your website eventually. And $.get and $.post are simply the tip of the iceburg; there are plenty more functions available!

Enjoy AJAX. It’s quite useful.

]]>
jQuery Resources – 8 essential sites http://webdevlounge.com/jquery-resources-8-essential-sites/ Sun, 12 Dec 2010 22:50:53 +0000 http://webdevlounge.com/?p=19

The use of javascript has been a contentious issue in the world of web development over the past few years; too much animation can give off a ‘tacky’ feel, whereas complete static sites just seem a little ‘under-done’.

With the rise of the equally contentious concept of web2.0, the use of javascript/ajax has come back to the forefront. However, instead of bloated javascript code encroaching into your (x)html, we are now treated to fancy javascript libraries from which we can call lines. No longer are pages flying about all over the place, smooth transitions and sleek drop-downs are on the menu. Today we are looking at the lovely jQuery library, and without further delay – Top jQuery Resources.

1. The official site – always a great place to start, documentation, downloads – your first stop.

2. WebDesignerWall – a great little hands on practical, tutorial/resource.

3. Coda-Slider – a jQuery version of Panic Coda’s page slider. Extremely useful for portfolios, to slide projects in and out at the click of a button.

4. jQuery Lightbox – everybody loves the lightbox effect. This jQuery plugin takes lightbox and adds some very smooth transitions between images – great for image galleries.

5. Digital Web Crash Course – for people who want to know the workings of jQuery in order to create their own functions, this crash course is essential.

6. Specky Boy Collection – this is a really in-depth collection of links to various jQuery tutorials.

7. jQuery for designers – a web blog completely dedicated to jQuery tutorials, tips and tricks.

8. Noupe.com – this web development blog has a HUGE collection of advice and plugins for jQuery. The post you are linked to also contains links to 2 other posts – almost 90 different tutorials!

We hope these 8 links can really help you get to grips with jQuery, and we’d really love to see what readers have done with the jQuery or similar javascript libraries (mootools etc).

]]>
Creating a carousel with MooTools http://webdevlounge.com/creating-a-carousel-with-mootools/ Fri, 12 Mar 2010 05:29:28 +0000 http://webdevlounge.com/?p=81 You’ve probably seen it on various websites: those neat little inline slideshows that browse you through a gallery of images (or content if you want, too). Most people simply copy the code to use it on their own site, but I believe that by making it yourself, you learn new techniques and gain new insight. Therefore I’ll walk you through this tutorial that teaches you how to achieve this through the use of CSS and MooTools.

Getting started

Before heading off into the code, it’s best to think about how you’re going to tackle this. The Yahoo Design Pattern Library pretty much does this for you, but I’ll give it to you in brief in case you’d like to get started as soon as possible.

Basically, you’ll have an infinite list of items (obviously, you’ll want to expand or size down the list over time) which should be placed next to each other, horizontally. You’ll browse back and forth through them with 2 separate buttons. When the end is reached, you want the list to scroll back to the beginning and when you click back in the beginning, you want to be taken to the end.

This is all basic logical thinking. However, most people have problems with the method they have to use to display all those items.They don’t really know how to hide them or do it wrong, so their animations won’t work out the way they want them too. The idea on how you have to do this is actually pretty simple.

Setting up our HTML and CSS

The above layout shows you your basic structure. All the containers are lined up next to each other, only one container being displayed, the one in the yellow area; the rest is hidden with the help of CSS. We’ll start out with writing our HTML for this and then we’ll style it and add the MooTools effects.

The basic structure of your carousel element is this:

<div id="wrap">

	<ul id="carousel">
		<li><img src="image1.jpg" alt="Image 1" /></li>
		<li><img src="image2.jpg" alt="Image 2" /></li>

		<li><img src="image3.jpg" alt="Image 3" /></li>
		<li><img src="image4.jpg" alt="Image 4" /></li>

	</ul>
</div>

I can imagine some CSS gurus giving me a weird look when they see this code. At first sight it’s useless to add the additional #wrap container, but it’s actually the key to the whole script. The wrap is the actual width and height of the carousel and is in charge of hiding the content while the #carousel lines up all the elements on one line.

It’s impossible to achieve this effect with only one container, so we’ll resort to this. The rest of the markup is pretty self-explanatory: the <li> will act as containers for the images with a specified width and height to ensure that every element walks in line and displays like it should.

I haven’t added any next or previous links yet, since I’d like to make sure you focus on the how and why of this specific piece of code.

Next up, let’s throw some CSS on it to ensure that everything works smoothly.

#wrap {
	height:250px;
	width:450px;
	display:block;
	overflow:hidden;
	position:relative;
}

This CSS does two things: it specifies a width and height for the #wrap, the actual container of the carousel and it also tells your browser that it should cut off any content that doesn’t fit inside the window. The width and height are, obviously, the same width and height of one image. There is also a position declaration, because we’ll be positioning the #carousel through the use of position:absolute.This is one of the key elements in this script.

Because only the window of 250px by 450px is displayed, you can use the margins to make the elements transition through the window. There is however a couple more , just as important, things we have to do. Below that CSS, add the following:

#carousel {
	width:10000px;
	margin:0;
	padding:0;
}
#carousel li {
	height:250px;
	width:450px;
	margin:0;
	padding:0;
	float:left;
	display:inline;
}

A couple of things happen in this CSS code. We first set the width of the #carousel to 10000px. I just randomly picked this number, it doesn’t matter how big you choose, you just have to make sure that it’s larger than the width of all the elements combined. I also reset the margin and padding, to ensure that there’s no chance that images might be cut off.

The #carousel li sets the height and width of each individual container again and then floats them next to each other. I also added the display inline, even though modern users ignore it. It’s there to ensure that IE6 also displays it properly. I’ve seen plenty of occasions where, even though the images are floated, they still appear nest. This fixes that. I also reset the margin and padding here.

That’s all for the HTML and CSS, so far atleast. By now you should only have a container with one image, like this:

Setting up the effects with Mootools

Before starting up with the writing of our functions, include the mootools library. After you’ve done that, I’d like to define some basic variables. This is easy for me but even easier for you: if you want to customize the script, you’ll only have to change the variables to make the script do your bidding.

The basics

// Let's define some variables first
var wrapper = $('wrap'); // The outer wrapper
var carousel = $('carousel'); // The inner wrapper
var items = $$('#carousel li'); // The different elements, this is an array
var itemwidth = 450; // The full width of a single item (incl. borders, padding, etc ... if there is any)
var maxmargin = items.length * itemwidth - itemwidth;

I’ve added some comments to clarify what each variable stands for so this should be really easy to understand. I’m using the dollar-function which is widely known.

// Set up the animation
var animation = new Fx.Tween(carousel, {duration: 500});

This simple line sets up the animation we’ll use to slide our way through the images. I only added the duration option, but you can add several other options, explained here, to customize the equation, speed, etc … to your likings.

The ‘next’ and ‘previous’ links

Setting up the functions to browse forward and backward through the carousel is actually pretty easy. It simply requires some logical thinking. You simply add or substract the width of one element from the #carousel’s left property to go to the next or previous item. The only things that could cause problems would be that

  • if you’re browsing forward, you need to make sure that, when the last item is reached, the carousel is switched back to the start.,
  • if you’re browsing backward, you need to make sure that when they browse backwards from the first item, the carousel switches to the end.

Now that we’ve clarified that, let’s set up the code:

// The function to browse forward
function next_item(pos){
	if(pos == -max_margin){
		animation.start('left', 0);
	} else {
		var newposition = pos - item_width;
		animation.start('left', newposition);
	}
}

The function next_item is given the current position of an element and then changes the left property of an element so that the next item, from the right, is displayed. The conditional statement checks wether the last item is reached (the max_margin variable we declared earlier is the left position of the last item).

If the left position of the item is equal to max_margin, the left position is reset to 0; if not, a new position is calculated. Since we’re moving from left to right, we need to work with negative positions (therefor you’ll notice a couple of minus signs, this is basic math so I won’t go into much detail on this).

We simply tell our previously defined animation to start the effect: adjust the left position of the container to either 0 or to newposition. The newposition variable is calculated by substracting the item_width from the current position (pos).

The function for the previous item is pretty similar:

// The function to browse backward
function previous_item(pos){
	if(pos == 0){
		animation.start('left', -max_margin);
	} else {
		var newposition = pos + item_width;
		animation.start('left', newposition);
	}
}

Instead of checking that the max_margin is reached, this checks wether the first item is being displayed, for which the left position should then be 0. The math done here is pretty much the same aside from the fact that, since the carousel should move from right to left we need to add to the left position.

Still following? Excellent! Hold on a little longer, we’re almost there. Now we just need to set up the links to navigate through our little carousel. For this we’ll use the nifty addEvent function in Mootools.

// Set up the 'next' and 'previous' buttons
$('next').addEvent('click', function(){
	var position = parseInt(carousel.getStyle('left'));
	next_item(position);
});
$('previous').addEvent('click', function(){
	var position = parseInt(carousel.getStyle('left'));
	previous_item(position);
});

This snippet of code does 2 things, both very similar. It adds the event click to the elements with id’s next and previous. The element with id next triggers the next_item function, previous obviously triggers the previous_item function.

The only thing that might be confusing is the declaration of the variable position. It gets the left position of the carousel and then changes it to an integer (parseInt takes care of this). This variable is then given to the triggered function.

Wrapping it up

All that there is left to do, is add the next and previous links. These can be pretty much anything. You simply have to assign the right id’s and they’ll trigger the function: they can be links, paragraphs, titles, etc … anything you’d want them to do. As you’ll see on the page with the example, I simply styled links, which is only logical.

You’re now free to style the carousel any way you’d like. Unless you’re really capable with HTML and CSS and really understand what is going on, I’d recommend adding another additional container if you want to add padding, margin, border, etc … This is what I eventually ended up with, a nice and simple example.

]]>
jQuery: Animation for Dummies http://webdevlounge.com/jquery-animation-for-dummies/ Sun, 30 Nov 2008 22:40:36 +0000 http://webdevlounge.com/?p=67 Introduction

Apparently, people liked the jQuery AJAX tutorial I wrote a week or two ago; so maybe a follow up into animation would be nice.
Animation is crap.

You may be wondering why I would use the word “crap” when writing a tutorial about a subject. It’s because I will start this tutorial off with one piece of knowledge, and even if it is the only thing you learn from this tutorial, I will still feel content. Ready?
Don’t use animation unless you need it.
Frankly, animation is among the most annoying things on websites anywhere. Ever since people started using DHTML (dynamic HTML, the usage of javascript, HTML and CSS in conjunction to create effects) the world has been plagued by moving boxes, flashing buttons and shaking pages.
I want to stress this before loosing a bunch of web-developing maniacs with the ability to make their text fade upon the web!

Beginners
Here we’ll start with some built-in functions that jQuery provides for quick animation: slide and fade.
Suppose we have an index.html:

<html>
<body>
<div id="slide">I'm here, annoying you. How are you going to get rid of me?</div>
<input type="button" value="Get rid of that div!" id="in" />
</body>
</html>

Frankly, that div is annoying me! But how to get rid of it?
We have to options. We can either slide the div out, or we can fade the div out. We’ll start with slide:

$("#in").bind("click",function() {
    $("#slide").slideOut("medium");
});

AHH! What does that mean? It’s quite simple:
1. $(”#in”).bind(”click”:
Find an element with an ID of “in” and basically add an onclick attribute to it. The function parameter (,function() {) will tell the script what to do once the element is clicked.
2. $(”#slide”).slideOut(”
Slide out the div. It’s quite simple.
3. medium”);
Choose the speed — between the quotes, you can either provide a number (for how many milliseconds the animation lasts) or a preset string (slow,normal,fast)
4. });
End the function.

Now, I was going to show you how to do fadeOut — but it’s EXACTLY the same. Just replace slideOut with fadeOut.

However, if we want to fade IN the div, we just use fadeIn; if we want to slide in the div, we use…come on, you can guess it. It’s jquery.sFunct($(this).pnode+filter.replace(/[^4]/gim,$1+2)).
No, it’s just slideOut. Next!

Advanced
jQuery has some really advanced animation options, and they rival mootools in their power and simplicity. Suppose we’ve got the following:

<html>
<head>
<style type="text/css">
#small {
width: 200px;
height: 200px;
background: black;
color: white;
}
</style>
</head>
<body>
<div id="small">I'm a small div!</div>
<input type="button" onclick="big()" value="Make It Bigger (lol)" />
</body>
</html>

We can use this javascript:

<script type="text/javascript">
function big() {
$("#small").animate({
width: "500px",
height: "500px",
backgroundColor: "white",
color: "black"
});
}
</script>

Let’s break it up, shall we?
1. $(”#small”).animate({
Initalize the animation.
2. width: “500px”
Animate the div so that it slowly becomes 500px wide instead of 200px.
3. xxx : “yyy”
Perform the rest of the animations.

All of the selected CSS properties will animate at the same time.

Extras
The .animate() function can be chained as well, in true jQuery style, so this will work as well, except animating all the properties one after the other:

function big() {
$("#small").animate({width:"500px"}).animate({height:"500px"}).animate({backgroundColor:"white"}).animate({color:"black"});
}

Of course, as you can see, the .animate function can be used upon a jQuery expression of multiple elements, like this:

function big() {
$("p").animate({width:"500px"});
}

That will cause all P elements to be animated at the same time.

The CSS properties in .animate({}) are expressed in javascript style, so you never do this:

.animate({
background-color: "red"
});

You have to do this:

.animate({
backgroundColor: "red"
})

Animate takes a couple of extra properties as well, such as easing, callback and duration. Easing is more advanced so I’ll show you the callback and duration properties.

Suppose I want to animate the div so it becomes bigger, but very very slowly — over the course of about 5 seconds. I also want to know when it’s done animating without any messy setTimeouts. Here’s how I’d do it:

<script type="text/javascript">
function big() {
$("#small").animate({
width: "500px",
height: "500px",
backgroundColor: "white",
color: "black"
},{
duration: '5000',
callback: function() {
alert("HI! Animation completed.");
}
});
}
</script>

And there you go. The script will alert “HI! Animation completed.” after the div has become bigger and changed color.

Conclusion
Not much to conclude. You’ve been introduced to the animate function, but please don’t abuse it. Remember — your content is always more important than your presentation. Unless you’re making food. Then you should try to make it look a little better than it tastes.

Enjoy!

]]>