Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - binding click event to a variable

All,

I am really stuck/ confused at this point.

I have an array with 6 items in it. Each item in the array is dynamically filled with elements using jquery '.html' method. However, I cannot seem to be able to attach/ bind an event to this dynamically created variable.

As soon as the browser gets to the problem line (see the area labeled 'PROBLEM AREA'), I get a 'undefined' error, which is really confusing as all the previous code on the very same variable works just fine.

var eCreditSystem = document.getElementById("creditSystem");
var i = 0;
var eCreditT = new Array(6);                    // 6 members created which will be recycled

function createCreditTransaction ()                 // func called when a transaction occurs, at the mo, attached to onclick()
{
    if (i < 6)
    {
        eCreditT[i] = undefined;                    // to delete the existing data in the index of array
        addElements (i);
    } else
    if (i > 5 || eCreditT[i] != undefined)
    {
         ...
    }
}

function addElements (arrayIndex)                   // func called from within the 'createCreditTransaction()' func
{
    eCreditT[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
    $(eCreditT[i]).attr ('id', ('trans' + i));
    $(eCreditT[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span>&nbsp;<img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
    creditTransactionSlideOut (eCreditT[i], 666);                   // calling slideOut animation
    console.log(eCreditT[i]);     // this confirms that the variable is not undefined

/* ***** THE PROBLEM AREA ***** */
    $(eCreditT[i]).on ('click', function ()                 // if user clicks on the transaction box
    {
        creditTransactionSlideBackIn (eCreditT[i], 150);                    // slide back in animation
    });
    return i++;
}
like image 404
Kayote Avatar asked Nov 29 '25 00:11

Kayote


1 Answers

Try this:

$(eCreditT[i]).bind('click', function() {
   creditTransactionSlideBackIn(eCreditT[i], 150);
});

Edit: use ++i instead of i++ like this:

return ++i;
/*
or
i += 1;
return i;
*/

retrurn ++i performs the increment first then return i after the increment. While return i++ return i then icrement it.

like image 162
Mahmoud Gamal Avatar answered Nov 30 '25 16:11

Mahmoud Gamal



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!