javascript - Disable event handler below a certain viewport width -
i'm trying disable script when window width less 700px. have looked @ advice on other posts nothing has work of yet.
window.onresize = function () { if(window.innerwidth < 700) { $(window).bind('scroll', function() { if ($(window).scrolltop() > 100) { $('#projectinfo').hide(); } else { $('#projectinfo').show(); } }); } }
the problem never unbind event handler once has been attached window. suggest not bind scroll event handler every time window.resize
event triggers, because extremely costly event performance-wise. also, keep rebinding existing handler which, if works @ all, still horribly bad practice.
what want decide on document.ready whether attach scroll handler or not. if resize use case relevant (web users don't ever resize browser window while viewing specific page, it's web frontend developers keep doing check responsiveness of work), first test if scroll handler attached window
, add if not and (&&) window.innerwidth >= 700
. otherwise, check again if scroll handler exist, , unbind in case exists and window.innerwidth < 700
.
also, please note can name events when binding using event.name
syntax when declaring binding. find in jquery docs herefor:
using namespaces
instead of maintaining references handlers in order unbind them, can namespace events , use capability narrow scope of our unbinding actions. shown in discussion
.bind()
method, namespaces defined using period (.
) character when binding handler:$("#foo").bind("click.myevents", handler );
when handler bound in fashion, can still unbind normal way:
$("#foo").unbind("click");
however, if want avoid affecting other handlers, can more specific:
$("#foo").unbind("click.myevent");
we can unbind of handlers in namespace, regardless of event type:
$("#foo").unbind(".myevent");
it particularly useful attach namespaces event bindings when developing plug-ins or otherwise writing code may interact other event-handling code in future.
Comments
Post a Comment