javascript snippets

Show and Hide (toggle) the Blueprint Grid with a JavaScript

Tagged blueprint, css, blueprintcss, toggle, grid, javascript  Languages javascript

This snippet--which could be improved on--allows you to easily display and hide the BlueprintCSS grid.

Put the following code inside the <head> element:

<style title="grid" type="text/css">
        .container { }
</style>
<script type="text/javascript">
    function toggleGrid() {
        if (!document.styleSheets) return;
    
        var cssTitle     = "grid"
        var selectorName = ".container";
        var cssText      = "background: url('images/grid.png');";
        var css = new Array();
    
        // Find the stylesheet
        for(i = 0; i < document.styleSheets.length; i++)
        {
            var styleSheet = document.styleSheets[i];
            
            if(styleSheet.title == cssTitle) {
                if (document.styleSheets[i].cssRules)
                    css = document.styleSheets[i].cssRules;
                else if (document.styleSheets[i].rules)
                    css = document.styleSheets[i].rules;
                else return;
                
                break;
            }
        }

        // Find the selector
        for (i = 0; i < css.length; i++) {
        
            if ((css[i].selectorText.toLowerCase() == selectorName)) {
                if(css[i].style.cssText == "") {
                    css[i].style.cssText = cssText;
                }
                else {
                    css[i].style.cssText = "";
                }
            }
        }
    }
</script>

Change selectorName or cssText, if needed. Next add the following link, for example, to the footer:

<a href="javascript:toggleGrid();" id="toggle-grid">Show grid</a>

Now when you click the link, the grid will be displayed. Click again to hide it.

Note that this is a simple example of how to change a CSS style sheet dynamically with JavaScript. You can use it to change any selector at runtime.

Disable javascript resizing of Firefox

Tagged resize, firefox, browser, koon muuttaminen, javascript, fã¶nstrets dimensioner  Languages bash

There is absolutely not a single developer in the world who knows what size I like my browser, although many people think they do. To prevent resizing of FF make the following steps.

  1. Open browser preferences
  2. Choose "Content"
  3. Choose "Advanced" on the "Enable javascript" preference
  4. Untick "Move or resize existing windows"

Combining CSS and JavaScript files with PHP to reduce page load time

Tagged css, javascript, combine, php  Languages php

This is a very simple utility class that I created which combines multiple files into one—in contrast to all other PHP scripts I've found elsewhere, which all work badly and are a million lines long, this one is simple to understand and maintain:

<?php
class Files
{
    private static function process($files, $output, $base_dir = '')
    {
        $contents   = '';
        
        # If this is a string then it's a search pattern
        if(is_string($files))
        {
            $files = glob($files);
        }
        
        foreach ($files as $file) 
        {
            $contents .= file_get_contents($base_dir.$file) . "\n\n";
        }
    
        # TODO locking 
        if ($fp = fopen($output, 'wb')) 
        {
            fwrite($fp, $contents);
            fclose($fp);
        }
    
        return $contents;
    }
    
    #
    # Combine all CSS files in the css directory:
    #
    #   echo Files::combine("css/*.css", "css/all.css");
    #
    # Combine only specified files in the given order:
    #
    #   echo Files::combine(array("css/core.css", "css/default.css"), "css/all.css");
    #
    #
    static function combine($files, $output_filename, $base_dir = '')
    {
        # Combine the files
        if(!file_exists($output_filename))
        {
            self::process($files, $output_filename, $base_dir);
        }
    }
}
?>

The call to Files::combine should go in a file that is called on each request. On the first request to this file, the files are combined into one, on subsequent requests nothing is done, the only overhead is a call to file_exists.

Ideally the name of the output filename should contain a version number, so that an updated CSS file is not taken from the browser cache. This can easily be supported by reading the build number from somewhere and appending it to the output filename:

Files::combine("css/*.css", "css/all-v$version.css");

Now all you have to do is add this to your HTML:

<link rel="stylesheet" type="text/css" href="/css/all-v<?php echo $version ?>.css" media="screen" />

This also works for JavaScript files. Note that I don't make an effort to minify anything as GZIP usually does a great job at minimizing bandwidth costs.

Opening a new window in the center of the screen with JavaScript

Tagged javascript, window, open, center, screen  Languages javascript

This JavaScript code will open a URL in a new window and center the window on the screen, instead of showing the window in a random place:

var url = 'http://google.com/';
var width  = 640;
var height = 480;
   
var left   = (screen.width / 2) - (width / 2);
var top    = (screen.height / 2) - (height / 2);
   
var xWindow = window.open(url, 'post', 'resizable=1,width=' + width + ',height=' + height + ', top=' + top + ', left=' + left);

xWindow.focus();

How to use jQuery with Rails 2.0 - aka How to fix "ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)"

Tagged authenticity, rails, rails 2, token, jquery, javascript, ajax  Languages ruby

This is a slight variation of Henrik Nyh's code, which fixes an issue with IE6 that makes all Ajax requests use POST in IE6.

In application.html.erb, or whatever layout file you're using, put:

<%= javascript_tag "window.AUTH_TOKEN = '#{form_authenticity_token}';" %>

In application.js, or whatever JavaScript file you're using, put:

$(document).ajaxSend(function(event, request, settings) {
  if (typeof(window.AUTH_TOKEN) == "undefined") return;
  // IE6 fix for http://dev.jquery.com/ticket/3155
  if (settings.type == 'GET' || settings.type == 'get') return;

  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);
});

That's all...

Simple JavaScript countdown timer

Tagged countdown, timer, javascript  Languages javascript

This JavaScript displays the days, hours, minutes and seconds left to the given date:

function Countdown(then) {

    this.then = then;
    
    function setElement(id, value) {
        if (value.length < 2) {
            value = "0" + value;
        }
    
        window.document.getElementById(id).innerHTML = value;
    }
    
    function countdown() {
        now           = new Date();
        diff          = new Date(this.then - now);
        
        seconds_left  = Math.floor(diff.valueOf() / 1000);
    
        seconds  = Math.floor(seconds_left / 1) % 60;
        minutes  = Math.floor(seconds_left / 60) % 60;
        hours    = Math.floor(seconds_left / 3600) % 24;
        days     = Math.floor(seconds_left / 86400) % 86400;
        
        setElement('countdown-days', days);
        setElement('countdown-hours', hours);
        setElement('countdown-minutes', minutes);
        setElement('countdown-seconds', seconds);
        
        countdown.timer = setTimeout(countdown, 1000);
    }
    
        
    function start() {
        this.timer = setTimeout(countdown, 1000);
    }
    
    start(then);    
}

Countdown(new Date("Dec 04 2008 12:00:00"));

Required HTML:

<span id="countdown-days"></span> days

<span id="countdown-hours"></span>:<span id="countdown-minutes"></span>:<span id="countdown-seconds"></span>

Output is for example:

23 days 23:00:12

How to warn a user when he's leaving and there's unsaved data

Tagged javascript, onbeforeunload, unload  Languages javascript
function confirmExit(enabled) {
  window.onbeforeunload = (enabled) ? onUnloadMessage : null;
}

function onUnloadMessage() {
  return "You're about to leave without saving!";
}

// Enable
$('.input').change(function() {
  confirmExit(true);
});