Never been to CodeSnippets 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 (or not, you can keep them private!)

jQuery accordion

jquery accordion
<script type="text/javascript" >
$(document).ready(function(){
    lastBlock = $("#a1");
    maxWidth = 210;
    minWidth = 75;	

    $("ul li a").hover(
      function(){
        $(lastBlock).animate({width: minWidth+"px"}, { queue:false, duration:400 });
	$(this).animate({width: maxWidth+"px"}, { queue:false, duration:400});
	lastBlock = this;
      }
    );
});
</script>

ul{
  list-style: none;
  margin: 0;
  padding: 0;
}

ul li{
  float: left;
  padding: 10px;
  display: block;
  margin-right: 10px;
}

ul li a{
  display: block;
  overflow: hidden;
  height: 75px;
  width: 75px;
}

#a1{
  width: 210px;
}

ul li img{
  position: absolute;
  border: 3px solid #881212;
}

ul li p{
  margin: 0;
  padding: 0;
  width: 120px;
  display: block;
  margin-left: 85px;
}

<ul>
  <li>
    <a id="a1">
      <img src="images/free_thumb.jpg" />
      <p>
        <strong>Freebies</strong><br/>
        Download free files to make your job easier.
      </p>
    </a>
  </li>
  <li>
    <a>
       <img src="images/tut_thumb.jpg" />
       <p>
         <strong>Tutorials</strong><br/>
         Tips and tricks to help you
         keep up with the latest technology.
       </p>
    </a>
  </li>
  <li>
    <a>
      <img src="images/inspire_thumb.jpg" />
      <p>
        <strong>Inspiration</strong><br/>
        Get inspired by what other designers are doing.
      </p>
    </a>
  </li>
</ul>

jQuery.innerWrap

The innerWrap method acts almost identical to the wrap method. The only real difference is that it wraps the contents of the element instead of the actual element. Authored by Brandon Aaron, author of the fantastic jQuery.Dimensions plugin.


jQuery.fn.innerWrap = function() {
	var a, args = arguments;
	return this.each(function() {
		if (!a)
			a = jQuery.clean(args, this.ownerDocument);
		// Clone the structure that we’re using to wrap
		var b = a[0].cloneNode(true),
		    c = b;
		// Find the deepest point in the wrap structure
		while ( b.firstChild )
			b = b.firstChild;
		// append the child nodes to the wrapper
		jQuery.each(this.childNodes, function(i, node) { 
			b.appendChild(node); 
		});
		jQuery(this)
			// clear the element
			.empty()
			// add the new wrapper with the previous child nodes appended
			.append(c);
	});
};


Usage:

The following example would effectively turn <h2>Title</h2> into <h2><span>Title</span></h2>

$(document).ready(function(){
      $(‘h2′).innerWrap(‘<span></span>’)
});


jQuery.emailProt

jQuery function to obfuscate email addresses.

jQuery.fn.emailProt = function(e) {
	$(this).each(function(){
		e = this.rel.replace('|','@');
		this.href = 'mailto:' + e;
		$(this).text(e);
	});
};


Usage:

$(document).ready(function(){
	$('.email').emailProt();	
});


<a rel="user|stylephreak.com" class="email"></a>

jQuery.attrToClass

Jquery function that appends a css class to all designated elements on a page by extracting a specific attribute from that element.

For instance, the example code below would change

<input type="submit" name="submit" value="Submit" />

to:

<input type="submit" name="submit" value="Submit" class="submit" />


jQuery.fn.attrToClass = function(attribute) {
	$(this).each(
		function(intIndex){
		    $(this).addClass($(this).attr(attribute));
	});
};

$(document).ready(function(){
        // designate the tag and the attribute to be extracted
	$("input").attrToClass("type");
});

Dynamically Display Form Parts

// Dynamically Display Form Parts

<script type=text/javascript>
var isIE=document.all?true:false;
var isDOM=document.getElementById?true:false;
var isNS4=document.layers?true:false;

/* _w : which ID (1) or (2) */
/* _h : (h)ide or (s)how */
function toggleT(_w,_h) {
  if (isDOM)
  {
    if (_h=='s') document.getElementById(_w).style.visibility='visible';
    if (_h=='h') document.getElementById(_w).style.visibility='hidden';
  }
  else if (isIE) {
    if (_h=='s') eval("document.all."+_w+".style.visibility='visible';");
    if (_h=='h') eval("document.all."+_w+".style.visibility='hidden';");
  }
  else if(isNS4)
  {
    if (_h=='s') eval("document.layers['"+_w+"'].visibility='show';");
    if (_h=='h') eval("document.layers['"+_w+"'].visibility='hide';");
  }
}
</script>

<form>
<span id="divt1" style="visibility:visible;position:relative;top:0;left:0">
  Type 1 Input:   <input name="t1" type="text"  value="">
</span>
<BR>
<span id="divt2" style="visibility:visible;position:relative;top:0;left:0;">
  Type 2 Input:   <input name="t2" type="text"  value="">
</span>
<BR>
Type 1 Visible  <input name="r1" type="radio" checked value="" onClick="toggleT('divt1','s')"> 
       Hidden   <input name="r1" type="radio" value="" onClick="toggleT('divt1','h')"><BR>
Type 2 Visible  <input name="r2" type="radio" checked value="" onClick="toggleT('divt2','s')"> 
       Hidden   <input name="r2" type="radio" value="" onClick="toggleT('divt2','h')">
</form>

Load file into Div via Ajax

// SCRIPT

$j(document).ready(function() {
	$j('a#ajaxLink').click(function(){
		$j("#ajaxBox").load("public/js/testAjax.html");
	});
});


// HTML
<a id="ajaxLink" href="javascript:;">Load Ajax</a>
<div id="ajaxBox"></div>

jQuery namespaced event binding/unbinding

// from a comment by Steven Bristol on errtheblog.com

I just wanted to share a really killer event handling tidbit:

Generally you do something like:

jQuery(’.class’).click(function(){//whatever});


Everyone knows this can be rewritten as:

jQuery(’.class’).bind(‘click’, function(){//whatever});


But sometimes you need to unbind something:

jQuery(’.class’).unbind(‘click’, function(){//});


The problem with this is that it will unbind all the click events, not just yours. So if multiple bits of javascript have a click event handler for ’.class’, unbinding removes them all. (This is because there is no way to identify an anonymous function.)

But jQuery is so good that there is a way to handle this: Namespacing your events:

jQuery(’.class’).bind(‘click.namespace’, function(){//}); 
jQuery(’.class’).unbind(‘click.namespace’);


or for reinitializing an element added via ajax:

jQuery(’.class’)unbind(‘click.namespace’).bind(‘click.namespace’, function(){//});

jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

Never render the full layout in a Rails view when called via AJAX

Essential for degradable javascript, when one never knows if a view or partial is being called via XmlHttpRequest or not. Throw the below code in your ApplicationController (application.rb)

More info in this blog post

def render(*args)
  	args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
	super
end

jQuery :: disable the enter key

// jQuery disable the enter key

You can intercept the enter key (code 34 I think...).

Something like this:

$("#myForm").bind("keypress", function(e) {
  if (e.keyCode == 34) return false;
});

Keypress may be the wrong event, can't remember if forms submit on keyup, keydown or keypress