Jenan
Jenan

Reputation: 3320

Jquery - live ready

I need to use the function live on the document ready.

I tried this code (it does not work correctly):

$(document).live('ready', function() {

 $(".icons").contextMenu(
                { 
                    menu: 'menuIcons'                    
                }, 
                function(action, el, pos) 
                { 
                    contextMenuWork(action, el, pos); 
                }); 

function contextMenuWork(action, el, pos) {
            switch (action) {
                case "open":
                    {
                        alert("open");
                        break;
                    }
            }
            }


});

Upvotes: 0

Views: 4712

Answers (4)

voigtan
voigtan

Reputation: 9031

In your AJAX code when when you know what data you can bind the plugin on that data when you have appended it to the DOM

(function() {
    var contextMenuWork = function(action, el, pos) {
        switch (action) {
            case "open":
            {
                alert("open");
                break;
            }
        }
    };

    $.ajax({
        url: myUrl,
        success: function( data ) {

        $("body").replaceWith(data); // Example!

        $(".icons", data).contextMenu({
            menu: 'menuIcons'                    
        }, function(action, el, pos) {
            contextMenuWork(action, el, pos); 
        }); 

        }
    });
})();

Upvotes: 1

Kevin B
Kevin B

Reputation: 95048

try this:

function contextMenuWork(action, el, pos) {
  switch (action) {
    case "open": {
      alert("open");
      break;
    }
  }
}
$(".icons:not(.live)").live('click',function(e){
  if (e.which === 2) {
    e.preventDefault();
    $(this).addClass('live').contextMenu({ 
      menu: 'menuIcons'                    
    }, 
    function(action, el, pos) { 
      contextMenuWork(action, el, pos); 
    }).trigger({type:'mousedown',button:2}).trigger({type:'mouseup'});
  }
});

it uses late binding to bind to the event when the element is right clicked; it then re-triggers the right click event.

Upvotes: 1

Gus
Gus

Reputation: 7349

$(document).live() doesn't really make sense, since there can only be one document and it can never be re-created without reloading the page.

You want to call:

$(document).ready(function() {...

If the document DOM object is already loaded, jQuery will call your function immediately.

Upvotes: 1

Related Questions