Search code examples
javascriptjquerymouseeventjquery-events

Adding event handlers to array of buttons does not work Javascript


I am trying to assign event handlers to my buttons in an array. When I press the button, it should call a function but just doesn't and can't figure out why. Here is my code:

var btns = [];
    btns.push($('<div />').addClass('mvn_no mvn'));
    btns.push($('<div />').addClass('mvn_n mvn'));
    btns.push($('<div />').addClass('mvn_ne mvn'));
    btns.push($('<div />').addClass('mvn_o mvn'));
    btns.push($('<div />').addClass('mvn_c'));
    btns.push($('<div />').addClass('mvn_e mvn'));
    btns.push($('<div />').addClass('mvn_so mvn'));
    btns.push($('<div />').addClass('mvn_s mvn'));
    btns.push($('<div />').addClass('mvn_se mvn'));
    for ( var i = 0; i < btns.length; i++) {
        btns[i].mousedown(function() {
            moveImage(this);
        }).mouseup(function() {
            clearTimeout(tMovement);
        }).mouseout(function(){
            clearTimeout(tMovement);
        });
        table.find('td:eq(' + i + ')').append(btns[i]);
        $($options.expose.elementMovement).empty().append(table);

    }
    alert($._data( $("div.mvn_so"), "events" ));

Once this piece of code runs, I click on the buttons and nothing happens. I even tried calling a dummy function that only had an alert in it and it still doesn't work. I also tried to get the event on a given element and it returns undefined. Any help is appreciated.


Solution

  • So, after hours of debugging, I finally found the culprit that was breaking my code. It was the goddamned .empty() on $($options.expose.elementMovement).empty().append(table); when I removed it, the code worked just fine. I have no idea why it didn't work as it was but I am glad it works now. Even putting the empty in separate line breaks my code.