What's the best way to allow the browser to return to the link if JavaScript is disabled or disabled?

I want to add some Ajax collation to the list. Since my site works without JavaScript, I would like it to work for people with disabled, old / mobile browsers or noscript.

How can I run a JavaScript block when a link is clicked if JavaScript is enabled and if that link is not linked to that link then navigate to a new page. I would like to stay away from the hacky noscript tags.


source to share

5 answers

Your links need valid href values ​​pointing to alternative non-JavaScript pages, and in your click event you need to return false to prevent JavaScript enabled browsers from following 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...




I would use preventDefault


$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following

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


If there is no Javascript, HREF will be used.



I would suggest that you can put the url of the new page in an HREF and return false from the onClick event handler to stop the communication. If JS is not enabled, onClick will not be fired, which means the HREF will follow.



For good separation of concerns, it is best to use attachEvent (IE) or addEventListener (standard) (or a toolbox that hides from you like Prototype, jQuery, MooTools, YUI, Glow, etc.) and then cancel the event from 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

    // ...your code here...


You don't need to assign an ID reference, there are many ways to find DOM elements other than IDs, but a handy example does that.

jQuery, et. al. will have their own versions of event.stop (), but that boils down to canceling the event.



I would just write the HTML how it would look without JavaScript and then change the content to how it should look with JavaScript enabled.

If JS is enabled, the site may load slightly slower and may look a little odd while it is being built, but the functionality remains. In case JS is disabled, the site remains as it is and remains accessible to non-JS users



All Articles