views:

1487

answers:

2

I have this link:

<a id="myLink_33" href="javascript:toggleMe(1);">Toggle</a>

How can I change the href attribute of this link using Javascript/jquery so the link becomes this:

<a id="myLink_33" href="javascript:toggleMe(0);">Toggle</a>
+6  A: 
$("#myLink_33").attr("href", "javascript:toggleMe(0);");
Tim S. Van Haren
+1  A: 

That will certainly work, however I'd like to propose an alternative.

HTML

<a class="toggle">Toggle</a>

jQuery/JavaScript

$(document).ready(function(){
  $('a.toggle').click(function (eventObject){
    var target = $(eventObject.target);

    // will add or remove the class automatically
    target.toggleClass('toggle_on');

    if(target.hasClass('toggle_on')){
      /* toggle on code here */
      alert('Toggle On');
    }
    else{
      /* toggle off code here */
      alert('Toggle Off');
    }
  });
});

This gets you out of having to use the href attribute for the toggles and lets you control things through styling and whatnot. Though my experience with jQuery is not all that extensive something like this seems a bit more conventional.

Crazy Joe Malloy