Good programming practice

I am wondering what is a good programming practice when using jQuery. Is it the best to use for everything jQuery for consequency, even for most simple things? Or is it ok to use for half things javascript without jQuery and adding jquery just for some things?

Example 1
For example I allways use functions and then href=“javascript:void(0);” onsubmit=“myFunction();”. Some people say I should use id instead.

Example 2
Another example TheForm.firstname.value.length; or $(“#firstName”).lenght().

Example 3:
<script language=“javascript”>
alert(‘Hello World’);
</script>

vs

$(document).ready(function()
{
alert(‘Hello World’);
});

Why some people say it should be used the second one since the first one is more pure and more simple?

And so on. What is your opinion about what is a professional practice?

When it comes to the javascript void stuff, that is nearly useless, as people who don’t use javascript will find the link to be completely useless.

Start from bedrock, with HTML.

Can the link be made useful when there is no javascript, such as by linking to a larger image, or to some other part of the current page?

Yes? Link to the appropriate location.


<div id="gallery">
    <span id="largeimage"></span>
    <a href="images/image.png"><img src="image.thm.png"></a>
</div>

Then use scripting to attach your onclick event to the links


function thumbClickHandler() {
    ...
    return false;
}
var gallery = document.getElementById('gallery'),
    thumbs = gallery.getElementsByTagName('a'),
    i;
for (i = 0; i < thumbs.length; i += 1) {
    thumbs.onclick = thumbClickHandler;
}

Or, using jQuery:


function thumbClickHandler() {
    ...
    return false;
}
$('#gallery a').click(thumbClickHandler);

No useful on-page link target? Create the link with javascript and place it on the page.


function handleNextClick () {
    ...
}
var next = document.createElement('a');
next.href = '#';
next.appendChild(document.createTextNode('Next');
next.onclick = handleNextClick;
if (gallery.nextSibling) {
    gallery.parentNode.insertBefore(gallery.nextSibling, next);
} else {
    gallery.parentNode.appendChild(next);
}

Or with jQuery.


function handleNextClick () {
    ...
}
$('#gallery').after(
    $('<a></a>', {
        href: '#',
        text: 'Next',
        click: handleNextClick 
    })
);

When dealing with jQuery, if you’re using it for more than a couple of small tasks, you might as well leverage the benefits that is has, in terms of reducing the complexity of your code, and providing cross-compatibility across many different browsers and environments.