javascript - Function overwritting -
is there way overwrite function or event handling in function?
using addeventlistener, can have many event handlers on element want
var test=document.getelementbyid("div"); test.addeventlistener("click",function(){alert("im first");},false); test.addeventlistener("click",function(){alert("im second");},false); // alerts "im first" , after "im second"
but if want overwrite function/event example based on client width example this
function one() { alert("first"); } function two() { alert("second"); } window.onresize = function() { var test = document.getelementbyid("div"); if (window.innerwidth > 500) { test.onclick = 1 } else { test.onclick = two; } }
is possible in javascript?
in case use effective little known approach. addeventlistener can accept object property handleevent
event handler. in case it's easy overwrite handler function, set null
ot different function without messing removeeventlistener
, addeventlistener
again , again.
in case:
var test = document.getelementbyid("div"); var handlers = { handleevent: function () { alert("im first"); } }; test.addeventlistener("click", handlers, false); function one() { alert("first"); } function two() { alert("second"); } window.onresize = function() { if (window.innerwidth > 500) { handlers.handleevent = one; } else { handlers.handleevent = two; } }
check demo below, resize pane see how dynamically picks different handlers based on viewport width.
Comments
Post a Comment