Search code examples
javascriptjquerydocumentcustom-events

javascript: document.dispatchEvent(CustomEvent) does nothing


I have the following chunk of code

$(function(){

    var TaskEvent = new CustomEvent('TaskAdded',{
        detail: {
            message:'A task fue ponida, champion'
        },
        bubbles:true,
        cancelable:true
    });

    var btn = $("#boton");

    function HandleSugar(e){
        console.log(e.detail.message);
    }

    btn.click(function(e){

        document.dispatchEvent(TaskEvent);
    });

    $(document).on('TaskEvent',HandleSugar);

})

When clicking in the button (#boton) nothing happens. Any idea?

Some clarifications:

  • The button is created, that is not the problem
  • The console shows no error at all, that's why I'm lost
  • The expected behavior is for the custom event 'TaskEvent' to be triggered, so when pressing the button the message will appear in console log.

Solution

  • You are listening for TaskEvent but the event is actually TaskAdded.

    $(document).on('TaskEvent',HandleSugar);
    

    should be

    $(document).on('TaskAdded', HandleSugar);