There a few simple things you could do to help clean up this code. The first thing I always recommend is to create a closure for your script using an IIFE. This allows your code to run in its own scope and keeps everything out of the global scope. You can also pass in jQuery
to the function expression and safely refer to it as $
.
(function($, undefined ) {
// pass in undefined for very old (ES3) browsers
// code goes here
})( jQuery );
The next thing you should consider is caching your selections. Since accessing the DOM is one of jQuerys slowest operations, you want to minimize this as much as possible. Anything you refer to more than once, you should cache.
var $min = $('#clockMinutes');
var $hr = $('#clockHours');
I prefix all of my jQuery selections with $ so I know they are jQuery objects.
You should also start using on
for defining your events instead of the shorthand of click
. Behind the scenes, click
uses on
so just skip the middle man.
$min.on('click', function() {
//code here
});
You might also want to consider DRYing your code. Since the click functions on both the clockMinutes
and clockHours
are so similar, you can combine them and just pass in the "main" element you want to work on. For example:
function updateScreen( $el ) {
$el.slideToggle();
if ( $el === $hour ) {
$min.hide();
} else {
$hour.hide();}
}
}
Here is an updated code sample based on the above. Note: I call an init
function on document.ready
to kick off the functionality.
(function( $, undefined ) {
//place holder variables for our selections
var $min, $hour, $minView, $hrView;
function init() {
$min = $('#clockMinutes');
$hour = $('#clockHours');
$minView = $('#clockMinutes');
$hrView = $('#minuteView');
$('#hour').on('click', function() { updateScreen($hour); });
$(' #minutes').on('click', function() { updateScreen($min); });
$('.timeSelect').on('click', function() { updateView($hrView); });
$('.minuteSelect').on('click', function() {updateView($minView);});
}
function updateView( $view ) {
$view.val( $(this).text() );
}
function updateScreen( $el ) {
$el.slideToggle();
if ( $el === $hour ) {
$min.hide();
} else {
$hour.hide();
}
}
$(function() {
init();
});
})( jQuery );
Hope you find this helpful. Let me know if you have any questions.