views:

73

answers:

5

I have some links displayed on a page, that I would like to enable/disable based on other events on the page. Is there a way to do this w/ jQuery?

+1  A: 

You could do something like:

$('.links').click(function(e){
  if( [some conditions] ){
    e.preventDefault();
  }
});

Be sure to show that they no longer work somehow, otherwise your users will get confused, lol.

pho3nixf1re
A: 

it depends on what you mean by "disable".

this will make them do nothing:

$("A").click(function() { return false; });
dave thieben
I think OP means change them from a link to text so they do not appear as links. Otherwise spot on!
Chris
return false is not advised. Use e.preventDefault() instead.
dekomote
well, you learn something new every day. thanks.
dave thieben
+4  A: 
$('selector_for_links_to_disable').bind('click', function(e){
        e.preventDefault();
})

and for enabling:

$('selector_for_links_to_enable').unbind('click')
dekomote
i like this one even better
dave thieben
A: 
$(document).delegate('.links', 'click', function () {
  if ([your condition is true]) {
    return false;
  }
})

delegation is better than handlers, because you can call them before the dom is loaded

Tibastral
A: 

You can do something like this:

<script>
    $(document).ready(function() {
        $('input#disableall').live('click', function(){
            $('a').attr( 'class', 'disabled' );
            alert('All links are disabled.');
        });


        $('input#enableall').live('click', function(){
            $('a').attr( 'class', 'enabled' );
            alert('All links are enabled.');
        });

        $('a.disabled').live('click', function(event){
            event.preventDefault();
        });
    });
</script>

<a href='http://www.google.com'&gt;Google&lt;a/&gt;
<a href='http://www.yahoo.com'&gt;Yahoo&lt;a/&gt;
<a href='http://www.hotmail.com'&gt;Hotmail&lt;a/&gt;

<input type='button' id='disableall' value='Disable Links' />
<input type='button' id='enableall'  value='Enable Links' />
NAVEED