Usually when doing javascript, you’ll see a lot of script inside a page. For instance when we add a date picker on a text input, you could add a script block to the page and do the necessary initialization there:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<h1>Modify your settings</h1>

<form>
<div class="control-group">
<label class="control-label">Birthdate</label>
<div class="controls">
<div class="input-append">
<input type="text" name="birthDate" id="birthDate" />
<span class="add-on">
<i class="icon-calendar"></i>
</span>
</div>
</div>
</div>
</form>

<script type="text/javascript">
$(document).ready(function() {
$("#birthDate").datepicker({
dateFormat: "dd-mm-yy"
});
});
</script>

Now what if we needed to do this more then just once? Let’s change our html to a more unobtrusive way:

1
<input type="text" name="birthDate" id="birthDate" data-role="datepicker" />

Now just add a new javascript file to your website and include it in our html.

1
2
3
4
5
6
7
8
(function($) {
$(document).ready(function() {
//datepicker convention
$(':text[data-role="datepicker"]').datepicker({
dateFormat: "dd-mm-yy"
});
});
})(jQuery);

In this file we make sure we alias ‘$’ to jQuery as another plugin we use could have aliased it differently.

If you are worried about performance of the selector used here, you can always use a class in your convention.