Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery delegate is not working?

Tags:

jquery

I am trying to use delegate to call a function, when a specific set of links get click. I have already used it before in some other page. It was worked there. But, this time i even not able to find, where the problem is.

My links were dynamically generated, they looks like

<a class="thumbLink" href="#" id="My HomeTown-1"><small>My HomeTown</small></a>

And the jQuery delegate function is,

$(document).ready(function(){
$("#albumHolder").delegate('a.thumbLink', 'click', this.loadAlbum);//albumHolder is div ID that holds all the <a> elements

this.loadAlbum = function(){
    var id = this.id;
    var number = id.lastIndexOf("-");
    var alubmName = id.subString(0, number);
    alert(albumName);
}
});

Update:

I tried both versions, But i am not able to make it work!

$("#albumHolder").delegate('a.thumbLink', 'click', function loadAlbum(){
    var id = this.id;
    var number = id.lastIndexOf("-");
    var alubmName = id.subString(0, number);
    alert(albumName);
});



   this.loadAlbum(){
    var id = this.id;
    var number = id.lastIndexOf("-");
    var alubmName = id.subString(0, number);
    alert(albumName);
}
$("#albumHolder").delegate('a.thumbLink', 'click', this.loadAlbum);

The above code is in $(document).ready(function(){});. Is that correct?? i also tried by putting them in a separate js file. I cannot make it work.

Any idea about my problem!!!


2 Answers

If that's the order of your actual code, you're trying to pass the function expression before it has been initialized.

Reverse them and it should work:

this.loadAlbum = function(){
    var id = this.id;
    var number = id.lastIndexOf("-");
    var alubmName = id.subString(0, number);
    alert(albumName);
}
$("#albumHolder").delegate('a.thumbLink', 'click', this.loadAlbum);
like image 142
user113716 Avatar answered Jan 29 '26 09:01

user113716


You use a function expression before defining it. This doesn't work. Either use a regular function declaration (function loadAlbum() { /* ... */ }) or define this.loadAlbum (this.loadAlbum = function() { /* ... */ }) before using it in your delegate() call.

like image 20
ThiefMaster Avatar answered Jan 29 '26 09:01

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!