Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable (and re-enable) the href and onclick on elements

I just want to enable / disable onclick and href on elements (a or div).

I don't know how to do this.

I can disable onclick by adding an handler on click event, but the href is still available.

 
$(this).unbind().click(function(event){
     event.preventDefault();
     return;
});

Edit FOUND A HACK FOR A ELEMENTS


if ($(this).attr("href")) {
     $(this).attr("x-href", $(this).attr("href"));
     $(this).removeAttr("href");
}
like image 452
jibees Avatar asked Jan 07 '11 13:01

jibees


4 Answers

If you return false on the onclick event, the href is irgnored.

  1. This will go to Goole: <a href="http://www.google.com" onclick="alert('Go to Google')">Test</a>

  2. This will not go to Google: <a href="http://www.google.com" onclick="alert('Go to Google'); return false;">Test</a>

like image 149
wosis Avatar answered Oct 23 '22 08:10

wosis


Ok i've found a workaround : putting an overlay over the main div containing all the elements i wanted to disable .. It just works.

like image 22
jibees Avatar answered Oct 23 '22 09:10

jibees


You could try the following:

$('a, div').click(
    function(e){
    return false;
        // cancels default action *and* stops propagation

    // or e.preventDefault;
       // cancels default action without stopping propagation
});

MDC documentation for preventDefault, jQuery documentation for event.preventDefault.

SO question: JavaScript event.preventDefault vs return false.

I'm unsure as to the problem of the "href still being available," since the click event is cancelled; however if you want to remove the href from a elements:

$('a[href]').attr('href','#');

will remove them (or, rather, replace the URL with a #).


Edited in response to comment (to question) by OP:

Ok, sorry ;) I just want to be able (by clicking on a button), to disable / enable all the links (click or href) over elements (div or a)

$('#buttonRemoveClickId, .buttonClassName').click(
function() {
    $('a, div').unbind('click');
});
$('#buttonReplaceClickId, .buttonOtherClassName').click(
function() {
    $('a, div').bind('click');
});
  • unbind(),
  • bind().
like image 38
David Thomas Avatar answered Oct 23 '22 07:10

David Thomas


Try this to disable click:

$(this).unbind('click');

like image 23
Diablo Avatar answered Oct 23 '22 08:10

Diablo