FREEBIE FRIDAY! Manipulate divs dynamically and proportionally with Javascript.

What is it?

This is a script I’ve written to dynamically manipulate divs according to viewport height. Any property that can be set with a pixel value can be manipulated, e.g. height, margin, line-height or background-position, just to name a few. It has been tested in Internet Explorer 10, Firefox 24.0, Chrome 30, Opera 12.16 and Safari 5.1.7. It works great with my imgResize script and is available for free use, private or otherwise.

How to implement it

HTML markup and CSS styling

The first thing you need to do to make the script communicate with the divs on your webpage is to name those divs. In your HTML markup add an id to each div that will be manipulated. It should look something like this:

<div id=”div1“>

So far so good. The next step is to declare what properties of the div will be manipulated and by how much. This will actually be done in your CSS styling. For example:

#div1:before {
    content: ‘height .04900‘;
    display: none;
}

The parts in bold can be edited; everything else should be left alone. #div1 could well have a different name, for example. The important thing is that it references the div to be resized; this example correctly references the HTML markup example above it. In this example height is the property to be manipulated and .04900 the percentage value, i.e. 4.9%. The value must contain 5 digits. If the property name contains a dash, it should be written in camel case instead. For example, the CSS property “background-position” should be written as “backgroundPosition.”

In summary the combination of this HTML markup and this CSS styling, when correctly coupled with divManipulate.js would result in #div1 always taking up 4.9% of the viewport’s vertical space.

It is possible to manipulate up to two different properties for each div. For example, if we wanted #div1 to not only take up 4.9% of the viewport’s height, but also maintain a top margin of 1% of the viewport’s height, the complete code would look like this:

#div1:before {
    content: ‘height .04900‘;
    display: none;
}

#div1:after {
    content: ‘margin-top .01000‘;
    display: none;
}

Notice the keyword “after” following #div1: – when a div has two properties to be changed, the second should always use the keyword “after.”

Customizing the script

Upon opening divManipulate.js take a look at line 5. This is where you can enter the names of the divs to be resized. The names refer to the ids assigned to each div.

Inserting the script on your webpage

We want the script to execute automatically on page load so the user is immediately presented with a page tailor-made for the current size of his or her browser. We also want it to execute on page resize for real-time adaptation upon browser resize. To achieve these objectives we will be calling the script using the following code:

window.onload = function() {
    divManipulate();
};

window.onresize = function() {
    divManipulate();
};

We can place the above in the file containing the HTML (enclosed by <script> tags) or in its own .js file. Just make sure this code comes after the divManipulate.js script itself — we can only instruct it to call something it already knows about! It’s also important to note that divManipulate.js should come after any CSS styling.

Implementing it, summarized

  • In the HTML markup add an id to every div that will be manipulated.
  • For each div, declare the properties to be manipulated and by how much. If manipulating more than one property per div remember to use the keyword “before” for the first and “after” for the second. Remember also that the value should contain 5 digits.
  • Edit line 5 of divManipulate.js – div id names.
  • Use the following order inside the HEAD tags in your HTML markup:
    1. CSS styling
    2. divManipulate.js
    3. window.onload = function() {
          divManipulate();
      };
      window.onresize = function() {
           divManipulate();
      };

Download

https://www.dropbox.com/s/snc32twm2lcql2p/divManipulate.zip

FREEBIE FRIDAY! Resize images dynamically and proportionally with Javascript.

What is it and how does it work?

Here is a script I’ve created to resize images according to viewport height. It has been tested in Internet Explorer 10, Firefox 24.0, Chrome 30, Opera 12.16 and Safari 5.1.7. I’m making it available for free use, private or otherwise. Just download it from the link at the bottom of this post.

I originally created this to ensure that my layout would adapt itself to different screen resolutions. For example, I wanted an image that takes up 50% of the screen’s height on a 2560×1440 resolution to still take up 50% of the screen’s height on a 1280×720 resolution. Without this script the image would take up 100% of the screen’s height when the page is viewed on a display with 1280×720 resolution.

Eventually I realized that the script would be more effective if it resized images based not on screen resolution, but on viewport height. So I re-designed it to take into account OS and browser bars at the top and bottom of the screen — e.g. Windows taskbar, Mac dock/menu bars, browser toolbars and status bars. The result is that images will be shrunken accordingly when those are present. Bars at the left and right edges of the screen/browser are not taken into account, just as resizing the browser window horizontally does not affect image size: this script is only designed to resize images according to the viewport height.

Having the script do its thing based on viewport size rather than resolution also opened up another possibility: real-time adaptation upon browser resize. This is true fluid design. A script based solely on screen resolution will run on page load and stop there, but one based on browser window/viewport can be fluid since the window/viewport can always be resized, at least on a regular desktop or laptop computer.

How to implement it

Creating the images

Images should be designed on a canvas with the same dimensions as your chosen maximum resolution. This will ensure that they will scale down proportionally to take up the same percentage of a browser’s viewport as it does on the canvas. For example, if we wanted to design a webpage for a maximum resolution of 2560×1440 we should create our images on a canvas of those exact dimensions (e.g. create a new Photoshop file that is 2560×1440). And if we wanted a particular image to always take up 20% of the viewport’s height we should make it take up 20% of the canvas’s height (288px in this case).

Customizing the script

After deciding on a maximum resolution for your layout, the script is ready to be customized. Upon opening imgResize.js take a look at lines 4 and 5. It’s pretty self-explanatory: on line 4 the names of the image files to be resized can be entered and on line 5 the maximum resolution for which they were designed. It may sound counter-intuitive but you can actually increase these values down the line if you change your mind and decide that the images are too large. However, don’t decrease the values or the image will be displayed larger than their native sizes at the original maximum resolution — in other words, there will be a loss of quality.

Last steps

In your HTML markup add an id to each image that will be resized. It should look something like this:

<img src=”image1.jpg” id=”image1“>

Notice that the id name is the same as the image name, minus the extension. This is very important, otherwise the code will not work.

Finally add the following lines in your CSS styling:

#image1, #image2, #image3 {
    display: none;
}

Of course this is just an example; #image1, #image2, and #image3 could well have different names. The important thing is that they reference the images to be resized. What this step does is hide the images until the resizing script has run. This prevents them from “flashing” in their native dimensions before being resized. It’s not crucial to the functionality of the script but it adds a professional touch to the whole thing.

Inserting the script on your webpage

We want the script to execute automatically on page load so the user is immediately presented with a page tailor-made for the current size of his or her browser. We also want it to execute on page resize for real-time adaptation upon browser resize. To achieve these objectives we will be calling the script using the following code:

window.onload = function() {
    imgResize();
};

window.onresize = function() {
    imgResize();
};

We can place the above in the file containing the HTML (enclosed by <script> tags) or in its own .js file. Just make sure this code comes after the imgResize.js script itself — we can only instruct it to call something it already knows about! It’s also important to note that imgResize.js should come after any CSS styling.

Implementing it, summarized

  • Create images in a canvas of the same size as the maximum resolution for which the webpage will be optimized.
  • Edit lines 4 and 5 of imgResize.js – image file names and maximum resolution.
  • In the HTML markup add an id to every image that will be resized. Each id should have the same name as the image file it represents.
  • Style each id with display: none; in your CSS styling.
  • Use the following order inside the HEAD tags in your HTML markup:
    1. CSS styling
    2. imgResize.js
    3. window.onload = function() {    
          imgResize();
      };
      window.onresize = function() {    
          imgResize();
      };

Download

https://www.dropbox.com/s/h08851b0yb586ou/imgResize.zip

Optimizing webpages for mobile devices, part 2: CSS media queries, Javascript and mobile-specific websites

In part 1 of this article we went over the viewport meta tag. Although it can be useful in certain circumstances I feel that it is often unecessary. What’s worse, it’s hard to predict how it will behave on different browsers and it can in fact ruin some users’ experiences if not used very carefully.

If you really want your webpage to be able to transform itself to suit mobiles, as well as various other types of devices and specific features, you can  add special CSS rules that will automatically be applied to suit the situation. This can be done either with media queries or Javascript.

Lastly, if you prefer to create a completely separate webpage for mobile devices, you’re covered there too.  Mobile-specific websites are very popular and definitely worth considering as part of your strategy.

Media Queries

Media queries have become a very popular way of optimizing webpages for mobile devices since their introduction with the advent of CSS3. They work by telling a browser to apply special CSS rules depending on the type of device a webpage is accessed from and what media features it has. As you might have inferred from the previous sentence media queries, unlike the viewport meta tag, influence not only mobile devices, but also “regular” computers (heron referred to as “desktops”), printers, and anything else that can display the webpage.

Media queries can, for example, tell a browser to use a specific stylesheet for a webpage when it detects that it is being accessed from the “printer” media type (this happens when the browser is told to print the page). That stylesheet could remove ads and background images, for instance.

Below is an example of a media query that displays a webpage’s background in different colors depending on the “width” feature. This feature corresponds to the width of the browser window.

Media queries

As with “normal” CSS, media queries can be defined in several ways. However unlike regular CSS selectors, media queries cannot be defined inline in an HTML tag. The ways in which we can refer to media queries are:

  • From inside the document in which they will be used. As shown below, the code should be enclosed by the <style> tags, which in turn are enclosed by the <head> tags.

<head>
     <style type=”text/css”>
@media screen and (max-width: 480px) {
selector { property: value; }
}
     </style>
</head>

While the page has a maximum width of 480 pixels it will follow the rules inside the bracketes (selector { property: value; })

  • From an external stylesheet by importing said stylesheet into the document in which it will be used using the <style> tags. Again, the code should be enclosed by the <style> tags, which in turn are enclosed by the <head> tags. 
    • @import rules must always be placed before any other CSS content, including comments. They are not supported by really, really old browsers.

<head>
<style type=”text/css”>
          @import “480pxRules.css” screen and (max-width:        480px);
</style>
</head>

While the page has a maximum width of 480 pixels it will follow the rules defined in “480pxRules.css.”

  • From an external stylesheet by importing a stylesheet into the document in the “regular” manner using the <link> tag enclosed by the <head> tags. With this method media queries will be handled by the imported stylesheet instead of the document. The imported stylesheet can contain any combination of the two methods above (the parts which are in bold), and of course regular CSS.  Two things to note:
    • Remember that @import rules must be placed before any other CSS content and are not supported by very old browsers.
    • Rules of selectors that appear more than once are always overriden by the last definition. This means that media queries should always appear after all other CSS.
    • As a result of the above two rules any CSS imported into a document must not contain selectors that are repeated in said document or later import.

<head>
<link rel=”stylesheet” type=”text/css” media=”screen” href=”style.css” />
</head>

This is a usual stylesheet import. Testing for page width and applying the corresponding CSS rules is done either in “style.css” or in other stylesheets imported into “style.css.”

  • From an external stylesheet by importing said stylesheet into the document in which it will be used using the <link> tag. The code should be enclosed by the <head> tags.

<head>
     <link rel=”stylesheet” type=”text/css”      href=”480pxRules.css” media=”screen and (max-width: 480px)” />
</head>

While the page has a maximum width of 480 pixels it will follow the rules defined in “480pxRules.css.”

Although the different ways of referring to media queries might cause some confusion due to their different syntaxes, the overall “template” should make sense to anyone well versed in CSS. In any case, it’s just a matter of deciding which method to call the queries with and sticking to that general template while modifying media types and detectable media features to suit the situation. These variables are defined as such:

  • Media types: used to specify which type(s) of media the CSS rules will apply to. For example, in the examples above I have used the “screen” media type, which was primarily meant for color computer screens. However this media type also targets most smartphones nowadays, despite the fact that there also exists a “handheld” media type. If you don’t care about old “handheld” devices it’s enough to set your media type to “screen.” If you want to be safe, set it to “screen, handheld.” By leaving out media types entirely the CSS rules you define will apply to all media types. Here is W3C’s guide to media types and an article on the doomed “handheld” media typePro tip: instead of driving yourself crazy with 10 different stylesheets for each media type, focus on “screen” and possibly “print,” which are the two most used and useful media types.
  • Detectable media features: the most important part of media queries, these are the conditions we can screen for. “Max-width” and “min-width” are the most useful for our purposes; possibly also “orientation.” As with the viewport meta tag, each “width” variant has different uses when optimizing for mobile devices, but since media queries also apply to desktops, you will probably want to avoid the ones which refer to device-width, which always returns the resolution of the device. That’s fine for mobile devices since the browser usually takes up the entire screen space but if the user is on a desktop  it will return that device’s resolution regardless of the current window size. On the other hand “width,” “min-width” and “max-width” always return the width of the browser window.1

There is actually one last component that is very important. Don’t worry, it’s an easy one:

  • Logical operators: allows screening for both media type and multiple media features using the notand, and only operators. For example, “min-width” and “max-width” can be used together to specify that the CSS rules are only to be used when the window is between two different widths:

<head>
<link rel=”stylesheet” type=”text/css” href=”480to900pxRules.css” media=”screen and (min-width: 480px) and (max-width: 900px)” />
</head>

1 Media queries that refer to device-width are relevant if you actually want mobile devices to use different CSS rules than desktops. My HTC Desire has a resolution of 480px, which is the most common resolution for smartphones. CSS rules set for “max-device-width: 480px” will affect my Desire and most other smartphones. Desktop browsers would not be affected by these rules unless the actual screen monitor was 480 pixels wide, an uncommon sight to say the least. 

Javascript

Media queries are not the only way of specifying CSS rules based on different media types or features. Basically by using Javascript to get a desired value (width, for example) and then feeding them it into a specific function we can assign different CSS rules to differently sized windows and devices. That’s beyond the scope of this article, but Particletree wrote a very good article about it over 7 years ago! It is definitely worthy of consideration. With that thought, following are the pros and cons of both media queries and Javascript. I can’t recommend one or the other; read about both and pick what’s right for you!

Advantages of CSS media queries

  • Do not require Javascript to be enabled in the user’s browser.
  • Browsers that support CSS2 and CSS3 all interpret detection of media features and media types in the same way.

Disadvantages of CSS media queries

  • Detectable media features are CSS3, which means older browsers may not support them (media types were introduced in CSS2 so they have wider browser support).
  • As Rob Glazebrook pointed out in his article Using the CSS @import Rule Internet Explorer versions 4-7 cannot handle media types correctly. Still no confirmation if they work on IE8. Leave a comment if you’ve got the answer!
  • All CSS is loaded upon page load even if the conditions on which it depends are never met.

Advantages of Javascript

  • Older browsers that do not support CSS2 media types or CSS3 detectable media features can handle all of that through Javascript.
  • Allows checking for media types and features before loading the corresponding CSS files (assuming that CSS is not defined in the same document). This keeps unecessary CSS files from loading, but the Javascript itself slows down page loading. The conclusion is that this point is only relevant when every second counts, and then only if the amount of CSS to load for different situations is large enough that it pays off having the extra Javascript.

Disadvantages of Javascript

  • Users must have Javascript enabled in their browser.
  • Different browsers detect media features using different object/property combinations. According to Craig Buckler at Sitepoint “all the main browsers support document.documentElement.clientWidth anddocument.documentElement.clientHeight but it’s inconsistent. Either the window or document dimensions will be returned depending on the browser and mode.”
  • When the amount of special CSS rules is small, the extra Javascript doesn’t pay off with regards to page load times.

Mobile-specific websites

Because of the huge potential media queries and Javascript have in allowing you to control how your webpages are displayed under different circumstances, I would recommend getting familiar with and making use of them. At the same time it can be easy to get overwhelmed by the amount of possibilities. That’s never good, so if your aim is simply to create a good mobile experience to match what you’ve created for desktop users, a mobile-specific website just might be the answer.

As you might have guessed a mobile-specific website is completely separate from the main website, although it is usually a sub-domain of that site (for example, m.yourdomain.com). Everytime someone visits the main domain name (yourdomain.com), a function runs and checks what kind of device it’s being accessed from and then re-directs them to the appropriate site.

The code which checks the device type can be written in a variety of languages. Javascript is popular for this application but if your server supports a server-side language I would recommend that to ensure that it will work for all users. If you don’t want to write your own code I’ve come across a very nice solution called WURFL. What’s awesome about it is that it uses a “repository” (wurfl.xml), which contains the definitions of thousands of devices, and is constantly being updated. On their website it is stated that “WURFL is deployed by key Internet companies such as Facebook and Google” so I can’t imagine that there is a more effective way to do device detection, but I haven’t actually tried it myself. There are APIs available in several programming languages or you could write your own and just use their wurfl.xml file.

Conclusion

The viewport meta tag, media queries, Javascript, and mobile-specific websites — and that’s not to mention good design sense! With so many options and a growing number of users accessing webpages through iPhones, Android phones, tablets and other mobile devices there is no excuse not to give your visitors a great experience everytime.

Combining HTML, Javascript, and PHP

Surfing around today I came across the topic of combining different scripting languages in web design. Let’s keep this simple and talk only about HTML, Javascript, and PHP.

HTML, Javascript, and PHP:

  • HTML: not actually a scripting language, but a markup language. HTML is a client-side technology.
  • Javascript: a client-side scripting language.
  • PHP:server-side scripting language.

Client-side vs. server-side:

  • Client-side: the code you write is executed by the user’s web browser. That means if the user has Javascript disabled, for example, s/he won’t get that awesome Javascript experience you created.
  • Server-side: the code you write is executed by your server, which is probably in Utah or something, and you probably don’t have access to it. That means that if you have any PHP code on your page, it will work for all of your visitors as long as the server hosting your site has PHP installed. Most of them do, but if your code is not working maybe you should get in touch with your hosting provider. Server-side scripts are executed before they are sent to the client-side. Keep that in mind.

Alright, now that’s out of the way let’s get to the meat and potatoes of this!  You can actually create HTML (.htm, .html), Javascript (.js), and PHP (.php) files. Each one will of course support code written in its respective namesake, but some will also support other codes. So here’s another list for you, to make it easy (or maybe confuse you more):

  • HTML (.htm, .html) files: in here you can write both HTML and Javascript scripts, no problem! The user’s browser will read everything at the same time. To begin writing in Javascript, make sure to open the code with <script type=”text/javascript”> and close it with, you guessed it </script>. Normally you cannot have PHP code in an HTML file. There are ways if you google around, but if you know you’re gonna be using PHP code, it’s much better to do it in a .php file.
  • Javascript (.js) files: sorry, but you can only write Javascript code in here and if you open it with a browser it will just show you a bunch of code. So what’s it good for? Well, here you can write scripts that you want to use on multiple pages. Reference this file from the HTML or PHP file which actually contains all your content.
  • PHP  (.php) files: inside PHP files you can have it all! HTML, Javascript, and PHP, everything will work. In fact you can think of a .php file as a sort of beefed-up .html file. That is, if you’re using .php files as your main site files (where all the content is), it will work just like a .html file in regards to how you write your HTML and javascript: even though the extension is .php, that doesn’t mean you have to embed the HTML or anything like that. Just write your code as if it was a plain ol’ .html file. Again, Javascript code has to be inside the Javascript script tags. It is actually only if you wanted to use PHP that you would have to embed it first by using <?php in front of the code and ?> at the end. The cool thing about it is that you can place this PHP code anywhere, even inside HTML tags or within Javascript scripts, but always remember that PHP is server-side so it is executed before Javascript. That means by the time the Javascript comes around all it finds is the plain text resulting from the PHP execution.

Alright, let’s look at some examples of combining PHP, HTML, and Javascript:

PHP embeded in HTML (in a .php page)

<form>
      <?php $name = “Enter name”; ?>
      <input type=”text” value=”<?php echo $name ?>“>
</form>

The example above is written in a .php file. Everything in bold is PHP and everything else is plain HTML. The result will be an input box with “Enter name” pre-written into it.

PHP EMBEDED IN JAVASCRIPT (in a .php page)

<script type=”text/javascript”>
function bacon() {
alert(“This was written in Javascript”);
alert(“<?php echo “This was written in PHP”; ?>“);
}

bacon();
</script>

Again, in the example above the PHP is in bold. Everything else within the <script> tags is Javascript. The result will be two popups on page load: “This was written in Javascript”, followed by “This was written in PHP”.

So now you can see that PHP can be embeded anywhere within a PHP file. But be careful combining Javascript and PHP. Again, remember that since PHP is server-side it will be executed first. That means by the time the Javascript comes around all it finds is the plain text resulting from the PHP execution.

JAVASCRIPT EMBEDED IN PHP (in a .php page)

<?php
     echo ‘<script type=”text/javascript”>; alert(“hey”); </script>
?>

The example above shows how to embed Javascript within PHP. Again, the PHP code is in bold. To embed Javascript in HTML, we use echo and then insert everything inside quotes. I used single quotes here and then double quotes inside the Javascript code, wherever it was necessary. I could also switch those single and double quotes around if I wanted. If I wanted to embed HTML in PHP I would follow the same procedure:

HTML EMBED IN PHP (in a .php page)

<?php
     echo ‘<a href=”http://frugihoyi.wordpress.com/”>my website</a>‘;
?>

That would output “my website“. The PHP code was in bold.

And that’s about it. I’ve already explained above how to embed Javascript in an HTML page. It’s pretty straight forward and if you know Javascript, you should know that already. As opposed to PHP you cannot have Javascript code actually INSIDE of an HTML tag, like in our first example, but you can of course use Javascript commands like onClick and onHover. As for embedding HTML within Javascript code, I can give you a last example.

HTML EMBEDED IN JAVASCRIPT

<script type=”text/javascript”>
document.write(“<font color=’red’>textextext</font>”);
</script>

The above will of course output textextext in red.

Well this turned out much longer than I expected, but I hope it was informative. I’m not sure what the next topic will be, but maybe AJAX so stay tuned!