Tutorial Validate Age

by in , 0

This snippet presupposed an HTML form with and ID of "age-form" and three inputs (text or select) with the IDs "day", "month", and "year" respectively.

$("#age-form").submit(function(){
	var day = $("#day").val();
	var month = $("#month").val();
	var year = $("#year").val();
	var age = 18;
	var mydate = new Date();
	mydate.setFullYear(year, month-1, day);

	var currdate = new Date();
	currdate.setFullYear(currdate.getFullYear() - age);
	if ((currdate - mydate) < 0){
		alert("Sorry, only persons over the age of " + age + " may enter this site");
		return false;
	}
	return true;
});

You may wish to do something more elegant than an alert, and should also probably validate the form with server side code or else this protection only works for users with JavaScript enabled.

Tutorial Underline Individual Words

by in , 0

There is no CSS for applying an underline (text-decoration: underline;) only to individual words in a multiple-word element. The best way would be to wrap each word in a span (not the spaces, just the words) in spans and apply underline to those spans. Here's jQuery to do that to h1 elements.

$('h1').each(function() {

	var words = $(this).text().split(' ');

	$(this).empty().html(function() {

		for (i = 0; i < words.length; i++) {
			if (i == 0) {
				$(this).append('<span>' + words[i] + '</span>');
			} else {
				$(this).append(' <span>' + words[i] + '</span>');
			}
		}
	
	});

});

Then you could do:

h1 span {
  text-decoration: underline;
}

Similar and slightly more robust solution: Lettering.js

Reference URL

Tutorial Triple Click Event

by in , 0

$.event.special.tripleclick = {

    setup: function(data, namespaces) {
        var elem = this, $elem = jQuery(elem);
        $elem.bind('click', jQuery.event.special.tripleclick.handler);
    },

    teardown: function(namespaces) {
        var elem = this, $elem = jQuery(elem);
        $elem.unbind('click', jQuery.event.special.tripleclick.handler)
    },

    handler: function(event) {
        var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
        clicks += 1;
        if ( clicks === 3 ) {
            clicks = 0;

            // set event type to "tripleclick"
            event.type = "tripleclick";
            
            // let jQuery handle the triggering of "tripleclick" event handlers
            jQuery.event.handle.apply(this, arguments)  
        }
        $elem.data('clicks', clicks);
    }
    
};

Usage

$("#whatever").bind("tripleclick", function() {
   // do something
}

Reference URL

Tutorial Trigger Click on Input when Label is Clicked

by in , 0

Labels should have "for" attributes that match the ID of the input they are labeling. This means we can snag that attribute and use it in a selector to trigger a click on the input itself. Assuming of course you have some reason to watch for clicks on inputs.

var labelID;

$('label').click(function() {
       labelID = $(this).attr('for');
       $('#'+labelID).trigger('click');
});

Tutorial Track Window Resizes through Google Analytics

by in , 0

Sparkbox has this snippet to help figure out how often browser windows really are resized.

(function() {
  var resizeTimer;
  
  // Assuming we have jQuery present
  $( window ).on( "resize", function() {
    
    // Use resizeTimer to throttle the resize handler
    clearTimeout( resizeTimer );
    resizeTimer = setTimeout(function() {

     /* Send the event to Google Analytics
      *
      * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
      * _trackEvent(category, action, opt_label, opt_value, opt_noninteraction)   
      */
      var $window = $( window );
      _gaq.push( [ "_trackEvent", "User Actions", "Browser Resize", $window.width() + " x " + $window.height() ] );
    }, 1000);
  });
})();

Note how easy it is to track events in Google Analytics. That can be used for just about anything.

Tutorial Toggle Text

by in , 0

Let's say you have a link to show more options which expands a list of options. It's says "more options". It's easy to toggle those options with .toggle() or .slideToggle(), but the text remains the same. To toggle the text too...

$("#more-less-options-button").click(function() {
     var txt = $("#extra-options").is(':visible') ? 'more options' : 'less options';
     $("#more-less-options-button").text(txt);
     $("#extra-options").slideToggle();
});

There is a bunch of other ways, as well.

Tutorial Test if at least one checkbox is checked

by in , 0

In this example, a submit button is disabled if none of the checkboxes are checked and enabled if at least one is checked.

<form>
   <!-- bunch of checkboxes like: -->
   <input type="checkbox" ... >
   <input type="checkbox" ... >

   <!-- submit button, defaults to disabled -->
   <input type="submit" value="submit">
</form>

The trick is that you can use .is(":checked") on a jQuery object full of a bunch of elements and it'll return true if any of them are checked and false if none of them are. AND, using .attr() for the disabled attribute with that boolean value will enable/disable that button.

var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");

checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
});

Reference URL