0

I want to create customEvent. For example i have some elements,and every one is listening to this event. When i click on one of them i want to trigger my customEvent. How to make this?

Example:

var customEvent = new Event('customEvent');

var $ul = $('ul');

var $markers = $('#map').find('.markers');

// UL>LI
$ul.delegate('click', 'li', function(){
    customEvent.trigger();
});

$ul.delegate('customEvent', 'li', function(){
    $ul.find('li').removeClass("active");

});

// MAP MARKERS
$markers.on('click', 'li', function(){
    customEvent.trigger();
});

$markers.on('customEvent', function(){
    // do sth
});

1 Answer 1

3

Its simple, you need to use .trigger() function

Execute all handlers and behaviors attached to the matched elements for the given event type.

Script

ele.on('click', function() {  
      $(this).trigger('customEvent');
      //Or, $(this).trigger(customEvent); 
});
Sign up to request clarification or add additional context in comments.

5 Comments

Will it trigger this event only on this element or on all listeners?
It will trigger on only current element, if you want to trigger on all element use ele.trigger('customEvent');
But i have many diffrence elements, im not stroing them into one variable. I can use ele.trigger(), but i will need to write it ele1.trigger(), ele2.trigger(). I dont want do that. Is it posible to trigger event as self?
@Sko You should provide concrete sample on what is your expected behaviour. Why would you want to trigger a custom event if it is not specific to any element but all? Why not calling a function? Does it help: stackoverflow.com/a/6860214/1414562?
@Sko i see $.event.trigger('customEvent'); no more working for jq 1.9+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.