javascript

Solving "Internet Explorer cannot open the Internet site http://xyz.com. Operation aborted."

Tagged ie6, ie7, bug, ajax, prototype, scriptaculous  Languages javascript

This bug exists in IE6 and IE7 and is caused by a JavaScript that tries to modify a tag that hasn't been closed (yet).

For example this one:

<div id="x">
  <script type="text/javascript">
  $('x').replace("wrong");
  </script>
</div>

This example fixes the problem, because the script is defined after the tag that it tries to modify:

<div id="x">
</div>
<script type="text/javascript">
  $('x').replace("correct");
</script>

See BUG: Error message when you visit a Web page or interact with a Web application in Internet Explorer: 'Operation aborted' for a detailed explanation of the problem.

Opening a new tab with Firefox

Tagged open, tab, firefox  Languages javascript

Note that this only works from a Firefox extension:

function openTab(url, focus) 
  {
    var tab = getBrowser().addTab(url);

    if(focus)
    {
      getBrowser().selectedTab = tab;
    }
   
    return tab;
  }

How to track user actions and custom events with Google Analytics and jQuery

Tagged jquery, google, analytics, track, click  Languages javascript

This is a customization of Rebecca Murphey's script:

$('a').each(function() {
    var $a = $(this);
    var href = $a.attr('href');
    
    if(typeof pageTracker == 'undefined') { return; }

    // Link is external
    if (href.match(/^http/) && !href.match(document.domain)) {
        $a.click(function() {
            pageTracker._trackPageview('/external/' + href);
        });
    } else {
        $a.click(function() {
            pageTracker._trackPageview('/internal' + href);
        });
    }
});

Note that clicks are shown as page views in reports, so you should exclude them from all reports. A future version of Google Analytics will allow you to track events, such as mouse clicks, without affecting page view reporting, see this page on the new event tracking beta feature for more information.

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 find a Google Map marker's exact position

Tagged google-maps, marker, position, relative  Languages javascript

You need a custom OverlayWindow:

function ProjectionHelperOverlay(map) {
  this.set_map(map);
}

ProjectionHelperOverlay.prototype = new google.maps.OverlayView();
ProjectionHelperOverlay.prototype.draw = function () {
  if (!this.ready) {
    this.ready = true;
    google.maps.event.trigger(this, 'ready');
  }
}; 

overlay = new ProjectionHelperOverlay(map);

And you need to find the markers position relative to the overlay:

google.maps.event.addListener(marker, 'mouseover', function(event) {
  var p = overlay.get_projection().fromLatLngToDivPixel(marker.get_position());

  // map world relative to map container
  var container = overlay.get_panes().mapPane.parentNode;
  var x = p.x + parseInt(container.style.left);
  var y = p.y + parseInt(container.style.top);
});

Code found in this thread on Google Groups.

jQuery increment/decrement plugin

Tagged increment, decrement, jquery  Languages javascript

With the jQuery increment-decrement plugin:

(function($){  
  /**
   * Returns the current value of the counter.
   */
  function value(counter) {
    return parseInt(counter.html());
  }
  /**
   * Changes the counter's value.
   */
  function change(counters, step) {
    return counters.each(function() {  
      var $counter = $(this);
      // Increment counter
      var count = value($counter) + step;
      $counter.html(count);
      // Trigger event
      var event_name = step > 0 ? 'increment' : 'decrement';
      $counter.trigger(event_name, [$counter, count]);
      return count;
    });  
  }
  $.fn.increment = function(step) {  
    if(!step) { step = 1; }
    change(this, step);
  };  
  $.fn.decrement = function(step) {  
    if(!step) { step = -1; }
    change(this, step);
  };  
  $.fn.counterValue = function() {  
    return value($(this));
  };  
})(jQuery);

and the following HTML:

<div id="counter">0</div>

you can call these methods to increment/decrement the number:

$('#counter').increment();
$('#counter').increment(10)
$('#counter').decrement();
$('#counter').decrement(-10)

Event listeners

You can also listen to the increment and decrement events:

$('#counter').bind('increment', function(event, counter, value) {
  console.log('Incremented ' + counter + value);
});
$('#counter').bind('decrement', function(event, counter, value) {
  console.log('Decremented ' + counter + value);
});

Firebugx.js for CoffeeScript

Tagged firebugx.js, coffeescript  Languages javascript
try
  window.console = window.console or {}
  names = [ 
    "log", "debug", "info", "warn", "error", "assert", "dir", 
    "dirxml", "group", "groupEnd", "time", "timeEnd", "count", 
    "trace", "profile", "profileEnd"
  ]
  nada = ->
  for name in names
    window.console[name] = window.console[name] or nada

How to implement collapsible content (folders, categories, jimmy the cat) with jQuery

Tagged collapse, expand, jquery, folder, category  Languages javascript

This here is a quick-and-dirty implementation of folders for jQuery:

Markup

Any markup following the naming conventions should work, for example:

<ul class="collapsible">
  <li>
     <a href="" class="toggle-button">This be the folder</a>
    <ul style="display:none" class="collapsible-content">
        <li>This be the folder content</li>
        <li>This be the folder content</li>
    </ul>
  </li>
</ul>

JavaScript

/**
 * Collapsible categories implementation.
 * 
 */
var category = {
  find_category: function(target) {
    var category = target;
    // This isn't the category, so look for it
    if(!target.hasClass('collapsible')) {
      category = target.closest('.collapsible');
    }
    return category;
  },
  collapse: function(target) {
    var category = this.find_category(target);
    category.find('.collapsible-content').hide();
    category.removeClass('expanded');
    category.addClass('collapsed');
  },
  expand: function(target) {
    var category = this.find_category(target);
    category.find('.collapsible-content').show();
    category.addClass('expanded');
    category.removeClass('collapsed');
  },
  toggle: function(target) {
    var category = this.find_category(target);

    var is_expanded = category.hasClass('expanded');

    if(is_expanded) {
      this.collapse(category);
    } else {
      this.expand(category);
    }
  }
}

Usage

$('.toggle-button').live('click', function() {
  category.toggle($(this));
  return false;
});

How to optimize page load times by moving content into iframes

Tagged iframe, optimization, page-load  Languages javascript

Optimizing page load times can be done by moving external content, such as banners and ads, into iframes. Iframes, however, make your page load slower which is why it's recommended to create the iframes dynamically.

With jQuery we could do this:

function addBanner() {
  // iframe content affects page load time...
  $('#banners').html("<iframe frameborder="0" height='120px' scrolling='no' src='/banners.html' width='100%'></iframe>");
}

But as I found out this doesn't help page load times much as the main page's onload event is triggered after the iframe onload event.

The solution is an optimization technique described by Aaron Peters to create the iframe with plain JavaScript:

function addBanner() {
  // iframe content does not affect page load time...
  var i = document.createElement("iframe");
  i.src = "/banners.html";
  i.scrolling = "auto";
  i.frameborder = "0";
  i.width = "100%";
  i.height = "120px";
  document.getElementById("banners").appendChild(i);
}

Now all you have to do is call the addBanner in the onload event of the main page:

<script>
$(document).ready(function() {
  addBanner();
}
</script>

This technique shaved ~2.5 seconds of page load times. Still, this might not be the optimal way to load iframes on your page, so check out the different optimization techniques on Aaron Peters blog.