views:

115

answers:

5

I want to add some Ajax sorting options to a list. Since my site runs without JavaScript thus far I'd like to keep it running for people with it turned off, old/mobile browsers or noscript.

How can I run a block of JavaScript when clicking a link if JavaScript is enabled and have that link direct the browser to a new page if it's not. I'd like to keep away from hacky noscript tags.

+1  A: 

I would imagine you could put the URL of the new page in the HREF, and return false from the onClick event handler to stop the link from being taken. If JS is not enabled then the onClick will not be run, meaning the HREF will be followed.

Tom Woolfrey
+6  A: 

Your links need valid href values pointing to the alternative non-JavaScript pages, and in your click event, you need to return false, to avoid JavaScript enabled browsers to follow the links:

<a id="aboutLink" href="about-us.html">About Us</a>


$('#aboutLink').click(function () {
   // ajax content retrieval here...
   return false; // stop the link action...
});
CMS
+1  A: 

For a good separation of concerns, your best bet is to use attachEvent (IE) or addEventListener (standard) (or a toolkit that hides that from you, like Prototype, jQuery, MooTools, YUI, Glow, etc.) and then cancel the event from within JavaScript. Assuming this link:

<a href='foo' id='mylink'>Link text</a>

...here's an example using Prototype:

// Hook up your handler on page load
document.observe("dom:loaded", function() {
    // Look up the link, apply your handler
    $('mylink').observe('click', yourHandler);
});

// Your handler:
function yourHandler(event) {
    // Prevent the default action
    event.stop();

    // ...your code here...
}

You don't have to assign the link an ID, there are lots of ways to find DOM elements other than IDs, but it makes a handy example.

jQuery, et. al., will have their own versions of event.stop(), but it comes down to cancelling the event.

T.J. Crowder
Sorry, missed the jQuery tag on your post, didn't realize you were looking for a jQuery example.
T.J. Crowder
That's cool, it's a good example none the less.
Sam152
+4  A: 

I would use preventDefault:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    $('#someDiv').load('content.php');
});

<a href="no-script.html">Load content</a>

If there's no Javascript, the HREF will be followed.

karim79
+1 for preventDefault
Wookai
A: 

I would simply write down the HTML as it would look like without JavaScript, and then modify the content as it should look with JavaScript enabled.

In case JS is enabled, the site might load a little bit slower and may look a bit weird while it is being built, but the functionality remains. In case JS is disabled, the site stays as it is and remains accessible for non-JS Users

Mike
The idea is that the UI is exactly the same but the way new content loads is different.
Sam152