Simple Parallax effect tutorial using Javascript

Parallax Effect is quite a beautiful trick that you can put on to your website to showcase your products or content in a very cool way. Confused lets see an example #1 this is how you can view the content but obviously its the advance way of doing it . So I’ll be doing in a more simpler way but the concept will be same .

Concept

So parallax is basically a combination of two new fashion of web design workflow one is Single Page design and the other is parallax scrolling . Single Page design means every thing in one page where as parallax scrolling means that as you scroll the page its background image moves slower than the speed at which you scroll .

Lets see some code

I started with using a simple HTML document page with style containing below code


<style>
*{
margin:0;
padding:0;
}

#image{
position: relative;
z-index: -1;
}

#content{
height:750px;
width:100%;
margin-top: -10px;
background-color:#4c4c4c;   //grey color
position: relative;
z-index:1;
}</style>

and in the body part
<body>
<img id="image" src="ime.jpg" height="710px" width="100%">
<div id="content"></div>
</body>

where ime.jpg is my image file. and content is a div ID selector that is basically the grey color background to show you the effect .Now the javascript code add it inside the head below the style close tag . As you know js should be written inside the script tag here’s the code .

<script type="text/javascript">
var ypos,image;
function parallax(){
ypos=window.pageYOffset;
image=document.getElementById('image');
image.style.top= ypos * .6 + 'px';
}
window.addEventListener('scroll', parallax);
</script>

So we have created a function called parallax() the first line inside the function gives the Y axis offset means the scroll location at y-axis , second line gets the element by using the id selector from the html body ie image and the third line does the actual changes to the top of the image element in the document . and the last line ie the window.addEventListener which basically calls the function parallex and has a type ‘scroll’.

Lets play with it , change the .6 value to .2 or .1 but not more than 1 and see the changes . If you saw the changes then you have successfully completed the tutorial . feel free to comment down below.

Boxify Deconstructed #1

Before starting you should check out my previous post on what are the essential things that you need before starting a website or any front end dev ie Designing . Since we have a Mock site Boxify it’s just that you need to download so that you get a kickstart .

First thing first you need a foundation for that we will be using the basic Boilerplate model you can download it from github.

boxify deconstructed

This is what it looks like after applying the boilerplate content ie the index.html file in the boilerplate folder . including the you need to add some other ingredients to add a nice flavor to it . lets see the changes

boxify deconstructed after change

You can see that we have made some additions to our old file like JS and some CSS(bottom and above resp). these are the changes .Have a look at their official websites .

1# Modenizr

2# Bootstrap

3# Jquery FancyBox

4# Flickity

5# Animate.css

6# font-awesome

7# Boilerplate

How to do Vertical Centering using CSS

One problem that many of us face in the world of CSS is how to put an element at the center of the page . One way to do it using Positioning and by applying top and left , In theory it’s easy to understand but in practical takes much time , space and css file size increases which in turn decreases the performance ( Again we need to minify it ) .

Method which i use is Flex .It is the value of Display property .The main idea behind the flex layout is to give the container the ability to alter its items’ width/height (and order) to best fill the available space (mostly to accommodate to all kind of display devices and screen sizes). A flex container expands items to fill available free space, or shrinks them to prevent overflow.


<html>
<head>
<meta charset="UTF-8">
<title> nothing</title>
<style>
*{
box-sizing: border-box;
}
.container{
height: 900px;
display:flex;
background: #fff;
border:3px dotted #ccc;
}
.box{
background: #F24B6A;
width:400px;
height: 300px;
margin: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
</div>
</div>
</body>
</html>

The thing that does the magic is the display:flex in the container and the margin:auto in the box present in the style inside the head . Another way is to use just two lines(assuming flex-direction:row).


.container{
display:flex;
justify-contents:space-around;
align-items:center;
}

 

There are many ways to do it . If you want to play with it you can visit the sites.

Why we need to compress or minify CSS and Js?

Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times. When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab). In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced. Two popular tools for minifying JavaScript code are JSMin and YUI Compressor. The YUI compressor can also minify CSS.

Obfuscation is an alternative optimization that can be applied to source code. It’s more complex than minification and thus more likely to generate bugs as a result of the obfuscation step itself. In a survey of ten top U.S. web sites, minification achieved a 21% size reduction versus 25% for obfuscation. Although obfuscation has a higher size reduction, minifying JavaScript is less risky.

In addition to minifying external scripts and styles, inlined <script> and <style> blocks can and should also be minified. Even if you gzip your scripts and styles, minifying them will still reduce the size by 5% or more. As the use and size of JavaScript and CSS increases, so will the savings gained by minifying your code.

Here are the top 3 online CSS compressor

1# CSS compressor

2# CSS minifier

3# Grunt Js  here is the tutorial to learn how to minify your css and js .

Why we need to put stylesheets at the top inside the head tag ?

Stylesheets are basically used to beautify HTML page . it contains many elements cascaded with properties and values . If you are developing a website then you might know the fact that bootstrap contains thousands of rules which are available both in the minified as well as unCompressed .Since it is an external Stylesheet we can use it in any html page . But here the problem is whether to put the CSS link at the top or not . According to yahoo Developers its good to attach it at the top inside the head tag which will increase the performance and also not cause any flash of unstyled content (FOUC) and allows the page to render progressively. When the browsers renders it progressively ie from top to bottom it also improves the user experience .

The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change. The user is stuck viewing a blank white page.

Flash of Unstyled Content occurs when your bandwidth is low and the browser is slow to render all the styles from the server which will appear as if there were no styles applied to the webpage for a second then after it renders it’ll be back to normal .

Even the HTML specification or W3C states that the styles should be put at the top of the document .The optimal solution is to follow the HTML specification and load your stylesheets in the document HEAD.

Material Design by Google

With the L developer Preview Google has made a great entry in the field of Design and sleek animations by changing the meaning of each element with the shadow . Basically every object works in a 3D space model with x, y and z axis and each object has a light and shadow with which virtual lights illuminate the scene and allow objects to cast shadows.

Thus Material Design is quite a niche move by google . but the developers wanted more than this , with the CSS frameworks in rise like Bootstrap, Foundation etc, Material design also became a CSS framework that is available online for free. Lets start Materializing your Website .

You can also get the latest release using bower. this release contains source files as well as the compiled CSS and JavaScript files.

bower install materialize

whatismaterial_environment_shadow1 whatismaterial_environment_shadow2 whatismaterial_environment_shadow3 whatismaterial_materialproperties_physicalproperties_thickness_01_yes

How to calculate the specificity in CSS

In CSS , we can apply 2 or more css rules to a single element ,so there may be a situation were there may be one selectors but different types ( id and class ) for example:

HTML#1

<div class="foo">
....
</div>

HTML #2

<div id="foo">
....
</div>

CSS

.foo{
color:blue;
}

#foo{
color:pink;
}

Here the type of selectors are different but the selector names are the same ie : foo and also effects same property ie color . Now the problem is which selector will have the highest priority or specificity . according to the above example its id .

In order to calculate the specificity of an element we need to remember 3 rules .

  1. Specificity of a type selector is 0-0-1
  2. Class selector is 0-1-0
  3. Id selector is 1-0-0

Things you should do before writing CSS

From many years developers were using the same old tricks to get all the values to normal that are by default set by the browser , since every browser have different DOM implementation thus providing different and abnormal properties after applying the CSS . so here are the few things you should take care before writing CSS.

First Normalize it ,

  • Preserves useful defaults, unlike many CSS resets.
  • Normalizes styles for a wide range of elements.
  • Corrects bugs and common browser inconsistencies.

For example by default chrome gives the body element some margin value when it is created in the DOM so inorder to have a proper functionality of page.we need to initialize the body element with margin:0

body{
margin:0;
}

There are several CSS resets that you can link with your HTML page .

#Eric Meyer CSS reset code : One of the most downloaded and applied code .

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}

Similarly there is normalize.css you can get the code form github.com .

How to use different fonts in CSS

Three ways standard , at-rules or by using javascript .

Standard way is by adding the css rule in the head section of your HTML file

<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

at-rules:

Let’s start with the simple @import rule. This is used to bolt another stylesheet onto your existing one.

@import url(http://fonts.googleapis.com/css?family=Open+Sans);

@font-face

@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

with the @font-face rule you can mention the name of the font whatever you like .

let’s see how to use @font-face

@font-face {
font-family: "flip side fonts";
src: url(flipsidefonts.woff);
}

What this does is create a font named “flip side fonts” using the font-family descriptor and links the font file “flipsidefonts.woff” to that name using the src descriptor. “flip side fonts” can then be used in a standard font rule, such as:

p { font-family: "flip side fonts", arial, sans-serif; }

The font will be downloaded (in this case from the same directory as the CSS file) and applied to paragraphs.

And because a font file might contain a whole host of weights or styles, you might also want to specify which one you’re interested in. So the @font-face rule could end up looking something like this:

@font-face {
font-family: "flip side fonts";
src: local("flip side fonts"), local(flipsidefonts), url(flipsidefonts.woff);
font-weight: 400;
font-style: normal;
}

JavaScript implementation

<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Open+Sans::latin' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})(); </script>

you can use free fonts (see the licence before use ) . some of the sites are

fontsquirrel , Google fonts , dafont , 1001freefonts