Monday, January 9, 2012

Looping through select fields and getting the selected text using jQuery

I spent a little time wrestling with this and I thought it may come in useful to pop on to the blog. In my situation I had to loop through a number of select items as I needed to post some data. I needed to do this as I had to pass 3 sets of information from each select / drop down box. It had to be done this way because I was using the dropdown boxes for a number of different functions, some needed to pull the text and some needed to pull the value.
  • The name of the select box
  • The value of the select box
  • The text of the selected item
$('select').each(function(){
     var selected_text = $(this).children('option:selected').text();
})
Happy programming :)

Labels: , ,

Friday, July 16, 2010

How to quickly cache images for css using jQuery

Please note, there are other ways of doing this, but this is a quick method for caching images for your page, using a very simple piece of jQuery.

If you use CSS to change the backgrounds on an element when a user moves their mouse over it you will the new image to display as soon as it happens. If the browser has no record of the image then it has to has immediately send a request to the server for the image. This can take precious seconds and in some cases, could spoil the whole look of your well designed element.

There are a number of fancy jQuery functions that may allow you to do this in a more compliant standard, but I can't see any harm doing it this way:

1. Create an empty element within your webpage (I put it just before </body>), for the case of the example, our element is a div element named 'imageCache':

<div id="imageCache"></div>

2. Set its display attribute to none, like so:

#imageCache{display:none;}

This stops the element from showing when the browser displays the page.

3. In your jQuery code, set the HTML of the element to use the images, in your document.ready function like so:

$(document).ready(function() {
$('#imageCache').html('<img src="image1" /> <img src="image2" />');
})


4. The Images will not appear as they are inside an element which has no visibility thanks to the CSS.

Hey Presto, your images are now ready to be used.

Some people may say that the element should not be added to the web-page unless it is to be used to display something. They may have a point, but if you want a quick solution and you are a jQuery newbie, this will do you just fine and will still pass W3C validation. If that is the case and you do not want an empty tag floating around your HTML source code then use jQuery's 'append' function and add the element in to the DOM and add the images using that method, like so:

$('body').append('<div id="imageCache"><img src="image1" /> <img src="image2" /></div>');

Please also note that this could be done entirely using CSS whereby you load in the images directly in to the HTML within your element, they would still be hidden because of the CSS, the above method is the alternative using jQuery.

Labels: , , ,

Tuesday, June 22, 2010

jQuery is what JavaScript should have been - introduction and examples

jQuery is what Javascript should have been - introduction and examples
Please note this is not an extensive jQuery tutorial, it is more about how jQuery is the better option for client side browser scripting compared to javaScript and is aimed at people looking to change over from one to the other. jQuery is a framework that uses javascript to 'write less and do more'.

jQuery is what Javascript should have been. This is most definitely true, but is somewhat harsh I think. Javascript was created by Netscape as a language that allowed the programmer/developer of the website to manipulate the various elements of a web page. It was called JavaScript after Sun licenced their Java brand name to give the language a little more credibility. JavaScript allowed the creators of the website to display and showcase the content with a little more flair.

Like a lot of things on the Internet, the use of JavaScript was exploited and made web surfing painful at times. JavaScript can be used to open multiple windows at once and these 'popups', especially when a user was connected to the 'net using a dial up connection and tens of windows would open up simultaneously offering you products ranging from hair extensions to god knows what. Popups thankfully became less of a problem as browsers and firewall software improved including pop up blockers.

Another problem and some may argue a bigger problem was the way the software ran in browsers. Javascript was created by Netscape and was thus adopted by other browsers, unfortunately the language was not adopted as a standard and the browsers (namely Internet Explorer) did not all act the same when they came across JavaScript - this gave developers a huge problem. Scripts had to be tested in mutliple browsers and debugging time obviously shot through the roof.

This is where the wonder of jQuery comes rushing through. JavaScript had started to be used more and more as many online applications needed the little bit of extra functionality to deliver. jQuery took away the need for writing scripts for multiple browsers. You could in a reduced manner add in code in one line that would without jQuery library taken 10 or so line of code. It really did make it that easy.

Below are a number of examples of some of the more common tasks that you can use JavaScript for. Starting with the basic task of obtaining an element's value right through to the more advanced method of making an AJAX call. Each example will have the jQuery code followed by the JavaScript that would have been necessary without the jQuery library. jQuery also allows for developers to easily add events to elements, i.e. a mouse click. This is where we will begin as it one of the cornerstones of using jQuery and using for the coding on the web.

For the sake of this tutorial, I will be an using an element named 'myElement' - which could be anything like a paragraph, div, input. If any other elements are used or are a special, I will explain further where necessary.

You will see the $ sign a lot throughout this exercise, it basically means let jQuery handle the code.

Adding an event in jQuery:

This is how you add an event in jQuery:
$('#myElement').click(function(){
alert('Hello World');
});


Like with all jquery it works in all browsers, now lets take a look at the above in plain JavaScript, unfortunately there are a number of issues when it comes to adding event handlers - Internet Explorer. Microsoft, in their infinite wisdom decided to add their own event handling system.

Here is the the code according to w3c specification - i.e. for Firefox, Opera, Chrome using an anonymous function as the second parameter - you could as easily add a reference to another function, i.e. myFunction() instead like I have shown on the Internet Explorer example below

myElement.addEventListener('click',function(){
alert('Hello World')
},false);


The 3rd parameter given here as boolean = false refers to refers to event bubbling and that goes beyond the scope of this introduction, rest assured though, jQuery makes that easier too!

Here is the code for Internet Explorer

myElement = document.getElementById('myElement');
myElement.attachEvent('onclick',myFunction);


The problems here not only lead to writing more code to get the reference for the variable, address both w3c spec and non w3c spec browsers but you may also have to write code that detects the browser type so that your script doesn't cause errors.

Getting the value of a input form field

This includes select inputs and and select, most form values- I know, how easy...

var myVar = $('#myElement').val();

Now let's look at this in plain JavaScript to obtain a text input value:

var myVar = document.getElementById('myElement').value;

For a select dropdown menu it's even more cumbersome, not only do you have to select the element from a form, but you have to go through the array of options to find the value:

var mySelectDropDown = document.forms['myForm'].mySelect;
var selectChoice = mySelectDropDown[mySelectDropDown.selectedIndex].value;


Modifying an Element's CSS property

Let us look at this in jQuery:

$('#myElement').css('background-color','#000000');

Now let us look at this in JavaScript:

In this case we are going to change the background color of an element and set it to black(#000000). First we have to find the element using the document.getElementById() function. We then have to name the CSS property

myElement = document.getElementById(myElement')
myElement.style.backgroundColor = "#000000";


Again, how much easier is this? The added bonus is that it uses the same referencing system that you may be used to using in CSS, rather than a different reference, again saving you time and effort.
On to Ajax...

Performing jQuery Ajax calls couldn't be easier. This example uses a the .open() method, but there are a number others you may be interested in, namely $.get() and $.post(), so you may want to read up on them later. The following example takes the contents of another page and then adds the content to the element:

$('#myElement).open('myOtherPage.html);

Now let's look at that in plain JavaScript:

//first we have to create the XmlHttpRequestObject
var myAjaxObject = createXmlHttpRequestObject();
//then we create the function that triggers the event
function getContents() {
//reference the source to open
myAjaxObject.open('get', 'myOtherPage.html);
//assign the function that will handle the response
myAjaxObject.onreadystatechange = handleInformation;
//declare extra parameters, not needed when using the get method
myAjaxObject.send(null);
}
//now we have to create the function to handle the above:
function handleInformation() { //check the state of the request
if(myAjaxObject.readyState == 4 && myAjaxObject.status == 200) {
//Add the information to the myElement ID
myElement = document.getElementById('myElement');
myElement.innerHTML = myAjaxObject.responseText;
}
}

Hope this helps.

Labels: , , ,

Wednesday, June 2, 2010

What is it be a web developer?

This piece is not about the history of the web, more about how the web grows and how new technologies constantly change the nature of what it means to be a web developer.

The Internet is growing (nothing new there with that statement). When a new idea or piece of technology springs up, developers are needed to be able to write software for it so that the new innovation gains ground and popularity.

The term 'web developer' came about because the web became the most sought after use for the Internet. When this happened people wanted to access information quickly and reliably. As a result web developers started programming on systems and servers that could dish out this information in a better way. With the integration of databases and server side coding, it allowed websites to move on from the stateless nature of HTML that is when Tim Berners-Lee developed it.

As time has moved on the web has gone from strength to strength. The other huge leap forward was advent of Javascript, a programming language that allowed coders to manipulate the pages that users saw in their browsers. This allowed websites to start behaving more the more traditional applications that ran on PCs and other computers. Of course it was only matter of time when the two started to inter mingle to give us even better applications and lo and behold Ajax sprang up when Microsoft created the XMLHttpRequest Object which allowed developers to send asynchronous requests to servers without the page reloading, thus enhancing even further the web experience. Ajax was designed to work with both XHTML and XML so that information could be injected and updated quickly and using less resources. Why reload the whole page when you only need to change the information in a single element? XML and the many web services created to use it allowed people to integrate information from website to another in a standardised way and crossed the divides that sprung up from the use of different systems.

The web didn't stop there over time, newer ideas and innovations continued to spring up all over the shop and applications became more and more complex. Social Media started to come in to the main stream and integration between web sites and applications became more and more common. MySpace and Facebook started to come to fruition and the web continued to make new ground with many people that had considered the web to be a fad with those 'young people'.

With the advent of Ajax it allowed applications to be made and resemble desktop programs, but there was a problem that became apparent as time went on. As with most javaScript functionality it had its problems with the numerous browsers that were available in the market. It was also quite code intensive and lots of testing was usually needed to make sure code with all browsers. That is where my topic pops up and that topic is jQuery. jQuery is a javaScript framework and has ironed out many of the problems that made javaScript such a pain to work with in the first place. DOM traversal, Ajax calls and element selection was made easier and standardised, no more cross compatibility testing to make sure things worked in firefox and IE. Debugging and development time has become vastly decreased, something of which, if you are a business can be passed on when you quote your customers for work.

So what is the future for the web. Well in my opinion, the future is becoming smaller. Well it is terms of the web. Mobile technology is becoming more and more common and I think that is where a lot of the future innovations will lie. Apple and Google have both moved into the mobile phone market and making a lot of people think about using their mobile device as the primary device for accessing the Internet. I myself have bought a mac mini to develop applications for iPhone as I want to keep with up with how the market is changing. I haven't actually created an app yet as I have too many commitments in other areas but the area between desktop applications and web applications are coming together quicker than ever, something of which I think will change the web and the Internet forever.

Labels: , , , , , ,

Saturday, May 1, 2010

Becoming Mobile

It's been a while since I last added a post on to this blog, mainly because I have been very busy. I took on a full time PHP development role in September and left behind the world of search (for the time being) so that I can really push on with my career.

Anyway, down to business. I once thought that if I could master a web language then I could stick to that, work away day after day and life would be good. This was of course a feeling I had before I had actually learnt a language, before I had actually applied the skills in a real life situation. This is now such a silly notion to me now that I cannot believe that I actually thought that, but I guess that is the benefit of hindsight. This is even more astonishing when you consider what the Internet is and how the very nature of the beast requires you to be fluid, adaptive and progressive. This now brings on to my next point. Mobile Apps.

I really do not want to talk about what I am going to do with them (in this post) yet, but as I have actually bought a Mac Mini to develop iPhone Apps I am sure I am going to have some great fun in doing so (but more on this later). The main point of this post is to discuss why I made the decision to start building apps and continue on my learning spree that I have been on these last couple of years. The purchase of Mac while important, only served as a catalyst to get me thinking about this idea of linked learning (a phrase I have coined for this post) and what the effect of learning one skill helps/drives to you to learning another. If this makes no sense to you, then please let me explain:

Years ago I taught myself VBscript to run within the ASP environment. These scripts required the use of databases (new skill) which in turn required me to learn MS Access which in turn allowed me to create dynamic website. The need to learn how databases worked is the link I am referring to. The acquiring of knowledge for one subject turned into another. This is quite a short chain of events, mainly because I came to the whole ASP game quite late, .Net was coming in and I considered learning that for a while but ended up choosing PHP instead.

This is very much a stripped down version, but you will get the idea. The arrows are not literally a point from one skill to another, just merely a way of demonstrating movement. If this was to be made a graphical representation then it would be more like a flow chart and many of the skill sets would be interlinked.

PHP/MySQL Led to Programming Skills -> OOP Theory -> XML -> javaScript
MySQL -> Advanced Database SQL-> Stored Procedures
Apache (running on windows) -> Regular Expressions
javaScript -> DOM knowledge -> jQuery and other frameworks
Apache (Windows) -> Apache running on Linux
Apache (Linux) -> Linux web server setups -> Linux OS
Linux OS -> Application Languages (c++, python)

This is not an exhaustive list, I could be here forever doing that. I would also have to decide at which point does each skill set become its own subset. Also, just because one skill has fired another it doesn't mean that its parent subject has been exhausted. This is especially true with something like Linux, which is a huge topic and will take years to master. The problem with this linked learning is that fact you may spread yourself a little thin. While I can apply all the skills mentioned above I am always new things about each one. In addition, as the skills are inter-related, it generally (though not always) makes each new skill all that bit easier. For example, once I had learnt PHP, I found C++ much easier as many of the constructs are similar in nature.

Does this post apply to other areas, of course. You could apply it to just about anything, if you have a similar experience then please think back. It may help you to [re]discover skills and improve your career prospects or just help you find some direction.

So what's next on the learning radar? Well, like I mentioned at the beginning of the post it is now Apple Apps for iPod and iPhone, so please watch this space as I be reporting on this once my shiny new Mac mini arrives and I learn how to use OSX (oops another new skill), it's a good job I know how to use Linux as I hear they have many things in common ;-)

Labels: , , , , , ,