Tutorial Cycle Through a List

by in , 0

This code will cycle through an unordered list with an ID of 'cyclelist'. Can be used on any element with children. Replace "ul#cyclelist li" with the elements you want to cycle through.

$(document).ready(function() {

	 var j = 0;
	 var delay = 2000; //millisecond delay between cycles
	 function cycleThru(){
	         var jmax = $("ul#cyclelist li").length -1;
	         $("ul#cyclelist li:eq(" + j + ")")
	                 .animate({"opacity" : "1"} ,400)
	                 .animate({"opacity" : "1"}, delay)
	                 .animate({"opacity" : "0"}, 400, function(){
	                         (j == jmax) ? j=0 : j++;
	                         cycleThru();
	                 });
	         };

	 cycleThru();

 });
ul#cyclelist {width:200px;border:solid;position:relative;overflow:hidden;height:200px}
ul#cyclelist li {font-size:1.4em;padding:20px;opacity:0;position:absolute}

Reference URL

Tutorial Combine Slide and Fade Functions

by in , 0

$.fn.slideFadeToggle  = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
}; 

Usage

$("#something").click(function() {
   $(this).slideFadeToggle();
});

Tutorial Click Once and Unbind

by in , 0

Have something happen on a click event, but only once! Unbind the click handler after the element has been clicked once.

$('#my-selector').bind('click', function() {
       $(this).unbind('click');
       alert('Clicked and unbound!');
});

Also see Ben's comment below for jQuery's .one() function which is essentially the same thing.

Tutorial Clear Default Search String on Focus

by in , 0

$("#s")
    .val("Search...")
    .css("color", "#ccc")
    .focus(function(){
        $(this).css("color", "black");
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    })
    .blur(function(){
        $(this).css("color", "#ccc");
        if ($(this).val() == "") {
            $(this).val("Search...");
        }
    });
Set value of field to "Search..." When field comes into focus, set color to black. If value is default, remove it. When field goes out of focus, set color back to light gray. If value is empty, put back default value

Tutorial Clear a File Input

by in , 0

You can just clone it and replace it with itself, with all events still attached.

var input = $("#control");

function something_happens() {
    input.replaceWith(input.val('').clone(true));
};

Tutorial Check if jQuery is Loaded

by in , 0

if (typeof jQuery == 'undefined') {

    // jQuery IS NOT loaded, do stuff here.

}

Tutorial Check if Event was Triggered or Native

by in , 0

$('button').click(function(event, wasTriggered) {
    if (wasTriggered) {
        alert('triggered in code');
    } else {
        alert('triggered by mouse');
    }
});

$('button').trigger('click', true);