1) Back To Top Button
$('a.top').click(function(){ $(document.body).animate({scrollTop : 0},800); return false; });
By changing the scrollTop value we can change where we want the scrollbar to land, in my case I used a value of 0 because I want it to go to the very top of our page, but if I wanted an offset of 100px I could just type 100px in the function.
So all we are really doing is animating the body of our document throughout the course of 800ms until it scrolls all the way to the top of the document.
2) Fix Broken Images
<pre><code>$('img').error(function(){ $(this).attr('src', ‘img/broken.png'); });</code></pre>
Occasionally there are times when we have broken image links on our website and replacing them one by one isn't easy and this often comes at unexpected times, so adding this simple piece of code can save you a lot of frustrations. Even if you don't have any broken images adding this doesn't do any harm, and a pretty —official— broken image of your own looks a LOT better than the browser default.
3) Stop Links From Loading
<pre><code>$(‘a.no-link').click(function(e){ e.preventDefault(); });</code></pre>
Sometimes we don't want links to go to a certain page or even reload it, we want them to do something else like trigger some other script and in that case this piece of code will do the trick of preventing the default action.
4) Make two divs the same height
<pre><code>$(‘.div').css('min-height', $(‘.main-div').height());</code></pre>
Sometimes you want two divs to have the same height no matter what content they have in them such as a sidebar and content area, this little snippet enables just that; in this case it sets the min-height which means that it can be bigger than the main div but never smaller.
5)Smooth Scrolling Links
$('a[href^="#"]').bind('click.smoothscroll',function (e) { e.preventDefault(); var anchor = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 500, 'swing', function () { window.location.hash = anchor; }); });
This snippet is becoming more and more useful as the prevelance of one page designs increases. This is useful for anchor links on the same page allowing for a much more user friendly experience when traveling to a different page of a page.