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.

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);
});

How to build popup menus and tooltips with jQuery

Tagged menu, hover, tooltip, contextmenu, jquery, popup  Languages javascript

This snippet shows you how to build a simple popup menu with jQuery. The example code can also be used to build things such as tooltips.

In the example we're going to build a menu for deleting table rows.

The HTML:

<table id="data">
  <tr>
    <td>
      <a href='/domains/digg.com'>digg.com</a>
      <!-- menu start -->
      <span class='hover-menu'>
        <a href='/domains/digg.com/remove' class='remove'>remove</a>
      </span>
      <!-- menu end -->
    </td>
  </tr>
</table>

The CSS:

.hover-menu
  display: none

The Javascript:

$.event.special.hover.delay = 200; 
$.event.special.hover.speed = 200; 

var show = function(e) {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');
  $tooltip.fadeIn();
}

var hide = function() {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');
  $tooltip.fadeOut();
}
$('#data td').bind('hover', show);
$('#data td').bind('hoverend', hide);

When you hover your mouse over table rows the menu will be shown.

You'll need to install the Event hover jQuery plugin to be able to use the hover and hoverend events. You could replace them with mouseenter and mouseleave, but usability would suffer...

jQuery cycle plugin

Tagged jquery, cycle  Languages javascript
(function($){  
  $.fn.cycle = function() {
    $(this).each(function(index) {
      var cls = index % 2 ? 'even':'odd';
      $(this).attr('class', cls);
    });
  }
})(jQuery);

Highlighting page elements with jQuery and the jquery-color plugin

Tagged jquery, highlight, ajax, plugin  Languages javascript

This plugin is useful for making the user aware of changes to the page. It does this through an animated effect that changes the matching element's color to light yellow and then back to transparent.

You need the jquery-color plugin and the highlight plugin:

// http://github.com/jquery/jquery-color
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);

// Highlight plugin
(function($){  
  $.fn.highlight = function(color) {
    $(this).each(function(index) {
      // Use default color if no color is specified
      if(!color) {
        color = "#faff99";
      }
      var $this = $(this);
      // We restore the original color at the end
      var original = $this.css('background-color');
      $this.animate({ backgroundColor: color }, 500)
      $this.animate({ backgroundColor: original }, 500)
    });
  }
})(jQuery);

To use the plugin use the following code:

$("table tr:first").highlight();

This will highlight the first row in the table.

You can also specify a color:

$("table tr:first").highlight('#ccc');