January 8, 2015 by Daniel P. Clark

JavaScript is easy with jQuery

If I had only known how easy it would be to pick up JavaScript with jQuery I would have learned it a long time ago.  But I had allowed a glimpse of obscure looking JavaScript to deter me in the same way Java kept me from learning programming for years.

When I first wanted to learn how to program Java was the big name, and the hype everyone was talking about.  It was cross-platform and it was going to be everywhere.  I was very excited at the idea of becoming a programmer and being able to write code that would work everywhere.  But the Java syntax discouraged me in such a way that I avoided programming because I felt it would be too difficult of a learning curve.  After a long period of time I discovered python.  It was easy to grasp.  And I started programming with it and had very rewarding results right off the bat.

JavaScript was something I avoided in the same way.  It’s not like I didn’t like the idea… I loved the idea.  But remembering all.of.the.words.with.dots.connecting.them and symbols that had no meaning to me at the time I didn’t want to even try it.  So I ended up learning JavaScript by necessity.  I didn’t sit down to learn it.  I didn’t take a course for it.  I only looked into it enough to get what I needed done.  And at some point, I became a fully capable JavaScript developer.

jQuery

Hearing a podcast with the maker of jQuery as a guest; it was nice hearing the back story of how it came into being.  jQuery was what I consider a necessary change for simplicity and beauty.  Up until I was developing in Rails where jQuery is included by default I was unaware of it and all that it’s capable of.  But as a Rails developer having a tool such as jQuery there to make the job easier to do, I picked it up as I went along the way.  And even though I have these old feelings of avoidance still lingering within me against JavaScript and Java; I’m quite glad I’ve learned JavaScript. (And as for Java, I’ve found Scala (which I love as a language).  Scala is Java reinvented the way it should have been.)

CSS Selectors

“CSS Selectors” sounds like strange foreign terminology.  If you don’t know what a CSS Selector is I’ll clue you in.  I believe it is the glue of all the wonderful things that happen in a web browser.  A CSS Selector is like a dog tag given to identify it’s owner.  With those ID’s you can then design and develop by referencing those IDs.  In CSS (Cascading Style Sheets) it is all for the design and look of the web page being defined in easy to re-use references.  For example; if I want to make many things in the web page have a background color of red I would create a CSS style such as this:

.red {
  background-color: red;
}

Then in the web page for anything I wanted to inherit this quality I would give it red as a class attribute.

<div class="red">This background is red.</div>

Don’t be fooled by the name.  I could have called it oompa-loompa and still had it set the background as red.  But remember when naming you want the intent of the code to be clear in what is being done.  So I would name your CSS styles and CSS selectors either by the content, or by the purpose/effect.

CSS styles are referred to with the pound symbol for the ID, dot for the class, or just the word for the tag.

tag {}
.class {}
#id {}

In html all of these would refer to:

<tag class="class" id="id"></tag>

With jQuery you can use the same CSS style references to select an Object block from the web page.  In these cases they are referred to as CSS Selectors.  In jQuery you can identify it with jQuery(‘.css-selector’) or sometimes you can use a dollar sign instead of the word jQuery $(‘.css-selector’).  With this CSS selector jQuery will return a result of all items that have the class css-selector.

<div class="select-this">Number 1</div>
<div class="select-this">Number 2</div>
<span class="select-this">Number 3</span>
<script>
  jQuery('.select-this');
</script>

In the example above the jQuery(‘.select-this’) will return an Array result with three Objects.  The first two will be Objects of the div tags, and the third is the span tag.  If I wanted to make them all disappear I could use the jQuery .hide() method.

jQuery('.select-this').hide();

And anything in the web page that has a class of select-this will disappear.

Learning

To master jQuery you pretty much just need to familiarize yourself with CSS Selectors and know how to lookup jQuery methods from api.jquery.comWith JavaScript it is a lot more difficult to figure out what went wrong when things don’t go as planned.  So it’s best to learn how to interact with console.log(“This show in the console log”) and alert(“This show in a popup window”).  But even that will leave you scratching your head.

My favorite tool to work with is the FireBug Firefox plugin by pressing CTRL-SHIFT-C, then clicking Console, then the small arrow button all the way on the right opens a JavaScript editor environment.  You may also use the Firefox console via CTRL-SHIFT-K.  But that is executed line by line, and the input is barely noticeable at the bottom of the screen.  I think that the best Firefox JavaScript tool is available via SHIFT-F4.  It’s the JavaScipt Scratchpad and it has lots of features built in.  Lastly the most used tool I’ve found for testing and sharing is jsfiddle.net.

In order to not be overwhelmed by JavaScript when you’re learning and looking at code examples it’s best to examine it in small pieces.  Simplify it.  That seems to be true in any programming language.  Understanding comes with simplifying what is before you.

Real World Application

Once you get a hang of JavaScript it really feels like you can do anything in a web browser.  I’ve written a Rails gem called Dynaspan which takes text on a page and allows you to update it by clicking on it. Check out my demo of Dynaspan on JSFiddle.  I’m very proud of this tool.  It takes something that should be easy to use anywhere, and it does just that.  It does a lot of stuff for you without you having to do any of the heavy lifting.  That is what makes an excellent tool.

JavaScript can help you solve a lot of real problems.  For example hitting the enter key on a text input field is known to submit the form.  Well if the form isn’t done being filled out then you could lose the work you’ve done this far.  So I’ve answered a StackOverflow question on changing the enter key to work like a tab key.

One shortcoming of working with forms on web pages is you can’t have forms within forms.  Why is that a problem you might ask?  Think of a web page with a contact list.  You have a bunch of rows of contacts and in each of those you can update the contact via AJAX.  What that means is you can change things without the page reloading.  Well each of those contacts have a check-box next to it so you can Select-All and then delete, move, or do something else with it.  But if you can’t have forms within forms, then you can’t use a form on the whole page for check-boxes and still have the AJAX forms within it.  To get around this you have to write client side code for that.  jQuery to the rescue!  Here’s my S.O. question and answer on this one: JavaScript generate Rails collection form from check-boxes and Submit (non-AJAX)

Just today I wrote a filter function.  The way it works is by getting an Array of all Objects marked with the CSS Selector for the class filterable.  I’ve put that class on all table rows of the page results.  Then as text is being entered into a search field it will match the text to the search field with the entire table row of text and make all non-matching table rows disappear.  It’s rather a simple way of doing it.  Here’s the code:

function filterBlocks() {
  var filterText = $('#filter').val();
  var filterable = $('.filterable');
  if (!filterText){
    filterable.show();
  } else {
    filterable.each(function(){
      var x = $(this).clone();
      x.find('select,input').remove();
      if (x.text().match(filterText)){
        $(this).show();
      } else {
        $(this).hide();
}})}}

And the input in the view is like this:

<input type="text" id="filter" placeholder="Filter" onkeyup='filterBlocks();'>

$() is the same jQuery() in most cases.  If you want to understand the parts of this look over each piece and find it on api.jquery.com.  Keep studying and experimenting and understanding will grow with experience.

Back to CSS Selectors

CSS Selectors are used in more places than just these.  Web scraping tools are loaded with them.  Mechanize and Nokogiri use them splendidly.  Just as in CSS styles you can combine the labels with selectors.

div > span > a {
  // Styles here...
}

This CSS style will affect all hyperlinks under a span which is also under a div HTML tag.  You can select the same objects in jQuery with:

$('div > span > a');
// or
jQuery('div > span > a');

There are many more ways to specifically select things.  I’ll leave discussing those for another time perhaps.  I’ll give on last code example to illustrate.  This is code that I’ve written for my site that will find all links to external sites and make sure they open a new window:

jQuery(function(){
  jQuery("a[href^='http']").not("a[href*='6ftdan.com']").each(
    function(){ jQuery(this).attr('target','_blank') });
})

In Closing…

I’d like to personally recommend a book.  I’ve only just received it as a gift a couple of weeks ago.  But glimpsing through it I’ve found it super easy to follow and understand:  JavaScript & jQuery: The Missing Manual by David Sawyer McFarland

As always!  I hope what I’ve written has been both helpful to you, and enjoyable to read!  Please comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

#article#blog#css#demo#easy#examples#html#javascript#jquery#js#learning#post#selector#selectors#style#styles

Leave a Reply

Your email address will not be published / Required fields are marked *