user1306165
user1306165

Reputation: 39

How to add and remove event in jQuery?

I have an image that has an InnerHTML for "a href" tag define in the .cs file as shown below.

HtmlGenericControl _divToolTipContainer = new HtmlGenericControl("div");
_divToolTipContainer.InnerHtml = "<a href=\"javascript:__doPostBack('" + btnItemThumbnail.ClientID.Replace("_", "$") + "','')\">" +
                              <img src='" + string.Format("ItemPreview.axd/{0}/width-250/height-328/", item.ID.ToString()) + "'></a>;

Now what I want is to have this "a href" event "remove" say if condition is (false) else "add" the event again by using jQuery. Sample code is shown below.

var objectDiv = document.getElementById(oElementId);    // get the object id 

If (false){ // condition here
    remove the event of the a href tag..
    jquery code must be added here..
}else{
    add the event again of the a href tag..
    jQuery code must be added here..
}   

How to do this?

Thanks

Jason

Upvotes: 0

Views: 74

Answers (2)

yckart
yckart

Reputation: 33408

if (false) {
    $('#oElementId').off('click', function() {});
} else {
    $('#oElementId').on('click', function() {});
}   

Upvotes: 1

Dylan Cross
Dylan Cross

Reputation: 5986

You may as well use jQuery to select the element by the ID as well, so

(function($) {

    var objectDiv = $("#"+oElementId);    // get the object id 

    if(false)
    { // condition here
        objectDiv.removeAttr("href"); 
    }
    else
    {
         objectDiv.attr("href", "javascript:__doPostBack('" + btnItemThumbnail.ClientID.Replace("_", "$") + "','')");
    } 

})(jQuery);

Edit: You may have to wrap your code in the (function($) to make sure your code is using the $ for jQuery

Upvotes: 1

Related Questions