#100DaysOfCode Days 34-37: Making Your Ionic App Work with Controllers and Services

The introduction is usually the part where I apologize for not updating you all daily on my progress. Sticking to a no excuses response, I’ll leave a link to my GitHub repo here for you all to follow the #100DaysOfCode challenge in real-time.  The best way for me to remedy being behind on my writing is not be. Therefore, let’s continue and talk about controllers and services.

If you use AngularJS, you are at an advantage.  Being based on AngularJS, Ionic makes the conversion from web app to mobile hybrid pretty seamless with a few tweaks.  Those unfamiliar with AngularJS can get familiar with it going through the documentation, but you also should be proficient in JavaScript when writing the functionality of an Ionic app.   JavaScript concepts, such as the use of objects, lists, closures, DOM manipulation, and templating are used heavily in Angular.  For this reason, I provided some resources below to better understand how to write better AngularJS controllers.

Also, please note that this post is a continuation of my series on building hybrid mobile apps with Ionic specifically. I’ve been walking through an app that I built for a course as part of a full stack web development certificate I’m earning this Spring through Hong Kong University via Coursera.  To get a series overview, you can go to the #100DaysOfCode page of the blog and read Days 26-33.

Linking JS Files in Your Ionic App

The index.html file of my app is already populated because I ran the ionic start appname sidemenu command upon installation of Ionic, thus also installing the sidemenu template and the views that come with it.  Using a template will save you trouble of having to write up the index.html file yourself and making sure on Ionic dependencies are linked beforehand.  Here’s a snapshot of my index.html file:

my index.html file

my index.html file

As you can see, it’s within the index.html file where the libraries and scripts are linked.  Pay attention to the bottom.  I linked three JS files, one for my app configuration, one for the controllers of the app, and one for the services.  I also use a ngDirective to name the app in the <body> tag and <ion-nav-view> to make sure the views are being fed from the www/templates subfolder of the app.

Initializing Your App

In my app.js file, I create a global variable with the Angular module. The parameters of the module argument is my app (the app name) and an empty array, which will take all the app dependencies. Under the module you have the .run() function that is included with the template used, and app states used for routing.  I discussed the app.js file more in detail in the previous post on app states you may review here so there’s no need to repeat myself today, it’s just important to note how a module is declared.  The following line of code is what my Angular module looks like now for the completed app:

angular.module('conFusion', ['ionic', 'ngCordova', 'conFusion.controllers', 'conFusion.services'])

The controllers.js file is where all the code functionality for the app is located.  I initialized the module for controllers with this line of code:

angular.module('conFusion.controllers', [])

Underneath the module includes each controller used in the app and the code functionality.

Setting Up Controllers and Services

Because I’m technically not allowed to share the complete project code for the course, I will share only a snippet as an example of controller setup.  Will look at the IndexController which is connected to the index.html view. My controller for the index.html does a couple of things:

  1. Defines the service $scope as the core dependency. Remember, a dependency is when an object is passed to a function instead of creating that object outside the function. For my IndexController, dependencies injected included both objects as well as services and factories I defined in the services.js file.
  2. Takes other dependencies within it’s array that are data from my db.json file, such as the dish, leader, and promotion objects.
  3. Takes the menuFactory, promotionFactory, and corporateFactory as dependencies as well. Factories are not to be confused with services, which I will go into later. For now, just know that a factory is a function in the services.js file that returns a value needed in the controller.
  4. Takes baseURL as  a dependency. baseURL is a parameter in the .constant() function defined in the services.js file which directs the user to the local url address to be used to view.  This may be the local host server address in the beginning, and later changed to your IP.
  5. Defines the function to be used with all of the above as dependencies as well.  Yes, you have to include all dependencies for the controller array within your function. It may seem recursive, but without doing so, you will get reference errors.
  6. Within the function, objects are assigned as properties of the $scope to initiate two-way binding with the view.

Here’s what my IndexController is written as:

.controller('IndexController', ['$scope', 'dish', 'leader', 'promotion', 'menuFactory', 'promotionFactory', 'corporateFactory', 'baseURL', function($scope, dish, leader, promotion, menuFactory, promotionFactory, corporateFactory, baseURL) { 
    $scope.baseURL = baseURL;
    $scope.message="Loading...";
    $scope.dish = dish;
    $scope.leader = leader;
    $scope.promotion = promotion;
}])

Let me break down each property and why is set to $scope.  As I said earlier, dish, leader, and promotion is data from the db.json file I created.  Without sharing the data from that file, know that each property stands for an individual id within the database for the dishes, leadership, and promotions objects.  The controllers get the id for each dish, leader, and promotion using factories that are functions that return those values.

Using Factories and Services to Return Values

Switching to my services.js file, the module for services is initialized, only unlike the controllers module, the services module takes ngResource within the array. Angular’s ngResource is a service that creates a resource object for interacting with data sources (like my db.json file). The module is set with one line of code as the global variable:

angular.module('conFusion.services', ['ngResource'])

Underneath, are the factories and services used for the act.  Here are the code snippets of the menuFactory, promotionsFactory, and corporateFactory from my services.js file that were injected as dependencies in the IndexController. Each factory takes the $resource  and baseURL services from the app.js file as a dependencies, and defines a function that returns the id from objects in the db.json file that is to be used in the controller as well as displayed with expressions in the template view using the PUT method:

resourcefactory

factories within the service.js file

By assigning the properties of the scope in IndexController, I set up two-way binding with the view expressions for index.html file, which my app state routes to the home.html template within the www/templates project subfolder. For example, take the following code from home.html which displays the leader data using expressions:

Ionic cards from the home.html template

Ionic cards from the home.html template

Now let’s review what was discussed in short summary:

  1. Controllers control the code seen in the template view (any html client-side file) via two-way binding. For each controller, dependencies are injected.
  2. Dependencies are any objects, services, or factories that the controller depends on for the function. They are injected in the controller and as parameters for the function argument. The example of the IndexController used all three as dependencies.
  3. In the controller function, dependencies can be assigned to the $scope as properties. The dish, leader, and promotion objects were assigned as properties to $scope in the example.
  4. The controller was able to use these objects by injecting the menuFactory, promotionFactory, and corporateFactory from the services.js file.
  5. Factories are functions that return a value.  All three factories returned data from an individual id within the db.json file.
  6. Factories are able to retrieve data from the db.json file using the ngResource (or $resource) service as a dependency injected in the services module for the app.
  7. The template view displays values from the controllers using Angular expressions. They are defined within Ionic templates using curly brackets.

All together, app controllers, services, factories, templates, and database objects work together to provide a fully functioning app powered using JavaScript.

In the next and last post of this series, I will go over deploying an Ionic app for Android and iOS.

*** Resources for Further Learning ***

  1. Go through Thinkster’s guide, A Better Way to Learn AngularJS here. It discusses controllers in detail and provides a curated list of learning modules to start with.
  2. Tony Alicea is a great web developer and even more awesome course instructor. If you ever taken his course, JavaScript: The Weird Parts, you know how well he can explain even the most complex JavaScript concepts. Thankfully for us, he has released his new series on AngularJS. You can take the first hour of his AngularJS course on YouTube here.

*** Days 34-37 Recap ***

  1. Finished week 4 lectures of the Web Design course, started on final assignment
  2. Worked on photo_gallery project, finished it
  3. Finished week 2 of the Mobile App Dev course lectures, submitted assignment. Passed at 100%.
  4. Finished week 3 of the Mobile App Dev course lectures

#100DaysOfCode Days 32 & 33 Ionic App Routing and State Configuration

So far, we discussed how to install Ionic and start an app, how to use templates for the app’s UI, and how to design the structure of the app using Ionic directives.  Now, let’s dive more into JavaScript and focus on the inner workings of our app, starting with app configuration.

Please note, that I used the sidemenu template in my app for the course, which comes equipped with a set of HTML views in the “www” folder.  I may reference particular views and code that you may not include in your Ionic app project.  Therefore, today’s post shouldn’t be considered as a how-to guide like the previous ones. It’s more like a show-and-tell walk through of my app structure and code.  As always, if you want a complete description of how Ionic works, seek the source code or the docs.

Initializing the App

Opening the index.html file within www subfolder of the Ionic app, you’ll want to modify the body tag by naming your app. Keep in mind that if the name of your app is case-sensitive, you’ll want to make sure it’s spelled correctly in all dependencies.

<body ng-app="appName">

After naming the app, it must be initialized in the controllers code. Within www, you’ll find a js subfolder, and within that, you’ll find two separate files: app.js and controllers.js.  Open the app.js file and modify the angular module code by inserting the name of your app.

angular.module('appName', ['ionic', 'appName.controllers')]

You’ll want to do a similar task within the controllers.js file code. Find the angular module code and insert the name of your app.

angular.module('appName.controllers', [])

If you’re using a template, there will be code in the controllers.js file that you don’t need (it comes with the starter app). Delete all or what doesn’t pertain to the functionality of your app.  For me, this meant all the controller code since we were converting our web app to mobile in the course.  Because Ionic was built with AngularJS, we were able to use the controllers we created in the AngularJS web app course previously, modified them for Ionic and Cordova, and add them in our controllers.js file, saving a lot of time.

Configuring UI-Router App States

In the sidemenu.html file, there are several list items href links that help the user navigate the app.  Prof. Muppala said we weren’t allowed to share the full app code, so I created a similar code snippet of a navigation list in the sidemenu for explanation purposes:

example of a list within an Ionic app with navigation options

example of a list within an Ionic app with navigation options

Ionic uses Angular UI-router to handle the routing where $stateProvider is injected. In order for the navigation links to work, we have to configure the app states. Each state is configured as an object with key:value paired properties. Properties include the app url, the template view in use, the template url (as a property of view), and the controller used for that template.  This is all done within the app.js file. I created the code snippet below of how the app states are configured as objects:

UI-router states within app.js file

UI-router states within app.js file

There are different UI-router events that you can use for loading, success, and error messages, but I won’t go into that now in order to keep today’s post short and sweet.  If you would like more info on accessing the full capabilities of Angular UI-router in an Ionic app, I listed a few resources at the end of the post for further learning.

Configuring Resolve Objects

Within app state you can include a resolve object. Resolve objects help map the dependencies that should be injected in a controller, such as Angular factories and services.  For those of you who are unfamiliar with Angular, I find that Tyler McGinnis offers one of the best explanations of factories and services.  To save me the time, I suggest you read his definitions of both here if you would like further information on why factories and services are injected as dependencies.

Resolve objects are done before the controller is called for faster UI response. They are listed as key:value pairs within app state as a property of views. The key is the name of the dependency, the value is a function of it. The keys defined within the resolve object are later injected as dependencies in the controller in use.

In our app, we have a template view favorites.html that shows a collection of dishes a user adds as a favorite.  To configure functionality in the app state, I will need a key for dishes queried from the menuFactory using a .query( ) function, and a key for favorites queried from the favoriteFactory using a .getFavorites( ) function.  Therefore, this is what my resolve object within the favorites app state looked like:

the resolve objects define two keys: dishes and favorites

the resolve object define two keys: dishes and favorites

In the FavoritesController, I then inject the dishes and favorites key and define the $scope variable for each one. In adhering to Professor Muppala’s rules, I’m only showing you the code snippet relevant to the example:

FavoritesController code snippet

FavoritesController code snippet

Data related to dishes and favorites are fetched from the json database (db.json) and returned using the functions.

I’m almost done wrapping up the Ionic series for #100DaysOfCode.  I will include a guide on controllers within an Ionic app specifically, and one that discusses Cordova deployment as the last two posts within the series.   Also, please checkout the #100DaysOfCode GitHub repo, especially for days 27-35.  Because I’m not allowed to share all of my Ionic app code, I worked on additional projects that you can check out there.

*** Resources for Further Learning ***

  1. Take the same course, Multiplatform Mobile App Development with Web Technologies, that I did on Coursera for free* here.
  2. Read software engineer Rob Ferguson’s post on using UI-router and defining states here.
  3. Build an App with Navigation and Routing via LearnIonic here.
  4. Read app developer Andrew McGivery’s post on building controllers within an Ionic app here.

*** Days 31 & 32 Recap ***

  1. Submitted week 1 assignment for the Mobile App Dev course, started week 2 lectures
  2. Started week 4 lectures in the Web Design course on handlebars.js
  3. Created photo_gallery project for the course to practice.
  4. Added free-use images to subfolder to use within the template data
  5. Added custom Bootstrap themes to CSS subfolder as options
  6. Created albums.js file within js subfolder to store data objects, added object data
  7. Created gallery.js file within js subfolder for handlebars.js source compilation and template configuration
  8. Added four templates within index.html for showcasing data.
*Note: The course is free for those who don’t want certification. If you want a certificate of completion signed by Hong Kong University, you must enroll and pay for the course. Applying for a scholarship is an option as well.

#100DaysOfCode Day 31: Using Ionic Directives to Structure Your Templates

Inside the HTML template, content is placed in between view module directives <ion-view>…</ion-view>.  While the views work with Angular directives (prefixed with ng-), Ionic also have also has its own directives to use within the views. There are directives for navigation, content, tabs, lists, and buttons. To help you, I created a table to describe each directive and how it works below:

list of Ionic directives

list of Ionic directives

Now lets revisit the example form that I posted in the intro to this series to break down all the directives used. The form below is a modal for logging in users:

sample form using Ionic directives, classes, and Angular ngModels

sample form using Ionic directives, classes, and Angular ngModels

In the form, I use <ion-modal-view> to create a container for the form, specifying that this view will be a modal. All content will go within this container. In the header, <ion-header-bar> I created a title heading and set a close button that will trigger the closeLogin( ) click event that I will define in the controller code. After closing the header, I use <ion-content> as a container the actual login form content. Because I’m defining a form inside a modal, instead of using <ion-list>, I used a <div> and gave it the “list” Ionic class.  Doing this still allows me to use the “item” Ionic class to do the form inputs. Both inputs use Angular ngModals to attach data to controller code.

Now that I spent some time discussing the HTML structure of an app, my next post will focus on configuration and coding the controllers in JavaScript. Stay tuned.

*** Day 31 Recap ***

  1. Debugged CSS code in the Bootstrappin’ Portfolio project. This project is now finished and available for cloning and download here.
  2. Worked on assignment for week 1 of the Mobile App Dev course.
  3. Created searchbox.html template using handlebars.js as an example for the Web Design course. It uses jQuery to filter through a data array to match text entered in a search box. Code is available here.

 

#100DaysOfCode Days 28 – 30: Ionic Templates, Views, and the Grid Structure

After finishing the mobile app development course this past Sunday, I’m excited about sharing what I learned.  For today’s post, I’m making a few assumptions that you all (1) read my post on how to install Ionic and start an initial app available here, and (2) you all know by now that Ionic is based on AngularJS, which I will reference every now and then.  Other than that, I won’t be providing much of an intro on terms. Let’s just dive in!

Using Ionic Templates and Views

Ionic comes equipped with a blank app template, but you can also use starter templates to provide a basic UI to customize.  For my app, I ran the terminal command ionic start conFusion sidemenu to start an app named “conFusion” with ready-to-go templates that included side-menu navigation. With this command, views such as browse.html, login.html, playlists.html, playlist.html, search.html, and a few others were installed in the “www” subfolder within my conFusion project file. I was able to use these views, customize the starter code to fit the content, and add in my own code to provide the functionality I needed for my app.

Ionic has three named templates sidemenu, tabs, and  blank.  When you run the ionic start [appname] [template] command from your terminal, Git is used to fetch the template from the GitHub source code and download it into your project folder.  In addition, starter templates can come from Codepen, a GitHub repo, or a local directory.  For GitHub repos and Codepens, use the full url of the source code to fetch the template.

Which views installed in the “www” subfolder will depend on which template you use in your starter app.  If you want to create your own views, I recommend that you use the blank template.

In our course, we built an app for the fictitious restaurant, conFusion.  While we kept the login.html view as is, we did add a modal, notifications, and buttons for more interactivity.  We also changed the playlists.html view to menu.html where we listed the available dishes at the restaurant by categories (appetizers, entrees, and desserts) users can choose from and select individual dishes.  Likewise, we changed playlist.html to dishdetail.html for showing a description of each dish with a form where users can enter comments, rate a dish, and submit their input which would be added and live instantly. Finally, we changed search.html to the mobile home page to showcase promotions, and browse.html to an about us page for chef information.

Ionic Grid Structuring

As part of the templates available in the “www” project subfolder, code is already provided for you to customize.  If you’re familiar with Bootstrap, Foundation, or Pure, the set up is pretty similar.  Sections are defined as <divs> in which are classes can be applied for additional styling or JS interactivity.  The hierarchy goes as follows: row –> column(s) –> content.

Unlike Bootstrap, Ionic does not follow a 12-column grid structure.  Ionic cols represent the percentage of the device screen the content will occupy. Offsets are also used to position content on the screen.  I created a table to break it down by example.

table

The following example below is a code sample in which I use Angular’s ngRepeat directive to loop through an array of images.  I define the columns at 25%, meaning that each image in the array will take up 25% of the screen pane, for a total of 4 images per row:

demo_one

mobile-col

You do not always have to set a percentage with the columns.  Simply nesting the columns within a row will give them equal spacing. In this example, both buttons will take up 50% or half of the row.

demo_two
The content within a grid structure can also be positioned and aligned vertically by applying certain classes to the <div> that defines the row, such as row-center and row-bottom.
 demo_three

Applying the classes –top, -center, -bottom works on columns too for structuring content vertically, but I prefer using the responsive grid classes within Ionic in order to structure columns for both mobile and tablet screens. The responsive-sm class collapses columns into single row when the viewport is mobile, but smaller than the typical landscape phone (such as iPhones 5 <).  The responsive-md class can be applied when the viewport is smaller than portrait tablet (think Kindle or Nook size) but bigger than the landscape phone, and responsive-lg class will be applied when the viewport is smaller than landscape tablet.

demo_four

 

mobile-col2
I kept it simple in this summary, but Ionic can handle more complex grid structures if you want to provide the best user experience for your app.  Therefore, I put together a list of articles you can bookmark and use as resources to help.
Because I’m not allowed to share the complete project app for this course, the code on the #100DaysOfCode GitHub repo will not always reflect what I cover on the blog.  To follow my Ionic development process, check in on the blog as I upload posts when I can.  To follow other projects I’ve been working on when not developing for the course, check the repo.
*** Days 28-30 Recap ***
1. Completed modules 5 & 6 for Mobile App Dev course on Ionic components
2. Finished week 3 quiz for LondonU’s course on Web Design.
3. Created Photo Album (photo_album) project to practice handlebars.js, code available here
4. Added first 3 templates to index.html in photo_album
5. Added initial data object code to “js” subfolder in photo_album (I’m using the solar system NASA data and images) to albums.js
6. Added free-use images to subfolder to populate templates
7. Added nav-tabs and album_template to index.html
8. Compiled template to handlebars.js in gallery.js file
 *All images and photos created by me for the post. They are free to use.

#100DaysOfCode Day 26: The Hybrid Mobile App Development Approach and Ionic

In the last post, we discussed 3 common approaches for developing mobile apps.  This included developing with native code, developing a web app for mobile, and the hybrid approach using a framework.  Today, I’ll highlight the hybrid approach and discuss the mobile framework I’m currently using for a course project: Ionic.

The Hybrid Mobile App Development Approach

Before Ionic, Cordova, and similar tools (Titanium, Unity, Kivy, Xamarin, etc) became popular, front-end developers could produce HTML5 and JavaScript-based apps using tools like jQuery mobile, or focus on making sure web apps were responsive to mobile.  However, there are problems that developers had to work around when it came to using webview (browser) for mobile.  Most importantly, lags in performance, UX considerations not being met, and speed became ongoing issues.  What makes the hybrid approach unique is that apps can be written in any language.  They are embedded or “wrapped” in a native container that provides them native code functionality.

This doesn’t mean they adopt all native capabilities, but more native features are accessible using the hybrid app approach than they would if you build an HTML5 app.   Features such as device access to the camera, calendar, notifications, contacts, and geolocation can be available in hybrid apps.   A SQL file system providing secure offline storage, and gestures such as pinch, spread, and swipe are also supported.  JavaScript developers should also note that using framework tools like Ionic and Cordova makes distribution through app stores possible (1).

Enter Ionic

I compare what Ionic is for mobile to what Bootstrap is for UI development. As a front-end tool, Ionic is based on Cordova and built with Sass, allowing developers to write apps in HTML, CSS, and JavaScript.  Bootstrap users will like that the Ionic CSS component syntax is similar in that it uses classes to drive both CSS styling and JS functionality.  Below is sample code I took from my project for the course to create a login form in a popup modal. You’ll notice Ionic’s own CSS component classes (.list, .item-input, .input-label) and directives (<ion-modal-view>, <ion-content>, <ion-list>) intermixed with Angular directives while applied to inputs:

sample form using Ionic directives, classes, and Angular ngModels

sample form using Ionic directives, classes, and Angular ngModels

Because Ionic works with Angular, I can program the modal and the JS function doLogin() in a separate controller. Likewise, I can add any Angular services or factories as a dependency injection in the controller if I need them to power the app.  I will share more code from my project’s controllers in a post on that subject later.

What’s also useful about Ionic is that it comes pre-packaged with templates to use when you install it and start an app. In Day 27, I’ll walk you through installation, starting an app, and more about templates and Ionic directives.

*** Day 27 Recap ***

  1. Finished module 2 and 3 of Multiplatform Mobile App Development with Web Technologies course.
  2. Finished week 1 of London U’s MOOC on web design, see code in the assignment I submitted on #100DaysOfCode GitHub repo.
(1) Source: Native, HTML5, or Hybrid: Understanding Your Mobile App Development Options

#100DaysOfCode Weekend Update: The Hardest Part About This Challenge

Almost forgot to post an update of what I did over the weekend. Sorry. I have no excuse other than the fact that I was busy with other things besides coding and writing.  Sneaking in my own coding sessions during my breaks at work has become difficult. I’m now working through them and have been for the last week.  Just to give you guys a glimpse into my personal life: I was recently promoted at work.  With the promotion, I’ll be responsible for leading the team in charge of building our district’s new website and app that is to be launched this Spring.  Though I’m grateful and excited about the opportunity, much work lies ahead for me, and staying organized is my priority.  I’ve set goals for myself outside of work that I don’t intend to give up on.  Even as I write this as my eyes are bleed with exhaustion, just know that #100DaysOfCode will continue.  As I said in earlier posts, the hardest thing about this challenge is not coding, but writing about it.  I hope you all forgive me if the posts become more sporadic.

Besides studying jQuery this past week, I also worked on the Bootstrappin’ Portfolio site.  I say I spent probably a total of 6 hours of the challenge on it so far, and it’s turning out well.  Over the weekend, I worked on the index and services.html pages.  I imported web fonts, fixed the hover animations on the navigation bar, worked on alignment of the column grid, changed the button structure, and incorporated some icons.  Here’s what the two pages now look like:

new home (index.html) page

new home (index.html) page

 

port_three

new services page with icons and center-aligned content

A cool thing I learned to do that I always wanted to incorporate on a site is a blinking cursor effect that you can see above in the first pic. I just like the way it looks and it reminds me of writing (my first creative passion).   I shared the sample code below:

/* BLINKING CURSOR */
.blinking-cursor {
   font-weight:100; 
   color:#fff; 
   -webkit-animation:1s blink step-end infinite; 
   -moz-animation:1s blink step-end infinite; 
   -ms-animation:1s blink step-end infinite; 
   -o-animation:1s blink step-end infinite; 
   animation:1s blink step-end infinite;
}
@keyframes "blink" {
   from, to {color:transparent;}
   50%{color:#fff;}
}
@-moz-keyframes blink {
   from, to {color:transparent;}
   50%{color:#fff;}
}
@-webkit-keyframes "blink" {
   from, to {color:transparent;}
   50%{color:#fff;}
}
@-ms-keyframes "blink" {
   from, to {color:transparent;}
   50%{color:#fff;}
}

I’m using the CSS class blinking-cursor, so place the following code <span class=”blinking-cursor”> | </span> where you want the cursor to be in your HTML file, and walla!

To finish the project off, I plan on adding a section for a developer’s bio to the services page, and including some additional page options for the portfolio section of the site.  Even though the Bootstrap grid is responsive, I haven’t tested what my latest additions look like in mobile view, so I’ll probably spend a day of the challenge on that.  I also want to refactor the code as a single page site, maybe with AngularJS since I’m more comfortable with routing views. That’s the future though, and I’ll just be thankful to get through this week.  Course 4 of the full stack web development specialization I’m in just started, so lookout for more and frequent posts on using Cordova and Ionic framework capabilities for building hybrid mobile apps.

You can check out the code I did over the weekend at the #100DaysOfCode Github repo.

*** Day 18 & 19 Recap ***

  1. Added font awesome icons to services.html page
  2. Changed font options for the entire site
  3. Fixed the alignment issues on the services.html and index.html pages
  4. Added code to create a blinking cursor effect

#100DaysOfCode: Day 16 & 17: jQuery CSS Selectors + Sample Code

Continuing with Day 15, I want to add more details about what I’ve learned and worked on in Module 1 of Microsoft’s jQuery course.  After instruction on initial project setup like where to download jQuery and options for a CDN (which I recommend), Chris the instructor went over how to use CSS selectors with jQuery.  Today’s post will be quick guide on this subject.

jQuery and JavaScript are often used interchangeably because jQuery is one of the most widely used libraries in JS.  Some would even say it’s easier to learn than JavaScript because it takes less code to do the same functions. I first heard about jQuery as it was described as an alternative to Flash for animation, interactivity, and easy manipulation of the DOM.  As someone who wants to focus on web design and front-end development, I’m getting accustomed to using it more often.

Adding jQuery to a Page

jQuery can be added to a project as a separate .js file or within the HTML doc using tags.  If you want to download it, the minified, lightweight 1.12 and 2.2 versions are available here at the official site. An alternative is to run npm or bower install commands if using one of these package managers to setup your project. The beta version 3.0 has also available been made available this week, but if keeping your load as lean as possible is important to you, you may want to stick to 1.12 or 2.2. I prefer using the CDN available for it, which I listed below:

https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js

Cloudfare has also posted a CDN for the version 3:

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js

Ready Your Doc

First, jQuery code is prefaced with $ to define it. To “ready” your document, you will need to use one of the two options for executing code on the DOM.

$(document).ready(function() {
   ...code...
});

 

or

$(function(){
   ...code...
});

Using CSS Selectors

The basic syntax for using CSS selectors is $(selector).event( ).  Selectors can be HTML elements, classes, ids, or utilize the keyword this.  There are multiple event handlers and methods that can be called on selectors. The w3 Consortium has a list of the most common ones available here, but for this guide, I’ll be using .text( ) and .click( ) as examples.

With the .text( ) event handler, it sets or returns content to the matching selector it’s applied to. The actionable code comes after the event.  In my example below, I use .text( ) on all <h1> elements in my doc to add a string:

 $(function(){     
    $('h1').text("hello world!");
});

The result in HTML is that the string is placed within <h1> tags. If there is content already in the tags, the content is replaced with .text( ) string.  Run the code and try it for yourself on jsfiddle here.

Likewise, the .click( ) event handler applies actionable code after the selector has been clicked on. For my example below, I used the .addClass( ) method to apply a class to the selector after it has been clicked.  CSS styles for that class are then set to the selector. For the html, I just created a paragraph inside <div> tags and added a <button> underneath

 

jquery_one

before

CSS styles for the class boxed

.boxed {
   border: 3px solid #33cccc;
   padding: 5px 5px;
   text-align: center;
   background-color: #ebfafa;
   color: #33cccc;
}

The class boxed is set to the <div> that contains the paragraph and styles it

$(document).ready(function() {
     $('button').click(function(){
           $('div').addClass('boxed');
   });
});

The results are shown below:

after button is clicked

after button is clicked

There’s tons more you can do with jQuery, and I’ll have more posts on the language in the future.  You can play around with my code examples on jsfiddle here, or download the demos I added to the #100DaysOfCode Github repo in the IntroJQ project folder.

*** Day 16 & 17 Recap ***

  1. Added demo2 to IntroJQ project folder
  2. Created buttons exercise and added to IntroJQ project folder
  3. Added buttons exercise to CodePen (available here)
  4. Tested for Module 1 in the jQuery course– Passed!
  5. Started Module 2