6 fast jQuery Tips

Force a Page Reload

This will forcefully reload the current page. No jQuery needed here.[ad code=4]

location.reload(true);

If your content might be cached by proxy servers and your URL has no query string, try this:

location.replace(
 location.href.replace(/\?.*$/, '') + '?' + Math.random());

Many ad networks use this trick to ensure that ad tags are never cached.

Try it: Reload this page.

Reload an Image

There is no reload or replace method for images. The src property can be set in the same way as the location.href property though.

with($('#image')) {
 src = src.replace(/\?.*$/, '') + '?' + Math.random();
}

Roßstein, Buchstein und Leonhardstein

Try it: Reload this awesome photo of my awesome tour to the Schildenstein. In Firebug, you will see the new image being loaded.

Replace a <div> with jQuery

The easiest way, pointed out by Paul, is to use the replaceWith method.

$('#thatdiv').replaceWith('<div>fnuh</div>');

A more confusing way is to insert the new element after the target element’s previous element and then remove the target element. The with statement makes it shorter.

with ($('#thatdiv')) {
 with (prev()) {
  after('<p>Your new content goes here</p>');
 }
 remove();
}

Try it: Replace this element with something completely different.

Verify if an Element is empty

if ($('#keks').html()) {
 // Do something to remedy the situation
}

Test it: Is this element empty?

Append or Add HTML to an Element

One of the nicest things about jQuery that most methods are named what you’d expect them to be named.

$('#lal').append("<b>lol</b>");

Test it: Append your eBay username and password to this.

When to load jQuery on the page?

I assume most people include the jquery.js in the <head> portion of a page – at least I do. But unless you write CSS overrides on the page from JavaScript (document.write('<style>/<script>…')), putting it at the bottom improves performance.

I hope you have enjoyed these snippets. If you did, get updates via my news feed.

http://johannburkard.de/blog/programming/javascript/6-fast-jQuery-Tips-More-basic-Snippets.html

Leave a comment