Don’t Disorient Your Users With Links Used As Buttons

This is an oldie but goodie – a basic technique for preventing the page jumping to the top when clicking an <a> with an href="#" (or class="nolink" if you want to use a real link for accessibility purposes) when used for JavaScript functions (using JavaScript to maybe open a pop-up browser window – not considered ‘best practice’ in 2014, but still useful in some web apps, like if you need to see the whole web page while inputting data into a form in a pop-up window – or to perform a UI function with your <a> acting as a button).

The jQuery way (super easy – smashed onto one line for brevity):

$('body').on('click','a.nolink,a[href="#"]',function(e){e.preventDefault()});

The ‘modern’ browser way (Chrome, Firefox, Safari, IE9+) with native JavaScript, wrapped inside a super-cool IIFE:

(function(){
    var forEach = Array.prototype.forEach;
    var findAll = document.querySelectorAll.bind(document);
    forEach.call(findAll('a.nolink, a[href="#"]'), function(v){
        v.addEventListener('click', function(e){
            e.preventDefault();
        }, false);
    });
})();

(got a little help for that one from good ol’ Stack Overflow)

I know the jQuery way will also work for elements added after initial loading of the DOM, but not sure about the native code.

So there you go. That’s it.

Or… You know you could always use a <button> and style it to look like whatever you want (but I’ve run into problems in the past with browsers handling styles for <button> elements differently, that’s why I usually prefer <a> elements for ‘buttons’ that trigger JavaScript).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s