Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Thursday, January 8, 2015

CSS3 Transforms


Intro

CSS3 has been around for a few years now. Prior to CSS3 and HTML5 we all lived in the dark ages. I'm pretty sure dinosaurs roamed the earth, Republicans were Democrats, and humans had just learned to fashion clubs. No electricity even! But now with CSS3 we can do a whole lot more on our not-as-primitive-as-before web pages, making them look ever-so-pretty. CSS3 does quite a bit more than just transforms, but this is a blog not a novel so we'll stick with just this one topic for today.

What They Be?

What are CSS transforms? Well they're CSS actions (a single property within a style-sheet definition) that you can use on your tags. I mostly like to use them on images, but they're valid on divs, spans, whatever. It's a nifty way to get cool 2D and 3D actions performed without having to write complicated modification routines using JavaScript.

Example Set #1: 2D Transforms

What all 2D CSS transforms can you do? Rotate, Scale, Skew, Translate. What Are they? Here's a quick example that shows 4 transforms on groovy-looking images.

control
rotate 90°
Scale (x: 1.5, y: 0.5)
Skew (x:10°, y:45°)
Translate (x:30px,y:10px)
 
It might be kinda tough to tell exactly what this did so I'll break it down. The control image has no transformation. It's just a standard HTML image. The rotation transform rotates the image as though it were the hands of a clock. Scale scales your image by the amount given in the parameters, where 1.0 is the same as 100%. Skew stretches/smushes (good technical term huh) your image. I like to think of it as though somebody were to pull on opposite corners of the element, with the corners and direction determined by x/y and the angle. The translate transformation moves your image by the amount specified.

Here's the code used to generate the above effects:

<style type="text/css">
.rotate {
transform: rotate(90deg);
}

.scale {
transform: scale(1.5, 0.5);
}

.skew {
transform: skew(10deg, 45deg);
}

.translate {
transform: translate(30px, 10px);
}
</style>

<div style="float: left;">
control< br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
rotate 90&deg; < br />
<img border="0" class="rotate" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
Scale (x: 1.5, y: 0.5)< br />
<img border="0" class="scale" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
Skew (x:10&deg;, y:45&deg;)< br />
<img border="0" class="skew" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
Translate (x:30px,y:10px)< br />
<img border="0" class="translate" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="clear: both;">
&nbsp;
</div>


Cool huh? 2D transforms are fun to play with. But guess what? CSS3 does 3D transforms too!

Example Set #2: 3D Transforms

So yeah, like I said, it's time for some 3D transforms. You can do many of the same 2D transforms as 3D transforms, such as rotation, scaling, and translating. Let's look at a slew of samples again to get a feel for what we can do:

control
rotate x30°,z20°
scale x 1.3
translate z 50px

Let's take a closer look at these homeys. Control is still the control image, no transforms. the 2nd image rotates on the x-axis 30 degrees and the z axis 20 degrees. Image numero tres scales the image on the x-axis by a factor of 1.3, and the final image translates the image on the x-plane by 50px (brings the image forward 50px thus putting it on top of the 3rd image).

Here's the code used in them thar samples:

<style type="text/css">
.rotatey {
transform: rotateY(30deg);
}
.rotatez {
transform: rotateZ(20deg);
}
.scalex { 
transform: scaleX(1.3);
}
.translatez { 
transform: translateZ(50px);
}
</style>

<div style="float: left;">
control< br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
rotate x30&deg;,z20&deg;< br />
<img border="0" class="rotatey rotatez" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
scale x 1.3< br />
<img border="0" class="scalex" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
translate z 50px< br />
<img border="0" class="translatez" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="clear: both;">
</div>



Pretty cool stuff! You can make lots of nifty effects with just some CSS, HTML and time.

What's Next?

Take a look at the resources below, play around with transforms yourself. There's more I didn't cover though it's all pretty similar. Get yerself a beverage of your choice and have at it for an hour or two, see what shakes out.

Resources

CSS3 Transform Property
CSS Transforms
CSS3 2D Transforms

Wednesday, December 24, 2014

Microsoft Analytics

Intro:


Do you still want analytical data for your website but are looking for an alternative that isn't made by the corporation whose motto is "Do no evil"?  Why yes there is another option: Microsoft Analytics.  If you thought putting Google Analytics was a pretty simplistic endeavor to add some statistical info to your site you'll jump for joy how easy M$ made it.

Step by Step:


Step 1:  Download and install Application Insights Tools for Visual Studio.  It's a fairly straight-forward procedure you've done the bulk of your coding career.

Step 2:  Open your website project you want to add analysis data to.  For this venture I'm going to use Peter Hyde's blog chess project used back in the summer that was checked into the online version of TFS.

Step 3: right click on the project and around 1/3 of the way down you should see something like the following:
You should see a popup like the following:
Click the blue link that says "Add Application Insights to Project".  When you do that you should see a new folder within your project called ApplicationInsights.config.

Step 4: Run your project and do things within it!  I fired mine up and clicked the 2 buttons that exist within the project a few times.

Step 5:  If you right click on your project you'll now see an option for "Open Application Insights Portal...".  If you click that option soon after you did step #4 you'll find out the feed to M$ isn't as fast as you'd assumed it'd be.  Take 5-10 minutes and then go check again, you should see information in the Raw Event Stream like the following:




Gotta love M$ for having an app that links up to your visualstudio online account.

Enjoy!

Source:


Microsoft Analytics Info
Application Insight Tools Download

Thursday, December 18, 2014

Google Analytics

Intro:

Got a website and wonder about traffic statistics on it?  Feel like doing a little bit of footwork and employing Google to do the data analysis?  Here's the blog for you!  (No humanoid creatures were used in this blog, methinks they'll make another appearance after next week's blog).

Code:


The coding section really isn't that terrible, it breaks down to 6 steps which are basically copy and paste.  Step 1 creates the container elements you'll use to display the data.  Step 2 loads the library Google is graciously hosting for you.  Step 3 authorizes the user to actually use the info (yeah they charge for the service but the demo should be well the 50k free limit they offer).  Notice there's a Client_ID in use.  I got the pleasure of generating that through their dev site, it's a specific id used for my particular URL hooked to my google user account (yeah, they really want their money).  Step 4 creates the view selector (fairly straight forward).  Step 5 will create the timeline chart based on the data you wish to see.  Step 6 runs the query based on the info in steps 2-5.

And the code:

<!DOCTYPE html>
<html>
<head>
    <title>Embed API Demo</title>
</head>
<body>

    <!-- Step 1: Create the containing elements. -->

    <section id="auth-button"></section>
    <section id="view-selector"></section>
    <section id="timeline"></section>

    <!-- Step 2: Load the library. -->

    <script>
        (function (w, d, s, g, js, fjs) {
            g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (cb) { this.q.push(cb) } };
            js = d.createElement(s); fjs = d.getElementsByTagName(s)[0];
            js.src = 'https://apis.google.com/js/platform.js';
            fjs.parentNode.insertBefore(js, fjs); js.onload = function () { g.load('analytics') };
        }(window, document, 'script'));
    </script>

    <script>
        gapi.analytics.ready(function () {

            // Step 3: Authorize the user.

            var CLIENT_ID = '201188138677-fq93f6i42il8b06pnhchhpj2tu2urjfr.apps.googleusercontent.com';  // you need to generate your own, source link #2 below shows you how

            gapi.analytics.auth.authorize({
                container: 'auth-button',
                clientid: CLIENT_ID,
            });

            // Step 4: Create the view selector.

            var viewSelector = new gapi.analytics.ViewSelector({
                container: 'view-selector'
            });

            // Step 5: Create the timeline chart.

            var timeline = new gapi.analytics.googleCharts.DataChart({
                reportType: 'ga',
                query: {
                    'dimensions': 'ga:date',
                    'metrics': 'ga:sessions',
                    'start-date': '30daysAgo',
                    'end-date': 'yesterday',
                },
                chart: {
                    type: 'LINE',
                    container: 'timeline'
                }
            });

            // Step 6: Hook up the components to work together.

            gapi.analytics.auth.on('success', function (response) {
                viewSelector.execute();
            });

            viewSelector.on('change', function (ids) {
                var newIds = {
                    query: {
                        ids: ids
                    }
                }
                timeline.set(newIds).execute();
            });
        });
    </script>
    This means something.
</body>
</html>

Output:
























What does the last screenshot mean?  It means I generated a quick and dirty website to show off Google Analytics and as the site has no prior data to pull from it obviously won't generate a darn thing.  For those of you that have your own websites hosted in the wild, hook up some Google Analytics and bask in the glory of the traffic info!

Tune in next week when I do a write-up of Microsoft Analytics.

Source:

google developer site with coding samples

Thursday, December 4, 2014

Lazy Loading of Images With JavaScript and JQuery (a Plugin)

Intro

Have you noticed a growing number of websites that load images while you are scrolling down the page? Even if you haven't, just pretend that you have, or hey read on anyways! I'll try to entertain you. These pages are using a technique called lazy loading for the images. Your browser does not download the image until the image is at or near the viewport (not downloaded until you the client need to see the image), thus potentially saving on bandwidth and initial page display time for the user. Under the assumption that most visitors won't view every image in a large scrollable list, this can be quite a boon for you (the host) and for your users (the clients). If you're intrigued and want to read about one way to accomplish this feat, read on!

How to use the plug-in

There are quite a number of ways to lazy load images, but for this article I'll focus on just one. A JQuery plugin named unveil by Luis Almeida. For those of you unfamiliar with JQuery, I suggest you read up about it on their website before continuing. It will help you to have a basic understanding of what it does and how it works. If you want just the cliff-notes version, it's a lightweight (small download size) JavaScript library that handles a multitude of tedious tasks for you, and it has a very vibrant ecosystem of plugins from thousands of contributors.

Back to unveil...this plugin lets you specify a placeholder image for images as well as the final lazy-loaded ultimate image that the user will see. It's got just a couple other configuration options, but you can read about those on the unveil site linked below. We'll use it in it's most basic capacity, downloading an image lazily when the user scrolls down to that portion of the page. So, let's see how to use it.

Fire up your favorite html editor and create yourself an html page. Paste the content you see below into your html file:

<!DOCTYPE html>
<html>
 <head>
  <!-- link to jquery library hosted by google -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <!-- link to unveil library in the same directory as this html file -->
  <script src="jquery.unveil.js"></script>
 </head>
 <body>
  <div style="height: 1000px;">
   hi!
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://digitalis.nwp.org/sites/default/files/stuff_1.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://static.tumblr.com/429df189c9e81bb388196fb442db77ba/vbdvuoy/xrUmksw6n/tumblr_static_green-stuff.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://images.electricpig.co.uk/wp-content/uploads/2012/01/internet-stuff.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcT3WjcjnXnXG3MIZZ1rw3dQsjrx-06ogqZbcjArDwM3n1Q9ixrwCw" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://www.abc.net.au/tv/stuff/stuff_wendy.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ-5Ud4e36C7a9xsXgKr6ETuuecqSNorBhiWWelWj4UyfIUzzUwHg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://tosaenglish.com/wp-content/uploads/2012/06/image.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://www.seren.bangor.ac.uk/wp-content/uploads/2012/10/story-of-stuff-book-adds-to-the-vision-of-decreased-consumption.jpeg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://i.imgur.com/c6D2qCb.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://sd.keepcalm-o-matic.co.uk/i/keep-calm-and-stop-saving-stuff-on-desktop.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSvKoJ_CqT0yZQFelslk6DUralqV73_SfzuiTa30e6YC1cLzkxY" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://lh4.googleusercontent.com/-ZknF9DJA52o/AAAAAAAAAAI/AAAAAAAAAB4/JKBNFb96bM0/photo.jpg" />
  </div>
  <script>
   $(document).ready(function() {
     $("img").unveil(-400);
   });
  </script>
 </body>
</html>

Let's go over this code in sections. The first section I want to talk about is the "<head>" section of the html file. The important bits are the 2 script links. The first one links to a version of JQuery hosted by google servers. The 2nd script links to a js file that is expected to exist in the same location as your html file. Save the unveil js file to your hard drive in the same place where you have the html file.

The next part to talk about is all them thar div tags. The first one makes sure we have 1000 pixels taken up by useless stuff. I did this so that you could better play with the scrolling effect of lazy loaded images. The remaining divs are all containers for img tags. For those of you used to using img tags already, you know what the src attribute is; it's the url of the image to display. In the case of the above img tags, we're linking to a single placeholder image file which is a blue circle. Each of these img tags also contains a special data-src attribute which in the case of the unveil JQuery plugin, contains the image that will be downloaded and displayed when the user's viewport scrolls the image into view. Long story short, this is the image you'll actually see.

The last chunk of code I want to discuss is the final script tag. This contains our jquery function (the document.ready) which fires off when the document has finished loading. Our function above will apply the unveil plugin to any img tag on the page. The -400 in there tells unveil to only "unveil" the real image after it's 400 or more pixels into the viewport. If you specify no value here at all the image is unveiled precisely when it gets into the viewport, and this is normally what you'll want, but for this sample I wanted you to see the placeholder images a little better.

OK go ahead and open up the html file in your favorite browser! Depending on your monitor resolution, you might either see just the word "hi!", or maybe you'll see a blue circle or 2 at the bottom of your screen. Now scroll down slowly. You'll see the blue circles come up on screen, and if you keep scrolling they turn into other images (the final destination images as denoted by data-src). Pretty nifty huh? Feel free to play around with that -400, change it to other values to see the change in behavior. The closer you get to 0, the less time (vertical scroll-wise) you'll have to see the blue placeholder circles. The more negative the number gets, the longer you see the blue placeholders.

If you get truly excited by all this, you can bring up the developer tools of your favorite browser (mostly by hitting the F12 key) and watching the timing of image downloads to confirm you're getting what you think you're seeing.



What's Next?

There are other lazy loading JS image libraries out there, including some that are JQuery plugins. Play around with them and see if you find another you like. I like this one because it's extremely light-weight and easy to use, but maybe you'll find one you like better.

You could also create your own sample page from scratch. That's the best way to learn after all, not by copying something another person has already done.

Resources

unveil
JQuery

Friday, November 28, 2014

Custom Search for Your Own Website, Parte Deux

Intro

In Part 1 we setup a Google custom site search for your (or my) website. This lets you very quickly setup a search customized to your website, powered by Google. It's much easier than creating your own search. Take a look at the screenshot below however and you may notice a drawback:


While the search results look nice, They don't match the theme of every site out there, and possibly not our own website. The good news is that there are ways of dealing with this. I'll cover 2 of those ways:
  1. Changing your pre-canned Google custom site search theme.
  2. Modifying things yourself with CSS.

The Easy Way

Changing the theme of your custom site search within Google's interface using a pre-canned theme is pretty easy. If you created search for your own site in part 1 of this series (as opposed to creating a search function on my sample website), then you can go to the Google CSE Page, and navigate to the section shown in this screenshot:


You can pick any of the themes shown here, click save, and refresh the search page you made, and voila! You have a new search theme. Here's an example of the results when I chose the Espresso theme:


This has the obvious drawback of limiting you to only the pre-canned themes. While they do look nice, I think we can do better than that.

The Coder Way

As with many things HTML-related, the Google custom site search results (and even the entry) are controlled by CSS classes. This makes our job of customization quite easy really; all we have to do is override some CSS classes. In this first example, I've overridden the search box to use a green font:


This is a pretty simple hack, accomplished with the following css:

        .gsc-input {
            color: green !important;
        }


Our next trick is to make the background of the search results black and to change the text and titles to slightly different greens. Here's what the result looks like:


And here's the CSS to accomplish this result:

        .gsc-results-wrapper-overlay {
            background-color: black !important;
        }

        .gs-title, .gs-title > b {
            font-size: 30pt !important;
            color: limegreen !important;
        }

        .gs-snippet {
            color: forestgreen !important;
        }


Not much to it really. All we did was set the results wrapper overlay (the popup results box) to have a background color of black, we set search result titles (the hyperlinks) to 30-pt font lime green, and we set the snippets in the results to forest green. As you can imagine, there are many more possibilities than what I've covered so have at it folks!

What's Next?

If this topic has interested you, use your browser's developer tools to find other CSS classes you can override. Let me know if you need help with that. You might also experiment with other ways of changing around the look and feel of things, perhaps through JavaScript. It's not my recommended solution as generally JavaScript should be reserved for actual code not changing appearance, but I make exceptions :)

Thursday, November 13, 2014

Custom Search for Your Own Website

Intro

So I'm creating a website that will, among other things, contain a large number of details and lists of items. These items are of different types and will be spread out (categorized) throughout the site. Seeing as how I'm just a lone developer and this is a personal site, I have things I would like to spend my time on other than a fully customized search feature. How can I accomplish search with minimal effort? Google to the rescue! Using Google Custom Site Search, you can setup search on your website (using Google to crawl and index your site) fairly easily. Setting up custom search involves 2 things, from a high-level view: 1) Setup some sort of service that will crawl and index your website. 2) Create a search feature where users can search for and view results.

For the remainder of this blog I am assuming you have a personal google account. If not you can create one. You don't need anything special, in fact I started this off with just a plain old gmail account. If you don't have a google account of some sort, go create one before you get too far.

There is one other alternative if you don't want to create a google account or if you don't have a website you want to search: skip the "Account Setup" section below and skip right to the code. You're welcome to create a custom search for my website, at least for learning purposes.

 

Account Setup

I'm going to assume that you already have a website you'd like to create custom search for. If not, hey maybe you've got a friend who has a site that could use it. Just keep in mind you will need a way to prove ownership of the site in the end, so be sure to get your friend's permission if you're not doing this on a site of your own. Anyways, here is how to setup your Google Custom Search account.
  1. Go to this page: Custom Search - Create CSE
  2. Follow the instructions on that page
  3. You're now taken to a congratulatory page that tells you you've setup the custom search engine. 
Now you need to prove to Google that you have admin access to the domain which is hosting your site. You do this through google sitemaster tools.
  1. Go to this page: Google Webmaster Tools
  2. Click the "Add a Site" button if your site isn't already listed on the page.
  3. Enter the url of your site/domain. 
  4. Follow the remainder of the on-screen instructions from google, which will most likely have you log into your domain provider's account (quite frequently this is register.com) in order to set a server-side variable, proving you have administrative access to the domain.
Congrats! That's it for account setup.


Code

A search engine sucks if you don't have a way to search for things, and we haven't done that half yet. A quick note: we won't be doing any server-side code here. This is all client baby!

Flip back over to the congratulatory page from the end of the process of setting up your Google Custom Search. As of now (2014) there's a button labeled "Get code". Click on that. This will show you some JavaScript that you can copy and paste into a webpage. Fire up your favorite text editor. Paste this code (or if you have your own site/script, by all means place that in the editor instead).

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Search Demo</title>
</head>
<body>
    <h1>Search Demo</h1>
    <div>some content before search</div>
    <div>
        <script>
          (function() {
            var cx = '003872741270381885457:moxcvku22ym';
            var gcse = document.createElement('script');
            gcse.type = 'text/javascript';
            gcse.async = true;
            gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
                '//www.google.com/cse/cse.js?cx=' + cx;
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(gcse, s);
          })();
        </script>
        <gcse:search></gcse:search>
    </div>
</body>
</html>

Now fire up the page in your web browser of choice. You should have a screen that looks like this. Not too bad looking, considering the very small effort involves so far.

Go ahead and type something into the search box. If it's your own site, pick a word that you know is on the site. If you're doing my site, use "shadowrun" as your search term, and hit enter or click the search button. Your screen should now look similar to this:


Neat huh? That's all there is to it.

What's Next?

I'm just learning how this stuff works myself. I hear tale you can customize the look and feel of the search though and there might even be some other advanced options, so I think I'll look at those for next week. Feel free to be a teacher's pet and look ahead if you like.

Resources

Custom Search Engine


Thursday, October 16, 2014

SignalR and WebSockets

Intro

WebSocket is a new protocol, developed alongside HTML5, that allows a 2-way communication between client and server. With HTTP and your standard web browsers the communication is all 1-way; the client requests resources from the server and the server serves them. With WebSockets the server can send messages to the client without the client first requesting those resources. Messages can be passed from client to server and from server to client, keeping the socket connection open. Not all the grass is green in this land of Eden though; because this is a newer technology, not all browsers support WebSockets just yet.

This is where SignalR comes in. SignalR is an ASP.Net library that simplifies 2-way communication between the server and the client. It's an implemention of WebSockets, but it's not just that. It will use WebSockets when both the server and client support it, but when one or both does not support WebSockets it will fall back to other technologies that accomplish the same goal in similar ways. Simply put, SignalR allows you to use 2-way communication between client and server using whatever is the best way you are capable of using. Plus, the fallback mechanism happens behind the scenes. This means that you the coder code a single codebase for communication and SignalR makes the choice of which method to use for you. And, one extra bit of info...SignalR allows you to call client-side JavaScript functions from the server. That's some cool stuff!

To the Code!

Create yourself a new Asp.Net web application. Mine's named BlogSignalR1.


Make it an Empty web app with no folders, no core references, and no authentication.

Now add the NuGet package named SignalR.



Now add a class to your project named NotificationHub. Our app will have a single page where we, on the server, can notify our users of things that are about to happen on the website in real-time. This new class is what we'll use on the server-side to send those messages.

Here is the content you'll want for your new class:

using Microsoft.AspNet.SignalR;

namespace BlogSignalR1
{
    public class NotificationHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.broadcastMessage(message);
        }
    }
}


Go ahead and create another new class in your website named Startup. This class will tell Asp.Net to fire up/initialize SignalR. Here's the code for it:

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(BlogSignalR1.Startup))]
namespace BlogSignalR1
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}


Now it's time to work in client-side code a little. First create a new html page in the project. Name the file default.html. Here's the content of that one:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic User Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi user!
    <div id="notificationArea">

    </div>
    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Create a function that the hub can call to broadcast messages.
            notification.client.broadcastMessage = function (message) {
                // Html encode display name and message.
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#notificationArea').text(encodedMsg);
            };

            //create a connection to the hub
            $.connection.hub.start().done(function () {
                //sometimes you might need to do something after creating the connection to your hub; for this example, we do not
                });
        });
    </script>
</body>
</html>


This is a very simple page whose sole purpose is to display notifications from a site admin within the div named notificationArea.

Note: there is a possibility your version of either SignalR or JQuery may be different than mine. If so, please modify the script references as necessary to reflect the version you have in your Scripts folder.

The above html file implies we need one more file, this one for admins to create notifications for users. Go ahead and create a new html file called admin.html. Here's the content:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic Admin Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi Admin!
    <label for="message">Message:</label><input type="text" id="message" />
    <button id="disseminate">Disseminate</button>

    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#disseminate').click(function () {
                    // Call the Send method on the hub.
                    notification.server.send($('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>



Another simple page; one entry where you enter text, one button that you click to get it to push out a notification to clients. Let's try it out!

Go ahead and run the solution, navigate to default.html. Open up a 2nd tab in your browser and navigate to admin.html. Type some text into the entry on the admin page and click the Disseminate button.


Now go back over to the other tab containing default.html and your text is there!

Yes that's right folks, with a little bit of server-side code and a little bit of client-side code, you can create a basic site that allows real-time 2-way communication using SignalR. This is some wonderful technology that has tons of potential uses (chat is the most oft-talked-about usage for SignalR and WebSocket technology). If you want to make sure I'm not fooling you, just drop a breakpoint in your server-side and client-side methods and you'll see the trip from admin.html client, to server-side NotificationHub class, back down to default.html. It's mesmerizing!

What's Next?

Play around with the code and see if you can figure out what all of that JavaScript is doing. I find the best way to dig through stuff is to set breakpoints and trace into it and I'm sure you'll have luck with that method too. You can also dig around in the SignalR documentation and tutorials, as I've provided a link to such beasts down in the Resources section.

Resources

SignalR
WebSocket
My Code

Thursday, September 25, 2014

HTML4 versus HTML5: new additions/changes to HTML5

Introduction:

Html was first published in late 1991 by Tim Berners-Lee.  It has equally enriched and tortured our coding experiences on the world wide web ever since :).  This blog shall show the differences between Html 4 (the most current implementation) and Html 5 (new and improved).

New and improved in Html 5:

  1. Consistent defined error handling!  Less effort on the developer to have to write javascript validation when it's built into the newer spec!  Think of creating a text field to validate an email address and then having to hook in a javascript wrapper to require the @ and . characters exist, now think about setting an attribute like required=true within the tag you'd just created.  Time saver!

  2. The <canvas> tag which is aimed at animation (goodbye Flash animations?).

  3. Deprecating tags that can (and should) be done in CSS.  Goodbye <b>,<noframes>, and <font>!

  4. Native support for audio and video similar to the <img> tag.  Injecting the Thundercats theme song into a website based on Hello Kitty or the Dungeons and Dragons 80's animated series?  Yes please :).
  5. Newer and updated APIs!  Better support to have the browser be an online/offline application program!  Adding click(), focus(), and blur() to all elements on the page! Yes putting blur() on most any element on the page is cheesy, but more options are better!

Tune in next week when I attempt to create the same web page using HTML 4 and HTML 5.

Source:

Wednesday, September 17, 2014

CSS Intermediate: an explanation of CSS Advanced

Introduction:

You're probably wondering at this point: Daniel, you've gone in the wrong order!  Well... kinda :)  Chances are some of the CSS you'd seen last time was interesting to look at but you had no clue what each section was attempting to do with various non alpha-numeric characters used in each declaration.  That's why an intermediate blog is in order.

Onto the explanation of last week's coding fun.  Below is the code from layout.css:


* (asterisk) takes care of all classes in the calling page.
body takes care of the body tag that exists on the calling page.
header takes care of all generic header tags that exist on the calling page.
header h2 takes care of the specific header h2 tag(s) and extends the css from header that was defined above it and modifies all h2 tags that exist on the calling page.
.container takes care of all elements with the id of container on the calling page.

This is some cool stuff!

From the file slideshow.cs we have even more interesting samples:


span.cap takes care of all span tags with the id of cap that exist on the calling page.  Think of this logic in the form of (tag type).(id of tag type).

That covers the bulk of the page layout except for one other declaration type on the page:  span#slide1:target ~ ul.slider li.lArrow a.  Where the . selector uses all generic (id=tag) tags # calls out a specific tag name.  The ~ (tilde/squiggle/twiddle) selector allows you to call a sibling element of the first id'd item getting css'ified to simplify the declarations you declare.

Here's another code sampling from last time, this time a portion of the index.html code written to call the CSS files used for the last tutorial:



for the css declaration span#slide7:target ~ ul.slider li.track .tr7 that makes  the class "tr7" within the list item (li) class "track" within unordered list (ul) have the background color of #f00 (this is the hexadecimal value for Red).

Enjoy!

Source:


Wednesday, September 10, 2014

CSS Advanced

Introduction

So the last tutorial showed some cool looking modifications to a web page with not too much code behind to achieve it.  You're probably asking yourself:  Tidwell's annoyance of bards seems to exist (yep!), any other cheese he could potentially code about for an advanced tutorial?  Yeppers, let's take the way back machine to the 80's where my first introduction to Dungeons and Dragons was in the animated form via Saturday morning cartoons.  Lets see if I can make some cheesy images from the "players" in the series somewhat palatable to view in a webpage.

Let the coding begin!

First lets create a webpage.  Nothing too fancy, here's something I "borrowed" from the interwebz (code downloadable in link at the bottom of the tutorial):



Now we need some css to make it work.  The first code sampling is a small css file we'll call layout.css to handle the general layout of the website:




and also a file we'll call slideshow.css to handle the transition from one jpg file to another:




The result looks like this in a web browser:



Wowsers!  Very little HTML, whole lotta love (for DnD the animated series anyways).  Even more powerful stuff for very little code behind!

Source:
http://www.script-tutorials.com/how-to-create-a-pure-css3-slideshow/

Image Source:

http://img4.wikia.nocookie.net/__cb20100224154850/dungeonsanddragonscartoon/images/a/ac/Diana.jpg

http://img1.wikia.nocookie.net/__cb20100224155117/dungeonsanddragonscartoon/images/1/10/Sheila.jpg

http://img2.wikia.nocookie.net/__cb20100224155256/dungeonsanddragonscartoon/images/1/10/Ericavalier.jpg

http://img4.wikia.nocookie.net/__cb20100224155632/dungeonsanddragonscartoon/images/0/07/MAGICIAN.jpg

http://img4.wikia.nocookie.net/__cb20100224155712/dungeonsanddragonscartoon/images/a/af/Barbarian1.jpg

http://img1.wikia.nocookie.net/__cb20100224154119/dungeonsanddragonscartoon/images/2/2a/Hank.jpg

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8iVf9HhZIr-Nv-KjWaPte6MpeT9spJe0c21pFBZJYRszvLgC07Ar3hBCI07AoiydBJe17cRYb4pgR3Z7VcDCQG4EEyehn-vYzyPtk92Jn-aAZcLmo15ROpOskVsYFTHz4y8kwSW7TvqOn/s1600/25th.jpg


Wednesday, August 27, 2014

jquery advanced: roll your own plugin

PREFACE:

So we've hidden some text, changed the size/color of other text at the click of a button, and made a pictorial slideshow.  Now what?  Our second adventure in jquery required the usage of some extra plugins, this adventure we'll learn how to write our own jquery plugins to use!

CODING CONCEPT:

Let's go for some more cheese:  reversing the text of list items we have displayed to the user.  It being football season, let's pick on four different teams from the NFL!

ACTUAL CODE:


The plugin code! Please note I've named the file jquery.reverseme.js

The html code used to call the .js file above:

Our final end product when rendered in a browser:


SOURCE:

http://www.sitepoint.com/how-to-develop-a-jquery-plugin/