JQuery & JavaScript : A Better way to write
We all think that JavaScript so easy and we all can write better code.
But have you ever thought of if you write it in a proper manner it will be really easier to maintain the code in future.
Lets see what mistakes we do while writing Javascript and JQuery
1) BREAK UP JAVASCRIPT FUNCTIONALITY
BAD CODE
<a onclick="doSomething()" href="#">Click!</a>
GOOD CODE:
<a href="backuplink.html" class="doSomething">Click!</a>
$('a.doSomething').click(function(){
// Do something here!
alert('You did something, woo hoo!');
});
2) DONT RELY ON JAVASCRIPT
BAD CODE:
var now = new Date();
if(now.getHours() >= 12)
{
var goodDay = $('p[title="Good Day Message"]');
goodDay.text('Good Afternoon!');
}GOOD CODE:
<p title="Happy Birthday Message">Many Many Happy returns of the day!</p>
var now = new Date();
if(now.getHours() >= 13)
{
var Bday = $('p[title="Happy Birthday Message"]');
Bday.text('Many Many Happy returns of the day!');
}
3) USE SEMANTIC & ACCESSIBLE CODE FIRST
WORST CODE:<table>
<tr>
<td onclick="doFoo();">1st Option</td>
<td>First option desc</td>
</tr>
<tr>
<td onclick="doFoo();">2nd Option</td>
<td>Second option desc</td>
</tr>
</table>BAD CODE:
<dl>
<dt onclick="doFoo();">1st Option</dt>
<dd>First option description</dd>
<dt onclick="doFoo();">2nd Option</dt>
<dd>Second option description</dd>
</dl>GOOD CODE:
<dl id="OptionList">
<dt>1st Option</dt>
<dd>1st option description</dd>
<dt>2nd Option</dt>
<dd>2nd option description</dd>
</dl>
4) jQuery for Unobtrusive DOM
$(document); // initialise jQuery for object
$('#newtr') // item with ID "newtr"
$('p.second') // P tags with class second.
$('p[title="Good"]') // P tags with title "Good"
$('p[title^="G"]') // P tags title starting with G
jQuery is an very useful library that provides important tools to create great interactions