Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 444 total  RSS 

jquery examples

// description of your code here

   1  
   2  some cool shortcuts in jquery to get started with it .. 
   3  
   4  http://www.shafqatahmed.com/2008/08/mybutton-font-f.html
   5  
   6   
   7  // Makes each odd tr element to have a blue backcolor
   8  $("tr:odd").css("background-color", "blue");
   9  
  10  
  11  // What if we want to make the header row have a different look ? Show Me
  12  $("#results tr:first").css("background", "black");
  13  $("#results tr:first").css("color", "white");
  14  $("#results tr:first").css("font-weight", "bold");
  15  
  16  
  17  // We also could have assigned a class name to the header tr element like this 
  18  $("#results tr:first").addClass("header");
  19  
  20  
  21  //All span that are inside a div element (may not be immediate child of the div) will be selected.
  22  $("div span").css("border", "1px solid");
  23  
  24  //Here is how we select the links that are descendent of span which are direct children of a div
  25  $("div > span a")
  26  
  27  //Here is how we can select a div with id mydiv 
  28  $("div#mydiv")
  29  
  30  
  31  // Here is how we select all links under div elements that have css class set to mycss
  32  $("div.mycss a")
  33  
  34  // if we want to find a link that points to http://www.google.com then we would write
  35  $("a[href=http://www.google.com]")
  36  
  37  
  38  // Modifications
  39  $("body").prepend("<img src='banner.jpg' />");
  40  $("div#mydialog").html("<p>Hi There!</p>");
  41  $("#mytable").wrap("<div></div>");
  42  
  43  
  44  // How to replace all hr elements (horizontal line) with a br element
  45  $("<br/>").replaceAll("hr");

Fire Javascript DOM events

Fire Javascript DOM events

   1  function fireEvent(obj, evt) {
   2    var fireOnThis = obj;
   3    if (document.createEvent) {
   4      var evObj = document.createEvent("MouseEvents");
   5      evObj.initEvent(evt, true, false);
   6      fireOnThis.dispatchEvent(evObj);
   7    else if (document.createEventObject) {
   8      fireOnThis.fireEvent("on" + evt);
   9    }
  10  }


Usage: clicking on a link using Javascript

HTML
   1  <a href="foo.html" id="fooanchor" style="display: none>Nothing to see here</a>

Javascript
   1  fireEvent(document.getElementById('fooanchor'), "click")

javascript: formatDate function



   1  
   2  var formatDate = function (formatDate, formatString) {
   3  	if(formatDate instanceof Date) {
   4  		var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
   5  		var yyyy = formatDate.getFullYear();
   6  		var yy = yyyy.toString().substring(2);
   7  		var m = formatDate.getMonth();
   8  		var mm = m < 10 ? "0" + m : m;
   9  		var mmm = months[m];
  10  		var d = formatDate.getDate();
  11  		var dd = d < 10 ? "0" + d : d;
  12  		
  13  		var h = formatDate.getHours();
  14  		var hh = h < 10 ? "0" + h : h;
  15  		var n = formatDate.getMinutes();
  16  		var nn = n < 10 ? "0" + n : n;
  17  		var s = formatDate.getSeconds();
  18  		var ss = s < 10 ? "0" + s : s;
  19  
  20  		formatString = formatString.replace(/yyyy/i, yyyy);
  21  		formatString = formatString.replace(/yy/i, yy);
  22  		formatString = formatString.replace(/mmm/i, mmm);
  23  		formatString = formatString.replace(/mm/i, mm);
  24  		formatString = formatString.replace(/m/i, m);
  25  		formatString = formatString.replace(/dd/i, dd);
  26  		formatString = formatString.replace(/d/i, d);
  27  		formatString = formatString.replace(/hh/i, hh);
  28  		formatString = formatString.replace(/h/i, h);
  29  		formatString = formatString.replace(/nn/i, nn);
  30  		formatString = formatString.replace(/n/i, n);
  31  		formatString = formatString.replace(/ss/i, ss);
  32  		formatString = formatString.replace(/s/i, s);
  33  
  34  		return formatString;
  35  	} else {
  36  		return "";
  37  	}
  38  }


   1  
   2  alert(formatDate(new Date(), "d mmm yyyy hh:nn:ss"));

determine screen height

// description of your code here

..normally

   1  
   2  var h = document.documentElement.scrollHeight;


..however in some cases (safari 3) you may have to find where something is on the screen and generate the actual screen size around that
   1  
   2  if (($('lightbox_bottom').cumulativeOffset().top+30) > document.documentElement.scrollHeight) {
   3    $('sBg').style.height=$('lightbox_bottom').cumulativeOffset().top+30+'px';
   4  }
   5  else {
   6    $('sBg').style.height=document.documentElement.scrollHeight+'px';
   7  }


30 being the height of the bottom element your using to judge.

parent.subclasses is undefined - prototype 1.8.0 error

http://prototype.lighthouseapp.com/projects/8886/tickets/151-extending-yui-objects-with-prototype

fix

   1  
   2  Class.create = Class.create.wrap(function(proceed, parent) {
   3    if (Object.isFunction(parent))
   4      parent.subclasses = parent.subclasses || [];
   5    return proceed.apply(Class, $A(arguments).slice(1));
   6  })

String.prototype.tld – match Top-Level-Domain

// javascript : match tld in window.location.hostname (last 2-6 chars)
   1  
   2  String.prototype.tld = function(){
   3  	return (m = this.match(new RegExp("\.([a-z,A-Z]{2,6})$") )) ? m[1] : false;
   4  }

htmlspecialchars in Javascript

   1  
   2  function htmlspecialchars(p_string) {
   3  	p_string = p_string.replace(/&/g, '&amp;');
   4  	p_string = p_string.replace(/</g, '&lt;');
   5  	p_string = p_string.replace(/>/g, '&gt;');
   6  	p_string = p_string.replace(/"/g, '&quot;');
   7  //	p_string = p_string.replace(/'/g, '&#039;');
   8  	return p_string;
   9  };


Retour a la Source : jeux-video games javascript

Timer function for JQuery

// This is a quick sample of how the plugin jquery.timers.js works. The timer code can
// be downloaded from http://jquery.offput.ca/every/
// or from http://www.downloadjavascripts.com/list/javasitekk37/Details.aspx
//
// I use the timer to avoid race-condition issues when switching from tab to tab in
// a JQuery UI. Since JavaScript doesn't (as far as I can tell) have a system for
// managing threads, I needed to introduce a slight delay to stop the code
// from trying to set focus on a tab before the tab was actually made visible.
// This code works on both IE and Firefox -- and, of course, slightly better
// on Firefox.
//
// Interesting side note: I used to switch on the field returned by
// "$tabs.data('selected.tabs');" but in IE the value would often switch
// back to zero before selecting that tab. Another race condition. So I found
// it safer to simply dictate to the switch statement which tab I wanted to select.
//
// Also, there seems to be an issue with the timer plugin -- I could not get it to
// work without having to specify seconds, miliseconds, etc. It is supposed to default
// to using miliseconds, but it did not seem to recognize integers at all, and needed time
// passed in strings with "ms" attached. It's entirely possible that I overlooked something,
// but I had a deadline looming so I just went with what I could get to work.
//

   1  
   2  function selectNextTab(tabName) {
   3      
   4      switch(tabName) {
   5          case ("firstTab"):
   6              $('#application > ul').tabs('select', 1).oneTime("50ms", function() { 
   7                  $('select#notificationType').focus();
   8              });
   9              break;
  10          
  11          case ("secondTab"):
  12              $('#application > ul').tabs('select', 2).oneTime("50ms", function() { 
  13                  $('input#annualIncome').focus(); 
  14              });
  15              break;
  16          
  17          case ("thirdTab"): 
  18              $('#application > ul').tabs('select', 3).oneTime("50ms", function() {
  19                  $('select#typeOfAssist').focus();
  20              });
  21              break;
  22      }
  23  }

Embed an OGG video on a web page

This code was copied from an HTML page from Superman: The Arctic Giant [xiph.org]

   1  
   2  <video id="testvideo" style="display:none"></video>
   3  
   4  
   5  <script language="JavaScript">
   6  var vlcActiveX = false;
   7  var vlcPlugin = false;
   8  var videoElement = false;
   9  var oggPlugin = false;
  10  var javaEnabled = false;
  11  </script>
  12  <script language="vbScript">
  13  on error resume next
  14  vlcActiveX = (IsObject(CreateObject("VideoLAN.VLCPlugin.2")))
  15  </script>
  16  
  17  
  18  <script language="JavaScript">
  19  
  20  function embedVideoElement(location, width, height) {
  21    document.write("<video style=\"width:" + width + ";height:" + height + ";\" src='" + location + "' id='video_element'></video><br>");
  22    document.write("<input type='button' value='play' onClick='document.getElementById(\"video_element\").play()'>");
  23    document.write("<input type='button' value='stop' onClick='document.getElementById(\"video_element\").pause(); document.getElementById(\"video_element\").start = 0;'>");
  24  }
  25  
  26  function embedOggPlugin(location, width, height) {
  27    document.write("<object type='application/ogg' width='"+width+"' height='"+height+"' data='" + location + "'></object>");
  28  }
  29  
  30  function embedVlcPlugin(location, width, height) {
  31    document.write("<object type='application/x-vlc-plugin' id='vlc_element' width='"+width+"' height='"+height+"' data='" + location + "'></object><br>");
  32    document.write("<input type='button' value='play' onClick='document.getElementById(\"vlc_element\").play()'>");
  33    document.write("<input type='button' value='stop' onClick='document.getElementById(\"vlc_element\").stop()'>");
  34  }
  35  
  36  
  37  function embedVlcActiveX(location,width,height) {
  38    document.write("<object classid='clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921' codebase='http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab#Version=0,8,6,0' width='"+width+"' height='"+height+"' id='vlc_element'>");
  39    document.write("<param name='MRL' value='" + location +"'>");
  40    document.write("</object><br>");
  41    document.write("<input type='button' value='play' onClick='document.getElementById(\"vlc_element\").playlist.play()'>");
  42    document.write("<input type='button' value='stop' onClick='document.getElementById(\"vlc_element\").playlist.stop()'>");
  43  }
  44  
  45  function embedCortado(location,width,height) {
  46    document.write("<applet code='com.fluendo.player.Cortado.class' archive='cortado.jar' width='"+width+"' height='"+height+"'>");
  47    document.write("<param name='url' value='" + location + "'>");
  48    document.write("</applet>");
  49  }
  50  
  51  
  52  
  53  if(document.getElementsByTagName("video").length > 0) {
  54    var myvideo = document.getElementById("testvideo");
  55    if(myvideo.play) {
  56      videoElement = true;
  57    }
  58  }
  59  
  60  var searchedMimeTypes = false;
  61  var foundJavaMimeType = false;
  62  
  63  if(navigator.mimeTypes && navigator.mimeTypes.length > 0) {
  64  
  65    searchedMimeTypes = true;
  66  
  67    for (var i = 0; i < navigator.mimeTypes.length; i++) {
  68      if(navigator.mimeTypes[i].type.indexOf("application/ogg") > -1) {
  69        oggPlugin = true;
  70      }
  71      if(navigator.mimeTypes[i].type.indexOf("application/x-vlc-plugin") > -1) {
  72        vlcPlugin = true;
  73      }	
  74      if(navigator.mimeTypes[i].type.indexOf("application/x-java-applet") > -1) {
  75        foundJavaMimeType = true;
  76      }
  77    }
  78  
  79  }
  80  
  81  
  82  var nativePlayback = vlcActiveX || vlcPlugin || videoElement || oggPlugin;
  83   
  84  if(searchedMimeTypes) {
  85    javaEnabled = navigator.javaEnabled() && foundJavaMimeType;
  86  } else {
  87    javaEnabled = navigator.javaEnabled();
  88  }
  89  
  90  
  91  var file = "arctic_giant.ogg";
  92  var width = 512;
  93  var height = 384;
  94  
  95  if(videoElement) {
  96    embedVideoElement(file,width,height);
  97  } else if(vlcPlugin) {
  98    embedVlcPlugin(file,width,height);
  99  } else if(vlcActiveX) {
 100    embedVlcActiveX(file,width,height);
 101  } else if(oggPlugin) {
 102    embedOggPlugin(file,width,height);
 103  } else if(javaEnabled) {
 104    embedCortado(file,width,height);
 105  }
 106  
 107  </script>
 108  


See also another example of embedded OGG video with information about Saint Lucia [wikipedia.org]

Javascript sleep

Imitate sleep in javascript

   1  
   2  function wait(msecs)
   3  {
   4  var start = new Date().getTime();
   5  var cur = start
   6  while(cur - start < msecs)
   7  {
   8  cur = new Date().getTime();
   9  }
  10  } 
« Newer Snippets
Older Snippets »
Showing 1-10 of 444 total  RSS