Thursday, October 5, 2017

A Visual History of Content Marketing #Infographic

While it may seem like a relatively new phenomenon, content marketing has arguably existed since The Stone Age. Okay, maybe that’s a bit of a stretch, but this new infographic from Uberflip outlines the evolution of content marketing, which not only provides insight into the origins of the...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

Hello, World! Your First JavaScript Programs

The following is a short extract from our new book, JavaScript: Novice to Ninja, 2nd Edition, written by Darren Jones. It's the ultimate beginner's guide to JavaScript. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.

It is a tradition when learning programming languages to start with a "Hello, world!" program. This is a simple program that outputs the phrase "Hello world!" to announce your arrival to the world of programming. We’re going to stick to this tradition and write this type of program in JavaScript. It will be a single statement that logs the phrase "Hello, world!" to the console.

To get started, you’ll need to open up your preferred console (either the Node REPL, browser console, or ES6 Console on the web). Once the console has opened, all you need to do is enter the following code:

console.log('Hello world!');

Then press Enter. if all went to plan you should see an output of "Hello, world!" displayed; similar to the screenshot below.

Congratulations, you’ve just written your first JavaScript program! It might not look like much, but a wise person once said that every ninja programmer’s journey begins with a single line of code (or something like that, anyway!).

JavaScript in the Browser

JavaScript is an interpreted language and needs a host environment to run. Because of its origins, the main environment that JavaScript runs in is the browser, although it can be run in other environments; for example, our first program that we just wrote ran in the Node REPL. Node can also be used to run JavaScript on a server. By far the most common use of JavaScript is still to make web pages interactive. Because of this, we should have a look at what makes up a web page before we go any further.

Three Layers of the Web

Nearly all web pages are made up of three key ingredients ― HTML, CSS and JavaScript. HTML is used to mark up the content. CSS is the presentation layer, and JavaScript adds the interactivity.

Each layer builds on the last. A web page should be able to function with just the HTML layer ― in fact, many websites celebrate “naked day” when they remove the CSS layer from their site. A website using just the HTML layer will be in its purest form and look very old school, but should still be fully functional.

Keep These Layers Separate

It is widely considered best practice to separate the concerns of each layer, so each layer is only responsible for one thing. Putting them altogether can lead to very complicated pages where all of the code is mixed up together in one file, causing “tag soup” or “code spaghetti”. This used to be the standard way of producing a website and there are still plenty of examples on the web that do this.

Unobtrusive JavaScript

When JavaScript was initially used, it was designed to be inserted directly into the HTML code, as can be seen in this example that will display a message when a button is clicked:

<button id='button' href='#' onclick='alert("Hello World")'>Click Me</a>

This made it difficult to see what was happening, as the JavaScript code was mixed up with the HTML. It also meant the code was tightly coupled to the HTML, so any changes in the HTML required the JavaScript code to also be changed to stop it breaking.

It’s possible to keep the JavaScript code away from the rest of the HTML by placing it inside its own <script> tags. The following code will achieve the same result as that above:

<script>
const btn = document.getElementById(’link’)
btn.addEventListener('click', function() {
    alert('Hello World!');
    };
</script>

This is better because all the JavaScript is in one place, between the two script tags, instead of mixed with the HTML tags.

We can go one step further and keep the JavaScript code completely separate from the HTML and CSS in its own file. This can be linked to using the src attribute in the script tag to specify the file to link to:

<script src='main.js'></script>
                

The JavaScript code would then be placed in a file called main.js inside the same directory as the HTML document. This concept of keeping the JavaScript code completely separate is one of the core principles of unobtrusive JavaScript.

In a similar way, the CSS should also be kept in a separate file, so the only code in a web page is the actual HTML with links to the CSS and JavaScript files. This is generally considered best practice and is the approach we’ll be using in the book.

Self-Closing Tags

If you’ve used XML or XHTML, you might have come across self-closing tags such as this script tag:

<script src='main.js' />

These will fail to work in HTML5, so should be avoided.

You may see some legacy code that uses the language attribute:

<script src='main.js' language='javascript'></script>

This is unnecessary in HTML5, but it will still work.

Graceful Degradation and Progressive Enhancement

Graceful degradation is the process of building a website so it works best in a modern browser that uses JavaScript, but still works to a reasonable standard in older browsers, or if JavaScript or some of its features are unavailable. An example of this are programs that are broadcast in high definition (HD) ― they work best on HD televisions but still work on a standard TV; it’s just the picture will be of a lesser quality. The programs will even work on a black-and-white television.

Progressive enhancement is the process of building a web page from the ground up with a base level of functionality, then adding extra enhancements if they are available in the browser. This should feel natural if you follow the principle of three layers, with the JavaScript layer enhancing the web page rather than being an essential element that the page cannot exist without. An example might be the phone companies who offer a basic level of phone calls, but provide extra services such as call-waiting and caller ID if your telephone supports it.

Whenever you add JavaScript to a web page, you should always think about the approach you want to take. Do you want to start with lots of amazing effects that push the boundaries, then make sure the experience degrades gracefully for those who might not have the latest and greatest browsers? Or do you want to start off building a functional website that works across most browsers, then enhance the experience using JavaScript? The two approaches are similar, but subtly different.

Your Second JavaScript Program

We’re going to finish the chapter with a second JavaScript program that will run in the browser. This example is more complicated than the previous one and includes a lot of concepts that will be covered in later chapters in more depth, so don’t worry if you don’t understand everything at this stage! The idea is to show you what JavaScript is capable of, and introduce some of the important concepts that will be covered in the upcoming chapters.

We’ll follow the practice of unobtrusive JavaScript mentioned earlier and keep our JavaScript code in a separate file. Start by creating a folder called rainbow. Inside that folder create a file called rainbow.html and another called main.js.

Let’s start with the HTML. Open up rainbow.html and enter the following code:

<head>
<meta charset='utf-8'>
<title>I Can Click A Rainbow</title>
</head>
<body>
<button id='button'>click me</button>
<script src='main.js'></script>
</body>
</html>
                

This file is a fairly standard HTML5 page that contains a button with an ID of button. The ID attribute is very useful for JavaScript to use as a hook to access different elements of the page. At the bottom is a script tag that links to our JavaScript file.

Now for the JavaScript. Open up main.js and enter the following code:

const btn = document.getElementById('button');

const rainbow = ['red','orange','yellow','green','blue','rebeccapurple','violet'];

function change() {      
document.body.style.background = rainbow[Math.floor(7*Math.random())];
}
btn.addEventListener('click', change);
                

Our first task in the JavaScript code is to create a variable called btn (we cover variables in Chapter 2).

We then use the document.getElementById function to find the HTML element with the ID of btn (Finding HTML elements is covered in Chapter 6). This is then assigned to the btn variable.

We now create another variable called rainbow. An array containing a list of strings of different colors is then assigned to the rainbow variable (we cover strings and variables in Chapter 2 and arrays in Chapter 3).

Then we create a function called change (we cover functions in Chapter 4). This sets the background color of the body element to one of the colors of the rainbow (changing the style of a page will be covered in Chapter 6). This involves selecting a random number using the built-in Math object (covered in Chapter 5) and selecting the corresponding color from the rainbow array.

Last of all, we create an event handler, which checks for when the button is clicked on. When this happens it calls the change function that we just defined (event handlers are covered in Chapter 7).

Open rainbow.html in your favorite browser and try clicking on the button a few times. If everything is working correctly, the background should change to every color of the rainbow, such as in the screenshot below.

Continue reading %Hello, World! Your First JavaScript Programs%


by Darren Jones via SitePoint

10 Surprising Stats You Didn’t Know About Marketing on LinkedIn #Infographic

"People spend time on other networks, but they invest time on LinkedIn" That’s a pretty good line – LinkedIn’s included this in their latest infographic, which provides an overview of some key stats and data around the platform’s marketing options and opportunities, underlining why...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

Integrated 2017

Brutalist One Pager featuring a fun spray can cursor effect for the upcoming Integrated art & design conference.

Full Review | Direct Link


by Rob Hope @robhope via One Page Love

The “Most Loved” One Page Websites from September 2017

one-page-love-hosting-reviews-bh-unlimited

This "Most Loved" One Page website round-up is brought to you by hosting provider, Bluehost.

Bluehost is the most affordable hosting option to host your One Page websites. They have an incredible $2.95/month deal exclusive to One Page Readers where you can host your website with 50GB diskspace and unlimited bandwidth. They also throw in a free domain!

If you want to get notified about the "Most Loved" awards each month, subscribe to our Inspiration Newsletter.

Below are the 5 One Page websites awarded “Most Loved” in September – hope you enjoy!


Pomorilla (Restaurant)

Impressive One Page website for the Pomorilla Pizzeria in Cupra Marittima, Italy. What a nice touch as you scroll the background morphs into different shapes similar to the dough making process. However the highlight is definitely the menu with lovely illustrations, ingredients filter and a size price switcher 🍕


A Violent Act (Long-Form Journalism)

Seriously impressive engaging One Pager investigating the famous 2003 student murders in Sydney. The long scrolling Singe Page website gives the unique perspective of two people with interactive content switchers. The research is thorough and the design is beautiful featuring tons of gritty textures and subtle animations as you scroll. This is the fifth Most Loved award in a row now for SBS. Respect 👏


SMU Basketball (Landing Page, Sport)

Engaging long-scrolling One Pager celebrating the bright looking future for the SMU Mustangs. The Singe Page site features quality video clips, a spacious arrangement of content and great typography.


Koya Bound (Long-Form Journalism, Photography, Product)

‘Koya Bound’ is a beautiful interactive One Pager and photographic record of Dan Rubin and Craig Mod’s eight days walking on the Japanese pilgrimage path, Kumano Kodo. As you scroll down, the photos correlate with the map to the right, giving more context to the journey. At the bottom they promote the (limited edition) print version of the adventure. A great reference to long-form journalism in a Singe Page website – also promoting a product.


Doggo For Hire (Résumé)

Awesome, fun-filled One Pager forming the digital résumé of a dog named Birch. There is just so much character from dog emoji-preloaders, confetti shower animations as you scroll, hilarious timelines, fun infographics and an even funnier recognition section. Lastly a shout out to the responsive adaption – especially how the confetti animation moves to the background and how the infographic changes to portrait orientation. Bravo 🐶👏


Hope you enjoyed these beautiful One Pagers from September!

Big love to hosting provider Bluehost for sponsoring the round up < 3


by Rob Hope @robhope via One Page Love

10 Questions to Ask When Creating a Social-Media Marketing Plan [video]

Ever heard the saying "Failing to plan is planning to fail?" That old but wise adage often rings true when it comes to social media marketing. Creating a detailed, goal-oriented social-media strategy is just as important as having a rock solid business plan.

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

API Authentication With Node.js

Building APIs is important; however, building secured APIs is also very important. In this tutorial, you learn how to build a secured API in Node.js. The authentication will be handled using tokens. Let's dive in.

Cookies vs. Tokens

Let's talk a little about cookies and tokens, to understand how they work and the differences between them.

Cookie-based authentication keeps an authentication record or session both on the server and the client side. In other words, it is stateful. The server keeps track of an active session in the database, while a cookie is created on the front-end to hold a session identifier.

In token-based authentication, every server request is accompanied by a token which is used by the server to verify the authenticity of the request. The server does not keep a record of which users are logged in. Token-based authentication is stateless.

In this tutorial, you will implement token-based authentication.

Setting Up an Express App

First, create a folder where you will be working from, and initialize npm. You can do so by running:

Use the package.json file I have below. It contains all the dependencies you will be making use of to build this application.

Now you can install the dependencies by running:

You can go grab a cup of coffee as npm does its magic; you'll need it for this ride!

Create a new file called app.js. In this file, you will require some packages and do a bit of setup. Here is how it should look.

  1. This imports all dependencies you installed using NPM. Here you are requiring express, morgan, body-parser, and mongoose. Morgan is an HTTP logger for Node.js. Here, morgan will be used to log HTTP requests to your console. So you see something like this when requests are made: POST /users/signin 401 183.635 ms - -. You also require your routes (which will be created soon) and set it to routes.
  2. Here you are setting mongoose to make use of ES6 promises.
  3. Set up morgan and body-parser middleware. Body-parser makes incoming requests available in your req.body property.
  4. Set up routes. With this, whenever a request is made to /users, the routes file which you required above and set to routes will be used.
  5. You set port to the port of your environment or 3000 and then pass it to the listen function which is called on the app to start up your server. When the server starts, a log is sent to the console to show that the server has started.

It's time to get our model up and running.

Map Out the User Model

Your User model will do a few things:

  1. Create a user schema.
  2. Hash the user password.
  3. Validate the password.

Time to see what that should look like in real code. Create a folder called models, and in the folder create a new file called user.js. The first thing you want to do is require the dependencies you will be making use of.

The dependencies you will need here include mongoose and bcryptjs.

You will need bcryptjs for the hashing of a user password. We will come to that, but for now just require the dependencies like so.

With that out of the way, you want to create your user schema. This is where mongoose comes in handy. Your schema will map to a MongoDB collection, defining how each document within the collection should be shaped. Here is how the schema for your current model should be structured.

In the above, you have just two fields: email and password. You are making both fields a type of String, and requiring them. The email also has an option of unique, as you will not want to different users signing up with the same email, and it is also important that the email is in lowercase.

The next part of your model will handle the hashing of the user password.

The code above makes of bcryptjs to generate a salt. You also use bcryptjs to hash the user password by passing in the user's password and the salt you just generated. The newly hashed password gets stored as the password for the user. The pre hook function ensures this happens before a new record of the user is saved to the database. When the password has been successfully hashed, control is handed to the next middleware using the next() function, else an error is thrown.

Finally, you need to validate user password. This comes in handy when a user wants to sign in, unlike the above which happens for signing up.

In this part, you need to ensure a user who wants to sign in is rightly authenticated. So you create an instance method called isValidPassword(). In this method, you pass in the password the user entered and compare it with the password attributed to that user. The user is found using the email address s/he entered; you will see how this is handled soon. A new error is thrown if one is encountered.

When that is all set and done, it is important you export the file as a module so it can be rightly required.

Up and Running With Passport

Passport provides a simple way to authenticate requests in Node.js. These requests go through what are called strategies. In this tutorial, you will implement two strategies.

Go ahead and create a file called passport.js in your working directory. Here is what mine looks like.

  1. Require dependencies installed using NPM.
  2. Creates a new instance of JwtStrategy. This object receives two important arguments: secretOrKey and jwtFromRequest. The secretOrKey will be the JWT secret key which you will create shortly. jwtFromRequest defines the token that will be sent in the request. In the above, the token will be extracted from the header of the request. Next, you do a validation to look for the right user, and an error gets thrown if the user is not found.
  3. Create a new instance of LocalStrategy. By default, the LocalStrategy uses only the username and password parameters. Since you are making use of email, you have to set the usernameField to email. You use the email to find the user, and when the user is found, the isValidPassword() function which you created in the user model gets called. This method compares the password entered with the one stored in the database. The comparison is done using the bcryptjs compared method. Errors are thrown if any is encountered, else the user is returned.

Before you jump to setting your controllers and routes, you need to create the JWT secret key mentioned above. Create a new folder called config, and a file inside called index.js. You can make the file look like this.

User Controllers

The user controller gets called whenever a request is made to your routes. Here is how it should look.

  1. Require dependencies.
  2. Here you are creating a new token for the user. To create the token, you need to create the payload, which contains the claims. Here you set the issuer, subject, expiration, and issued at. The creation of this token is saved in a function called signToken().
  3. This is the sign-up action that gets called when creating a new user. The email and password are obtained from the body of the request. You need to check if a user with the same email exists, to ensure two users are not signed up with same email address. When that has been verified, the signToken() function gets called with the new user as an argument to create a new token.
  4. This action handles the signing in of users. Here you simply pass in the user who is trying to sign in to the signToken() function that creates a new token.
  5. You are using this function for a secret route that can only be accessed by users who have been authenticated.

Setting Up Routes

Before you create the main routes for your application, you will first create a route helper. Go ahead and create a new folder called helpers, and a file called routeHelpers.js. Here is how it should look.

Here you are validating the body of requests sent by users. This will ensure that users enter the right details when signing up or in. The details to be validated are obtained from req.body.

The routes of your application will take this format.

Save it in routes/users.js. In the above, you are authenticating each request, and then calling the respective controller action.

Now you can start up your server by running:

Open up postman and play around with your newly created API.

Conclusion

You can go further to integrate new features to the API. A simple Book API with CRUD actions with routes that need to be authenticated will do. In the tutorial, you learned how to build a fully fledged authenticated API.

If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available in the Envato marketplace.


by Chinedu Izuchukwu via Envato Tuts+ Code