Let’s do some jQuery

I’ve been feeling a little silly in the past few weeks. Well.. over the last few years if I’m honest. In my never ending quest to hone my programming nous and skills I’ve never spent enough time throughout my coding and web design life to bother to look too much into jQuery. Sure I’ve played around with a few scripts whether it be for jQuery or for JavaScript and understood the scripts I’ve used but I haven’t really spent enough time to actually learn it.

Secondly I’ve spent time learning JavaScript (which is harder to learn) before learning jQuery which is more exciting and is a more predictable coding structure. This apparently was a bad move.

And finally, last night, late last night I sat there trying to apply some jQuery code that I’d learned on Codecademy, to a my own file on my own netbook and later onto my web server and found nothing worked. I painstakingly checked the HTML file that linked the jQuery code and the code itself, tried to link to the proper libraries but nothing worked. It was past midnight before I decided to let it go and try another day.

By hook or by crook (but probably by luck) I managed to make something happen in my Firefox browser that was jQuery powered. So, to clear up my confusion I thought I’d investigate and document the code in HTML and the .js file that is almost foolproof with regard to making jQuery tick.

These below are examples of the snippets we can use to link to the jQuery library.

<script src=”http://code.jquery.com/jquery-1.10.1.min.js”></script&gt;
<script src=”http://code.jquery.com/jquery-migrate-1.2.1.min.js”></script&gt;
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script&gt;

And this is the actual file that contains the jQuery goodness.

<script type = “text/javascript” src = “jquery.js”></script>

The file is correctly linked but there’s no effect because I haven’t included the piece of code that links to the jQuery library. So I’ll add that now by linking to Google as follows.

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script&gt;

<script type = “text/javascript” src = “jquery.js”></script>

And voila! We have some jQuery action. But there is one caveat. And this might actually be one of the things that got so stumped last night. When linking to a jQuery library, it is important to make sure it is the first script linked.

“The problem exists because browsers understand javascript and not stand alone jQuery snippets. jQuery turns our code into normal javascript code, so that the browsers can interpret what we are saying. Javascript libraries are shortcuts.” css-plus.com/2010/03/6-steps-to-take-if-your-jquery-is-not-working/ 

So that could be a huge answer to our problem.

Now, the version of jQuery we used via Google was 1.7.2. I also have a link to 1.2.1 and 1.10.1. Let me test those right now.

In place of the google jQuery library link.

<script src=”http://code.jquery.com/jquery-1.10.2.min.js”></script&gt; Worked

<script src=”http://code.jquery.com/jquery-1.10.1.min.js”></script&gt; Worked

<script src=”http://code.jquery.com/jquery-migrate-1.2.1.min.js”></script&gt; Migrate plugin and not a jQuery library file as such. Probsly another reason this was not going to work for me last night

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script&gt; Worked


The only logical conclusion is that I did not link jQuery correctly i.e. I did not make the linking script tag, the top most script tag my list of scripts in the HTML document head. Put simply, the link to jquery should be at the very top of any scripts you link in your web pages.

In Summary

So all of this is for one little fade effect using CSS, HTML and just a little jquery. Have a go and make this for yourself. You’ll find it on the jquery track of Codecademy where I got the code to work from.

CSS
div {
   height: 60px;
   width: 100px;
   border-radius: 5px;
   background-color: #69D2E7;
   text-align: center;
   color: #FFFFFF;
   font-family: Verdana, Arial, Sans-Serif;
   opacity: 0.5;
}

 

HTML

<!DOCTYPE html>
<html>
<head>
<title>Button Magic</title>
<link rel=’stylesheet’ type=’text/css’ href=button.css’/>

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script&gt;
<script type = “text/javascript” src = “jquery.js”></script>
</head>
<body>
<div><br/><strong>Click Me!</strong></div>
</body>
</html>

jQuery
$(document).ready(function() {
$(‘div’).mouseenter(function() {
$(‘div’).fadeTo(‘fast’, 1);
});
$(‘div’).mouseleave(function() {
$(‘div’).fadeTo(‘fast’, 0.5);
});
});

Mystery solved then I think.  Thanks for reading, please don’t forget to check out my website, and catch you later.   🙂

Advertisements

Making a basic Javascript For loop do more

CodeAcademy is the perfect way of learning to code for people like me. That’s what I think. I think I’ve mentioned in a past blog that I like it for its interactivity; its feedback;  its impressive console interface and its goal setting. I chose Javascript to begin with but I’m looking forward to gaining more points as I go through more exercises.

But the biggest thing is its explanations. Some of them are starting to stick in my mind and I love that certain points as revisited so you find yourself coming back and doing more practice in code topics you’ve done so it sticks a bit more in the brain. And it’s all available to come back to if you need a little helping hand or a refresher.

I’m part of the way there to locking all this Javascript stuff in the brain. Code Academy has taught me a lot but I’m not there yet. There is another little piece of code I went through that caught me out when I thought I’d got it The output I made just wasn’t right. Not that I don’t think Code Academy hasn’t been useful for me.

Last night I was tasked with the job of writing a loop that counts to 20. Yes simple enough, but for numbers that are divisible by 3 or 5, or both replace number values with strings. I tried, but generally I was stumped, and yes I resorted to Google for the answer.

So sometimes that learning just falls flat, and in the following blog I want to explain these thought processes into a solution for the below problem…

With due respects to @michaelnle for the providing the solution I found. It’s a solution that shows what else can be done with an otherwise bogstandard loop. It iterates 20 times but when it finds a number that is divisible by 3 or by 5 (or both) it prints something different rather than just the number.

So here I go,

var number = 20;

I started by declaring a variable and giving it the value of 20. This wasn’t required but I wanted to get into the habit of storing values in variables rather than just using the number direct in the for loop.

for(i=1;i<=number;i++){

This bit I got right. I needed at a basic level, a loop that printed 1 to 20 on the screen, for. See that I reference the value with the variable name which is equal to 20.

if(i%3===0){

Again, this was something that didn’t quite tick and this is the point where I was stuck. I tried basic condition statements rather than nesting them as the problem required and this was before I even found the right way to compare the values.

But I was on the wrong track from the start because I didn’t compare value properly. I tried all sorts of different ways to create the right comparison. === % 5 for example, but it gave me much the wrong output. I won’t go into specifics, it was just wrong.

This condition statement is the first condition, the parent one if that term is is applicable in JS.

if(i%5===0)

console.log(“FizzBuzz”);

inside the “parent” condition, is another condition test. We’re testing for a number in the same loop, that is divisible by 5. This is where we get our difference in string output “FizzBuzz”. Because we’re saying here that there are true tests for a number were divisible by both 3 and 5 we output Fizzbuzz rather than just outputting the iteration number. If one of these is false only one number counts…

else

console.log(“Fizz”);

 

}

… and that is “Fizz” because the numer is divisible by 3 but only by 3. So I simply print “fizz” to the console.

else if(i%5===0)

console.log(“Buzz”);

We’re now outside the first code bracket. “Else if” is the first alternative condition and it is now that I’m checking for other alternative output. This means if the number is not divisible by 3 but by 5 we print “Buzz” which denotes a number divisible by 5

else
console.log(i);
}

if not divisible by 3 nor 5 print the number.

The Whole Solution

The complete solution is this…

for(i=1;i<=number;i++){

if(i%3===0){
//if divisible by 3 and 5 print FizzBuzz
if(i%5===0)
console.log(“FizzBuzz”);

else
console.log(“Fizz”);
}

else if(i%5===0)

console.log(“Buzz”);
//if not divisible by 3 nor 5 print the number
else
console.log(i);
}

One other thing I noticed about this code block is this; there are no curly braces for if and else if. Putting them in is valid code and doesn’t affect the output in any way but it’s interesting to think that you don’t need then in certain statements. Even for loops. I’ve always been taught to use them as much as you use semi colons to separate statements.

So

for(i=1;i<=number;i++) 

if(i%3===0)
//if divisible by 3 and 5 print FizzBuzz
if(i%5===0)
console.log(“FizzBuzz”);

else
console.log(“Fizz”);

else if(i%5===0)
console.log(“Buzz”);

//if not divisible by 3 nor 5 print the number
else
console.log(i);

is as valid as

for(i=1;i<=number;i++){ 

if(i%3===0){
//if divisible by 3 and 5 print FizzBuzz
if(i%5===0)
console.log(“FizzBuzz”);

else
console.log(“Fizz”);
}

else if(i%5===0)
console.log(“Buzz”);
//if not divisible by 3 nor 5 print the number
else
console.log(i);
}

Have a go with the program yourself if you like, thanks for reading and don’t forget to check out my website. 🙂

Arrays and their index keys – Demystified

In my latest blog, I thought I’d tackle the subject of arrays and array index keys because they’re quite tricky when you delve into their full potential. And in my code academy exploits, I just don’t think I quite learned enough.

In code academy, they threw the terms rows and columns at me and while I had an inkling I was supposed to use my brain and work it out for myself, I was always a little miffed it wasn’t really explained in a bit more detail. So, I’ve done some more experimenting and tried to see just what these array keys can do and how they work.

First, a refresher. An array is an extension of the Javascript variable; but instead of storing one item.

var jgdm = “Jonnie Grieve Digital Media”

it stores lists

var jgdm = [“Jonnie”, “Grieve”, “Digital”, “Media”];

The above, is an array in it’s simplest form. Just as an example, I’ve split the text into 4 separate string indexes. To access the array you’d type:

document.write(jgdm[0]);

which would print “Jonnie” to the screen. That, again, is an array in its simplest form. There are various different types of array, including:

  • Singular arrays (My name for a standard array that we have just gone though)
  • Two Dimensional arrays
  • Jagged arrays

Two-Dimensional arrays

A 2 dimensional array is a nested array structure. It is an array that is inside another array. An example of which is this:

var jgdm2D = [[“Jonnie”, “Grieve”, “Digital”, “Media”], [“web”, “design”, “interface”, “design”]];

There’s one array here just like before, only this time, it contains 2 extra rows of arrays that have 4 values each. But how do we access these values? Remember that word? Rows? I’m thinking rows are the brackets that surround the values, and I can only think that columns is supposed to be the array value. Unless someone can put me right?

Anyway, consider the jgdm2D array above, and consider that to access the first key in the array you use the number 0. Zero always refers to the first key in an array. 

So for multidimensional arrays, you need to write something like

document.write(jgdm2D[0][0]); Outputs “Jonnie”
document.write(jgdm”D[1][0]); Outputs “web”
document.write(jgdm2D[1][1]); Outputs “design”

Again, this is simple enough. The red code block referenes items in the outermost “row” of the index key, and the blue on the inner. But what about a more complicated, layered array?

Multi-layered Arrays

var jgdmMulti = [“Multi”,[“Jonnie”, “Grieve”, “Digital”, “Media”], [“web”, “design”, “interface”, “design”], “Array”];

Now, I’m not sure if this kind of array is encouraged or practices in Javascript or if I’ve just made it up. It’s certainly workable code.
You can access multi and Array by using [0] and [3].

document.write(jgdm2D[1][1][0])

for accessing individual letters in an index key.

Jagged Arrays

var jagged = [[“Jonnie”, “Grieve”, “Digital”, “Media”], [“web”, “design”, “interface”, “design”], [“extroadinaire”]];

A jagged array is an array in which there are several rows and items but one row has more items in it than the other. In this example, There are 2 arrays with 4 items and one with only one.

As with all array values if you attempt to try an access a key that doesn’t exist, for example, [3][0]; the browser will return “undefined”.

Single Characters

If you include an extra layer of index keys when attempting to write the keys to the screen, you’ll return a single character in that index key.

So,

document.write(jgdm[0]); will return “Jonnie” but [0][1] will return “J” and so on.

To further ram home the point, let’s use one last example.

var jgdm2D = [[“Jonnie”, “Grieve”, “Digital”, “Media”], [“web”, “design”, “interface”, “design”]];

jgdm2D[0] outputs “Jonnie, Grieve, Digital, Media,” to the browser
jgdm2D[1] outputs “web,design,interface,design,”
jgdm2D[2] outputs “undefined,”
jgdm2D[0][0] outputs “Jonnie”
jgdm2D[1][0] outputs “web”
jgdm2D[2][0] outputs Nothing 
jgdm2D[0][1] outputs  “Grieve”
jgdm2D[0][2] outputs “Digital”
jgdm2D[0][2][1] outputs “i”
jgdm2D[1][2][1] outputs “n”
jgdm2D[2][2][2] outputs “Jonnie”

That’s array indexes for you.  I hope this was helpful to you check out my website and thanks for reading.   🙂

Understanding Loops

Loops. Loops. Loops. Loops.

For the last few days, well… actually throughout my programming lifetime, I’ve felt like I’m stuck in an infinite loop of my own. I said before in a previous blog that I’m familiar with programming concepts and for the most part I am. But loops can still tackle my brain and make it utterly melt.  It’s enough to make me go loopy! (Sorry about that!) :/

Sure, I’ve gone through the code academy course and passed it, advancing my way through the course, got the lovely little “way to go” graphic, but some of the things in there to do with loops have gone over my head

So, what I want to do is study them in detail so I can understand just what is going on with loops and how they are used in common situations.

Using Loops with Conditions and Arrays

Now, in programming, Loops and arrays go hand in hand and I’ll demonstrate this in an example, via code academy lesson code and go through it bit by bit so it locks in my brain and makes it clearer for my readers to.

The journey as in all programming languages, starts with variables.

Let’s think of them as boxes that store values, like a box can store a DVD. That’s all a variable is; a container with a name that holds contents such as a string or an integer.

e.g. var dvd = “Doctor who”

stores a string called Doctor Who.

And here it is again in our main example,

//FULL CODE – SEARCH TEXT FOR YOUR NAME – based on code academy program.

var text = “Blah blah blah blah blah blah Eric blah blah blah Eric blah blah Eric blah blah \ blah blah blah blah blah Eric”;

var myName = “Eric”;

var hits = [];

for(var i = 0; i < text.length; i++) {

if (text[i] == “E”) {

                                // If we find it, add characters up to

                                // the length of my name to the array

for(var j = i; j < (myName.length + i); j++) {

hits.push(text[j]);

                                }

                }

}

if (hits.length === 0) {

                console.log(“Your name wasn’t found!”);

} else {

                console.log(hits);

On a basic level, the code is declaring a long string in which is going to be searched using another string (i.e. the search parameter) and then appended (pushed) to another string.  Now, I’ve done a lot of research into how it all works and here is the code again in a bit more detail.

Fig1

var text = “Blah blah blah blah blah blah Eric blah blah blah Eric blah blah Eric blah blah \ blah blah blah blah blah Eric”;

var myName = “Eric”;

var hits = [];

Nice and simple to begin with. What we have here are 2 variables with values and an empty array.

  • var text is the string that will be searched.
  • myName is the string that will be searched for.
  • We then declare an empty array with the variable name of hits. This is the string we will eventually populate and put on the screen. 

Fig2

// Look for “E” in the text

for(var i = 0; i < text.length; i++) {

var i = 0 – So we start with the first for loop of the program. First expression in the loop is an iterator (i=0)  which is a separate variable to declare the beginning condition of our loop. This is the value which the loop begins with. It’s a counting variable so we can use numbers to count through the loop until we eventually reach the point where the condition is false and the loop ends.

i < text.length – The second condition in the for loop is the exit condition which searches the length of the text variable which is the entirety of the string contained in text. Put simply, it controls where the loop ends text.length is the programming talk for check the length of the string, or to put it another way number of characters.

i++ – In the last part of the loop, we increment the search one by one with i++.  Provide a way for the loop to end. If we didn’t do this, the loop would have no way of knowing when it should stop and go on continuously.  Infinite loops are not good and will crash the browser. Avoid them. 

Fig3

if (text[i] == “E“) {

Now this is trickier. It’s the first point in which I think, “hold on, what’s happening here?” or otherwise go completely blank. It looks like it’s searching for points in the string called text, that contain the capital letter E. 

But if so, what on earth is the relationship with [i]?  None initially, but we link I by using [i] it to reference the array. 

In the example above, text is the variable name and is the iterator for the for loop, so the computer knows which array we’re looping through. But all this happening inside a condition statement which then has its own code block. What we’re doing is telling the program to prepare to do something if a certain character is found.

Close out the code blocks by closing the curly braces.

Fig4

for(var j = i; j < (myName.length + i); j++) {

hits.push(text[j]);

We have another for loop to play with, within the if statement code block. This time we use the variable j as an iterator and assign it to i so they link together. Another variable, another count through as we’re looping through counting the number of characters in myName. it gives the value of the first iterator plus the length of the variable.

It also adds the characters of the name until the name length is met.  See how myName.length is used. In the expression “length” is the method, but “myName” is the variable name, which we’ve already set with a search parameter. The parameter is 4 characters long.

Then we push (or add) the number of characters equal to your name’s length to an array.

Fig 6 //

if (hits.length === 0) {

console.log(“Your name wasn’t found!”);

} else {

console.log(hits);

This is the final code block.  Hits.length counts up the characters if E and subsequent letters are found. If none are found “your name wasn’t found” is printed to the console. Otherwise, the result of the hit array and the loops and conditions are printed to the screen the hits array.

A final summary on the different types of loop;

For

Remember, for loops are run using counting variables. i.e. variables that have a numeric values that increment or decrement until such a time that a condition can no longer be met.  For loops have a starting point, an exit condition and an increment counter. e.g. (var i = 0; i < text.length; i++)

For loops can go hand in hand with arrays

//For loops with arrays

Q var cities = [“Newcastle”, “Liverpool”, “Manchester”, “Leeds”];

for (var i = 0; i < cities.length; i++) {

    console.log(“I would like to visit ” + cities[i]);

}

And again

var array = [3, 6, 2, 56, 32, 5, 89, 32];

var largest = 0;

// Write your code below!

for(i=0; i<=array.length; i++)

{

    if(array[i] > largest)  

    {

       largest = array[i];  //array referenced and assigned to array name

    }

}

console.log(largest);

while

If you have a need for a loop but don’t know how many times you’ll need to loop, you can use a while loop.

var score = 0;

while (score <1)

{

    console.log(“The score is 0”);

    score++;

}

start with a value in a variable

while (variable)  checks a condition directly.

But you can set an initial condition outside the while block of code, as long as you don’t put in the while brackets in between or you could cause the browser to loop infinitely. 

do-while

For loops you want to run at least one time no matter what. Loops that will definitely run at least once.

loopCondition = false;

 

do {

                console.log(“I’m gonna stop looping ’cause my condition is ” + String(loopCondition) + “!”);       

} while (loopCondition);

Learning to Code with Code Academy

Happy December everyone!

As a professional, I am devoted to learning to be better at what I do, and for me that means learning to keep up with web design trends, techniques and the biggest challenge of them al; learning to code. In my time I’ve come across various programming languages across different mediums.

I’ve attempted

  • MS Visual Basic – the building blocks of classic windows applications
  • C and C++
  • Actionscript 3.0 (and 2.0 a little bit)
  • Php
  • Perl & Cgi
  • and Javascript

When you look at all that, it sounds like a very impressive portfolio of programming languages.  Except, I’ve not really had a good track record at becoming fluent at them. I know and understand many programming concepts but I wouldn’t describe myself as what you would call a programming “whiz”.  That’s why I stick to the description of web designer for what I do, because while web designers should be prepped up for at least a basic understanding of programming languages of course, the distinction for me between designer and developer has always been clear.

So why can’t I join the big boys of the web development world then?  Well I’d love to!  I’m devoted to learning new things, new tricks and would love to find a way be able to take in the programming nous that comes in and retain in.  My problem is I have a brain that won’t allow me to do it.

  • I’ve gone to college  (C, C++, Javascript, Dynamic HTML)
  • I’ve gone to University and got my degree (Actionscript, php)
  • I follow web tutorials (take your pick)
  • I follow tips and advice and encouragement from others
  • I use web videos

But there is one thing I haven’t mentioned yet. During our last web outage (we overused our web bandwidth  – oops) I found out via my phone WiFi that there was a wonderful thing on the web called Code Academy.  Now I’d heard of Code Academy, but I’d not considered before that their courses were Free!.   (For a man of my budget, Free is a good thing right now, trust me) so I decided to check it out!  

Soon, I felt like I was coding like a pro.   Basic programs of course, but at a level good for my current nous of Javascript.  It is interactive, it guides you through every step, piping you with all the knowledge you need to write your code and to write good code.

There are other sites out there I feel I should try too.   

I’ve known about CodeLesson for some time,  TeamTreehouse promises much and Udemy is well respected too.  But I think Code academy is right on the money and just the sort of thing I need.  The best way to learn to code, is to code, and maybe this is the kind of tool I need to learn to write code and good code for projects to come in the future, because in this business you can never learn too much!