Оcenka-BEL.com - безплатни онлайн тестове, пробни изпити, видео уроци и помощ при писане на задания от литературно и хуманитарно естество

Web Development Soup

Публикувано: 2017-08-14 08:09:39

Свързано изображение

Copyright © 2013-2015 by Ivan Dimov

All rights reserved. This e-book or any portion thereof may not be reproduced or used in any manner whatsoever without the written permission of the author.

Disclaimer of warranty

The author makes no representations or warranties with the respect to the accuracy or completeness of the contents herein and specifically disclaim all warranties, including, but not limited to, fitness for a particular purpose. The advice provided in this e-book may not be suitable for every situation.

First Edition, 2015

 

About the Author

Ivan Dimov is a student of IT and a full-stack web developer. He is currently following a Master’s degree in Informatics and working as a freelance web developer. In his free time, he writes articles about everything Web for companies such as InfoSec Institute, SitePoint and PHPGang. He has won several hackathons and competitions related to developing apps in Bulgaria. He has worked on Web things for firms such as Onix Web Development and is fascinated with everything having the word Web in it.

He has prepared a website for this book with some goodies located at http://wds.dimoff.biz and you can contact him through his website, obviously located at http://www.dimoff.biz or find him in Facebook.  

What’s in this book?

In Web Development Soup,  you will learn important HTML, CSS, JavaScript, and PHP concepts. You will get up-to-date with the recent developments in HTML5 and CSS3 – the tags, selectors, attributes and APIs they offer. You will get acquainted with Foundation and Twitter Bootstrap which are invaluable when it comes to designing user interfaces. In terms of JavaScript, you will build basic knowledge of recent developments such as Angular.js, jQuery, Node.js, new JavaScript APIs and features. In terms of PHP, you will get a head start on WordPress, Laravel, CakePHP and so on.

Throughout the book, besides explaining different possibilities in the programming languages and giving sample codes we will also be building real and functioning applications such as a voice chat with Node.js, a small marketplace with CakePHP, a simple game with JavaScript and Processing.js, two apps where users can take and manage notes, a screenshot-capturing service in which users can enter a URL address and get a screenshot of the website as our server sees it, and more.

Furthermore, some widgets will be built such as a countdown timer which can be reused in your applications, a PHP script which takes an URL address to a WordPress RSS feed and extracts all relevant information for you to use or displays its contents in a table, amongst others.

Check out the book’s accompanying website: http://wds.dimoff.biz.  
In it, you can download all code samples from this book and examine them or run them in a browser. Furthermore, you can do the exercises on the website each time you read a chapter and if you manage to complete all exercises and the final exam without mistakes (you can repeat the exercises as much as you like) you can get a special certificate!

In the bottom of the book, you will find your username and password. Use them to access the code samples and the tests.

 

Some other useful aspects of web development are also examined in the Web Development Soup - such as improving your workflow, securing web applications and optimizing your websites in search engines.

Тhe content of the book will serve you well in establishing a base knowledge of the different aspects of web development and guide you to find out the sphere that you most like and will empower your career.

This book will be periodically updated with new content, as well as the accompanying website. New things will be added at least once every few months.

If you have a question or feedback related to the book and its accompanying website feel free to write an email to ivan (-at- ) dimoff.biz

 

 

Table of Contents

 

Web Development Soup. 1

What’s in this book?. 2

Table of Contents. 2

HTML5 APIs and features. 7

Media queries in JavaScript. 7

HTML5's download attribute. 9

Browser support. 9

Drag and Drop API 10

Browser support. 10

CSS calc(). 13

Browser support. 13

Box-sizing. 15

Srcset attribute. 16

Browser support. 17

Srcset example. 17

CSS3 Transforms and Transitions. 18

Transforms and transitions examples. 18

Conclusion. 20

CSS-like JavaScript selectors. 20

Browser support. 20

Examples. 20

Cool things you can do with CSS3 attribute selectors. 21

Semantic Tags. 23

Collapsible boxes. 24

Introduction. 24

Browser support. 24

The

tag. 24

 

Examples of the details tag. 25

JavaScript. 27

Manipulating the browser's history for SPAs. 27

Introduction. 27

Browser support. 27

Session history management for SPAs. 27

Conclusion. 30

Creating an offline application using HTML5 Application Cache and the Underscore Templating Engine. 30

Useful tiny JavaScript functions. 36

Force HTTPS in JavaScript. 37

HTML characters and security. 37

Parse query string with JavaScript. 37

Break your website out of iframes. 38

Conclusion. 39

A note-taking app with Angular.js. 39

Introduction. 39

Modules, controllers and factories. 39

Form validation in Angular.js. 42

Further reading. 44

jQuery. 44

Lazy loading Images. 44

Countdown timer with Vanilla JavaScript. 46

The visuals. 47

The logic. 47

Creating a game with JavaScript and Processing.js. 51

Conclusion. 61

Node.js Real-time Chat Application, Part I 61

The markup. 62

The styles. 63

The client-side JavaScript. 64

Speech Synthesis Browser Support. 65

The back-end of the chat. 66

Finishing up the back-end. 68

Submitting the app to Heroku. 68

PHP. 70

Frameworks. 70

Laravel 70

Building a simple marketplace with CakePHP 2 and Foundation. 75

Setting up the Models. 85

Master View.. 88

Building AppController. 91

Home View.. 93

Finishing OffersController. 95

Category of Offers View.. 96

Offers Index View (Recent Offers). 97

Last edit in the Offers Controller. 102

Creating the Orders Controller. 103

Creating the Users Controller. 103

Login View.. 105

Register View.. 106

WordPress. 107

Adding Custom Design or Functionality to your WordPress Theme. 107

Creating a Shortcode for your Theme. 112

Creating a Plugin with a Custom Taxonomy. 116

Creating a Plugin That Consumes a Web API in WordPress. 121

Introduction. 121

What's new?. 122

The Plugin. 122

Preview.. 125

Conclusion. 125

PHP in the Command Line. 126

Getty. 126

Conclusion. 129

Parsing WordPress feeds with SimpleXML. 129

Writing to XML files in PHP using XMLWriter and DOM... 135

APIs. 137

Integrating Payments with Stripe. 137

Creating your own simple website screenshot capturing service with PhantomJS and PHP. 142

Installation. 142

Coding the PhantomJS Service. 143

Coding the front and back-end of the service. 143

Web Scraping. 146

Using the Web Scraper Chrome Extension. 146

How to prevent your website from being scraped and a demo of the Goutte PHP Scraping Library. 154

Why should I worry about scraping?. 154

What is the legal situation when it comes to Web Scraping?. 155

Preventing Web Scraping. 155

CSS. 165

Creating a webpage with Zurb's Foundation Library. 165

Introduction. 165

The markup of the page. 165

Foundation grid system.. 165

The navigation. 165

The Beer Mugsy's Title. 166

The Beer Mugsy's Promo Section. 166

Installation. 167

Quotes. 168

Product listings. 168

Pagination. 169

Responsive video. 169

Beer Mugsy's footer. 170

Conclusion. 170

Sass. 170

Variables in Sass. 170

Nesting selectors. 171

Comments. 172

Mathematical operations,  interpolations and for loops. 172

Randomness and concatenation. 174

Conclusion. 175

Workflow tools. 175

Git and GitHub. 175

Increasing HTML workflow with Emmet. 178

Web Application Security. 181

General HTML5 Security. 181

New attack vectors. 181

Browser’s History API 182

SVG.. 183

Web Storage. 185

CORS (Cross-Origin Resource Sharing). 188

Conclusion. 188

General HTML5 Security, Part 2. 188

Content Security Policy. 189

New Remote File Inclusion. 190

Geolocation. 192

Web Workers. 193

Iframe sandboxing. 196

Data Extracter. 198

Conclusion. 200

References and Further Reading: 200

Search Engine Optimization. 200

Introduction. 200

Pretty URLs. 201

Meta tags. 201

Heading tags. 202

Image's alternative text. 202

Other techinques. 202

Final SEO Tips. 203

Accessing the book’s website contents  203

HTML5 APIs and features

 

 Media queries in JavaScript

The HTML5's matchMedia API allows you to use media queries in JavaScript. If you want to change something programmatically depending on the screen size that cannot be done with CSS this comes in really handy. It is widely supported with 88.87% of the Internet users' browsers being able to take advantage of the API.

Support starts from:

1.  IE10+

2. Firefox 31+

3. Chrome 31+

4. Safari 7+

5. Opera 29+

The syntax is the following:

if (window.matchMedia("(min-width: 720px)").matches) {

           // execute code here only if the screen is wider than 720px

        }

 

If you want a truly responsive site you cannot just execute the conditional once when the user is first visiting the page but you would have to listen for changes to the screen size and execute the conditionals again.

 

We have created a simple wrapper for matchMedia to exemplify how you can achieve this:

function responsify() {

        function makeResponsive(args,callback) {

          var mQuery = args.min && args.max ? "(min-width: " + args.min + "px" + ") and (max-width: " + args.max + "px)" : "";

            mQuery = !mQuery.length && args.min ? "(min-width: " + args.min + "px)" : mQuery;

            mQuery = !mQuery.length && args.max ? "(max-width: " + args.max + "px)" : mQuery;

            if (!window.matchMedia) {

                //provide fallbacks

            }

          if (window.matchMedia(mQuery).matches) {

                callback();

            }

        }

 

        function responsiveHandlers() {

            //bootstrap xs device

            makeResponsive({'min' : 1}, function() {

                document.getElementsByTagName("body")[0].style.backgroundColor = "#000";

            })

 

            //bootstrap sm device

            makeResponsive({'min' : 768}, function() {

                document.getElementsByTagName("body")[0].style.backgroundColor = "crimson";

            })

 

            //bootstrap md device

            makeResponsive({'min' : 992}, function() {

                document.getElementsByTagName("body")[0].style.backgroundColor = "lime";

            })

            //bootstrap lg class

            makeResponsive({'min' : 1200}, function() {

                document.getElementsByTagName("body")[0].style.backgroundColor = "orange";

            })

        }

 

 

        responsiveHandlers();

        window.addEventListener("resize", function() {

            responsiveHandlers()

        })

    }

 

    responsify();

 

We create a separate scope and in it we define a function called makeResponsive which takes an object with possible min and max properties and a callback function which would be executed if the screen matches the given numbers in the min and max arguments. We also listen for screen resize and execute our media query checks again on such an occasion.

 

If you plan on using it, be sure to fill in some fallbacks in the wrapper above and modify it to suit your needs.

 

HTML5's download attribute

 

The download attribute should be placed on an anchor and allow users to save the linked file instead of opening it in their browser. For example, if your anchor’s href attribute points to an image - users would be presented with a download screen instead of opening the image in their browser. However, the support is a bit lacking at the moment.

 

Browser support

1. IE - not supported

2. Firefox 31+

3. Chrome 31+

4. Safari - not supported

5. Opera 29+

 

Here is an example of how you can use it:

href="screen.png" download="facebook-bot.png">

 

    src="screen.png" alt="Dimoff the Facebook Bot"/>

 

 

 

 

 

Whenever the user clicks on the image, he will be prompted to download it and the default name would be facebook-bot.png instead of screen.png. Of course, you can set the name programmatically with something like: download="$dlname;?>"

 

 

 

Drag and Drop API

 

 

 

The days when one relied heavily on libraries and third-party plugins to achieve drag and drop functionality are coming to an end with the Drag and Drop API

 

Browser support

 

The Drag and Drop API is not supported very well with 60.24% global support.

 

The following browsers support it:

 

1. IE8+ have partial support

 

2. Firefox 31+

 

3. Chrome 31+

 

4. Safari 7+

 

5. Opera 29+

 

 

 

To exemplify the drag and drop API we will be creating this:

 

 

 

It is a simple notes web app. We will just create the functionality to move your notes from the type "Important Notes" to the type "Useless Notes". In fact, our code can be modified to include new notes and new note types with ease and the drag and drop functionality will handle them properly.

 

 

 

The HTML that we need is:

 

 

 

 

 

We have added some basic CSS:

 

 

 

 

 

As you can see from the CSS, when you drag the notes to a different section they will change colors immediately as we have added selectors that change the color of the note depending on which section it is located in. You can also see that we have set the cursor to move so our users would be aware they can drag the note.

 

 

 

At first, we set up our notes and note sections in variables on DOM load.

 

 

 

Then we loop for each note and add a unique class (we could have used an ID) to it. You will see why in a bit.

 

We add to the note an attribute of draggable so that our notes can be draggable and so that we do not have to manually add it when adding each note to the DOM.

 

Then, we add an event listener that will catch the start of a drag and save its class name as data in transfer. Because the class names would be unique we would later listen for drop events and append the element with that class name to the container where the note was dropped.

 

 

 

Finally, we loop over each note section/type and add a drop listener to it. We get the data that we saved as data in transfer (the class name of the dragged element) and use it to find the element with document.getElementsByClassName and move the element to the note section where we have dropped the note in.

 

 

 

That's it! Nothing really complicated. If you are working on a project whose user base have the latest technologies, then you can certainly use it but you should consider adding some kind of a fallback for now.

 

CSS calc()

 

 

 

The calc property can be used as a value to other CSS properties such as width, height and top. It allows you to perform calculations with the measure units in CSS - such as pixels, ems and percentages.

 

Browser support

 

The calc property has decent support with 81.52% of used browsers worldwide supporting it.

 

1. IE9 - Partial support

 

2. IE10+ - Full support

 

3. Firefox 31+

 

4. Chrome 31+

 

5. Safari 7+

 

6. Opera 29+

 

 

 

For more details on the browser support, visit http://caniuse.com/#feat=calc

 

The calc property can be useful for many sizing purposes so you would not have to calculate top,left,right,bottom offsets or widths and heights manually.

 

 

 

We will show you a simple example to illustrate the property. What we do can easily be achieved without calc but it serves as an illustration.

 

 

 

 

 

We add two boxes in terms of markup.

 

Then, we set their width to be equal to 50%. However, if we directly set the width to 50% for both and add margins and borders to them - there will not be enough horizontal space on the row for the second box and it will move to the next line. This is why we add calc and subtract from 50% the margin and the border for that particular box.

 

For the first element, we have a 1em margin but the margin comes on the left side and on the right side of the element as well so we have to subtract 2em. The same is valid for the border which takes the space of 1 pixel on the left side and 1 pixel on the right side. Making such a cross-unit measurement manually may take a lot more time.

 

 

 

Now, our elements take all of the space that our margin has made available for them.

 

 

 

Figure 1: Two boxes with CSS3 calc

 

 

 

Box-sizing

 

You can start using the box-sizing property without fallbacks. It has 96.99% global support (according to Can I Use) so I would not be mentioning the browsers that support it.

 

The property has two keywords of notice: content-box and border-box.

 

Content-box is the default set for the width and height properties when you write CSS. This means that when you add a width to an element - this width would be taken only by the content of the element itself. Any padding, margin or border that you add will have separate widths. Thus, if you add two elements with 50% width and add either a padding, margin or a border then they would not be placed on the same horizontal row.

 

A fix for that is setting the box-sizing to border-box. This would include the padding and border to the width that you set so you would only have to include the margin when making calculations on how to position the elements horizontally.

 

Below is an example of how we take advantage of box-sizing and calc:

 

 

 

We only subtract the margins from the width and any padding and border we add to the element will be added by subtracting from its content area.

 

 

 

The result is two boxes that take all the space available to them.

 

 

 

Figure 2: Two boxes made with box-sizing

 

 

 

The box-sizing property is one that you should start using today, if you are not using it already. About the calc property - it would be best to rely on CSS preprocessors such as Less and Sass for now as they possess many more benefits than an implementation of calculating measurement units.

 

 

 

Srcset attribute

 

 

 

HTML5's srcset attribute was much needed with the technologies that we have today. Smartphone use has been increasing tremendously and many Internet users are connecting to the web through slow 3G networks and serving them huge image files when they have a small viewport is not a good option. Not only does this deplete their traffic limit but it makes them wait forever for the website if they are not connected to a high-speed Wi-Fi. And, this eats up your hosting’s bandwidth.

 

 

 

So, the srcset attribute came to the rescue. It allows you to serve different versions of an image to users depending on their viewport area.

 

Browser support

 

The browser support is not good enough yet but that would change in the near future.

 

 

 

Currently,  IE Edge has partial support for srcset, Firefox 38+ and Chrome 39+ support srcset fully,  Safari 7.1+ provides partial support and the attribute is fully supported in Opera from version 29+.

 

 

 

On a global scale, 55.75% of the Internet users are running browsers which can handle srcset.

 

 

 

For more information on browser support, visit http://caniuse.com/#search=srcset

 

 

 

Srcset example

 

 

 

 

 

We create a normal img tag and set its src. The src would be used as a fallback for browsers that does not support the srcset attribute (they will always get the image provided in the src attribute as expected)

 

Then, in our srcset attribute we define all of our image versions in a comma-separated list. First, we write the path to the image followed by a space and the width of that image version followed by w.

 

Then, we add a sizes attribute and tell how much of the viewport is dedicated for the image. If you have breakpoints where the size of the image changes you can add media queries. Here is how the format for the sizes attribute looks like: [media query] [length], [media query] [length], ....

 

In our case, we want our image to always take 50vw units or 50% of the viewport so this should be taken into account when determining which image to serve.

 

 

 

 CSS3 Transforms and Transitions

 

 

 

CSS3 Transforms have a pretty decent support with 90.9% global support. CSS3 Transitions have good support as well:  89.32% of user browsers support transitions.

 

Transforms allow us to rotate, scale, move and skew elements while transitions allow us to animate CSS properties over time. They can be used together to produce animations and effects.

 

Transforms and transitions examples

 

 

 

 

 

Here we create a simple animation when the user hovers over our image. Each time the user hovers the image will rotate in 360 degrees within the period of 1 second. Since we have set up the rotate to be 360deg or 360 degrees our image will return to its normal position after the transition finishes.

 

 

 

For our next, animation - we create a container with a button and an image. Whenever the user hovers over the button an animation will trigger for the image.

 

 

 

You can see that we have used .hover-me-evo:hover + .evo to animate the image with a class of .evo whenever the button with a class of .hover-me-evo is hovered upon.

 

The translate property moves an element. It takes two arguments - a unit measurement telling it how much to move the element in the X and Y axes. translateX takes only one argument and moves the element on the X axis, while translateY movies the element in the Y axis.

 

You can see that we move the element to the end of the viewport (100vw is 100% of the viewport or the rightmost corner) minus 420 px. Our image has a width of 400px so we do not want it to move beyond the viewport width.

 

Now, for our final example we add an image to the DOM:

 

 

 

Then, on hover we apply two css transforms - scale and skew. We increase the image's width with 50% and the image's height with 30% using scale. Giving scale a value of 1 would leave the image as is while giving it a value of 1.1 would scale it with 10%.

 

 

 

You can see that to add two or more CSS transforms you only separate them by space.

 

Conclusion

 

If you are not using CSS3 Transforms and Transitions yet, now is a good time to start applying them in your projects, at least because they are faster than animations produced with JavaScript.

 

Using the srcset attribute is also a good way to be forward compatible since if the user does not support it - they do not really lose anything as the normal src of the image would be loaded.

 

CSS-like JavaScript selectors

 

HTML5 brought us CSS-like JavaScript selectors and they have a pretty decent support. This is really handy and was one of the main benefits of the jQuery library. The lengthy JavaScript selectors such as document.getElementsByClassName("container")[0].getElementsByTagName("p")[0] are on the way to history.

 

 

 

Browser support

 

 

 

The following browsers support the querySelector property:

 

 

 

1. IE8 has partial support

 

2. IE9+ supports it fully.

 

3. Firefox 31+

 

4. Chrome 31+

 

5. Safari 7+

 

6. Opera 29+

 

 

 

Generally, it is supported by 96.92% of the Internet users out there so you can decide to use it without any fallbacks (statistics can be found at http://caniuse.com/#feat=queryselector )

 

Examples

 

First, we add some basic markup:

 

 

 

We can use querySelector and querySelectorAll. querySelector returns the first element that matches the given string with a CSS selector while querySelectorAll returns us all elements that match the CSS selector.

 

 

 

If we did not use querySelector and wanted to get that paragraph (which does not have a class on its own) we would have to type something like:

 

 

 

 What a relief!

 

If we want to get both (all) paragraphs with the div with class of container we could use:

 

 

 

Cool things you can do with CSS3 attribute selectors

 

 

 

We are going to show you how you can easily add an image or text to a link indicating that it is a .pdf, .doc file or whatever you like. We are also going to show how you can signal the users that a particular link will move them away from your website.

 

In our markup, we have a div with links:

 

 

 

Firstly, we will add a .pdf icon to the links that lead to a .pdf file:

 

 

 

a[href$='.pdf'] is instructing the browser to search for anchors which have a href attribute whose value ends with .pdf. $= followed by text searches the attribute for a value that ends with the provided text.

 

 

 

We have used the :after pseudo-element and its feature content to add an image to the end of each matched anchor.

 

Let us repeat the process with the files that end with .doc:

 

 

 

If you view in a browser the links now you will see that href="pdf4.docx">What do men know about women does not have a Microsoft Word icon. This is because it does not end with .doc, it ends with .docx.

 

 

 

Now, to add an external icon to the websites pointing to other domains we would have to use another attribute selector that seeks the beginning of an attribute for a certain value: ^=.

 

 

 

This searches for any anchor with a href attribute that starts with http (it could be http:// or https://). Notice also that this time we insert the icon before the content of the anchor itself with the :before pseudo-element.

 

Here is what we end up with:

 

 

 

Figure 3: CSS3 attribute selectors in action

 

Semantic Tags

 

 

 

There is a demo page in the Code Samples that shows most of the new semantic tags and I will describe the new elements that are used in it as they appear in the page.

 

The first semantic tag that I am going to show you is the

tag. Its name seems simple enough but it is important to know that it can be used not only for the main header of the page. The tag can also be used to indicate headers of different parts of your page such as the header of an independent article located in your website.

You usually insert into a header one or more headings (

to

), some sort of a logo or information about the author of the post/article/document that will be discussed below it.

 

 

We include another new element which is the

- it is best used for the primary navigation(s) of the page. It would not be a good idea to enclose every distant anchor on your webpage with the tag.

 

 

Next, we have the

tag which indicates sidebars or content that is related to the DOM location where it is being placed but it is not essential to it. For example, if your readers are reading an article on a page, you can use it to show the user additional information about the article such as references, highlights from it, interesting facts and even to show the user related articles.

 

 

You can also see the use of

. You should use it for code snippets, images, diagrams, charts and other visual content that is related to the place where it is placed but in the same time the enclosing content should still make sense without that figure. Inside the tag you can nest other tags such as and you can add a caption which explains the figure through the element.

 

 

The

tag indicates a generic section in the document and it should not be used merely for styling purposes as it affects the document's outline. The specification pinpoints that the theme of the section should be specified by inserting one or more headings in the section. An important difference between and is that the tag should be a self-contained composition so that when you copy the article to a different place - it would still make sense and will not require the rest of the website's contents.  Like the tag's name suggests, you could use for blog posts, newspaper articles, comments, widgets and many more.

 

 

The

could be used not only at the page's end but it can be used throughout different sections and articles. It typically contains information such as information about the author, copyright notices, contact information, a map of the site, related information,a way to go back to the top amongst other possibilities.

 

 

The last tag we are going to discuss is - you can add an attribute called datetime to it. This attribute supports a date and a time in the following format: YYYY-MM-DDThh:mm:ss. The element and attribute are machine-readable and can pinpoint times when an article was created, updated or when an event is going to occur. Here is an example of how you might use it: 

 

 

 

Collapsible boxes

 

 

 

Introduction

 

 

 

HTML5 allows us to create collapsible boxes (panels) without the need of adding our custom JavaScript code - the

tag allows us to create panels with minimal setup and makes our pages load faster. However, it should still be used with fallbacks as support is not very decent as of the moment of writing this.

 

 

Browser support

 

 

 

The

tag is supported in Chrome 31 and greater, Opera 27 and greater and Safari 7 or greater. The Android's built-in browser supports it as well. Notably, IE and Firefox does not have a released version with support for the tag at this moment.

 

 

The

tag

 

 

 

The details tag accept an optional child -

. The contents inside the details tag (we can place nearly everything) will be hidden until we open the box. The title of the box would either be a localized version of Details or if we add our own summary tag - the title would be the summary that we have added.

 

 

Optionally, we could declare if we want the collapsible box to be expanded or opened when the page is accessed with the attribute open. Its value is false by default which makes the contents of the boxes hidden until the user clicks on their title.

 

Examples of the details tag

 

 

 

Here are some examples of the details tag in action.

 

First, we change some of its default styling:

 

 <

За контакти: моб. телефон: 088 7 0 5 8 6 2 1 | еmail: pdivanova [- - -@- - -] mail.bg | Web design by: Ivan Dimov
-->