addeventlistener - How to trigger JavaScript custom events correctly -


i struggling understand how custom event type linked specific user action/trigger. documentation seems dispatch event without user interaction.

in following example want event dispatched once user has been hovering on element 3 seconds.

var img = document.createelement('img');img.src = 'http://placehold.it/100x100'; document.body.appendchild(img) var event = new customevent("hoveredforthreeseconds");  img.addeventlistener('hoveredforthreeseconds', function(e) { console.log(e.type)}, true);   var thetrigger = function (element, event) {     var timeout = null;     element.addeventlistener('mouseover',function() {         timeout = settimeout(element.dispatchevent(event), 3000);     },true);     element.addeventlistener('mouseout', function() {         cleartimeout(timeout);     },true); }; 

i have trigger no logical way of connecting event.

i thinking creating object called customeventtrigger customevent has third parameter trigger , creating method called addcustomeventlistener, works same addeventlistener when initialised passes target element custom event trigger dispatches event when it's instructed to.

custom events have triggered programatically through dispatchevent, not fired dom. need explictly call them in code, such in response user-generated event such onmouseover, or change of state such onload.

you're close working implementation, you're invoking dispatchevent in settimeout. if save closure (as below) can invoke dispatchevent while passing element after settimeout has finished timeout.

it's practice declare variables @ top of file, avoid possible scope issues.

var img = document.createelement('img'), timeout, event, thetrigger;  img.src = 'http://placehold.it/100x100'; document.body.appendchild(img);  img.addeventlistener("hoveredforthreeseconds", afterhover, false);  thetrigger = function (element, event) {     timeout = null;     element.addeventlistener('mouseover',function() {       timeout = settimeout(function(){ element.dispatchevent(event) }, 3000);     },true);     element.addeventlistener('mouseout', function() {         cleartimeout(timeout);     },true); };  function afterhover(e) {     console.log("event called: " + e.type); }  event = new customevent("hoveredforthreeseconds");  thetrigger(img, event); 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -