Tuesday, 15 May 2012

jquery - create page specific JavaScript while keeping it all in one global JavaScript file? -



jquery - create page specific JavaScript while keeping it all in one global JavaScript file? -

i have javascript file included every page of site.

i have code below part of file. code meant work on 1 specific page , not work on other page of site.

so when viewing other pages of site console window show error message:

uncaught typeerror: cannot read property 'top' of null

this sort of problem run often, way wrap code below prevent error showing on other pages of site not have dom elements looking for?

is possibble wrap code block function , phone call function on page needed somehow while keeping al in 1 global javascript file?

// add together fixed header bar on tasks edit view "save" button var edittaskfixedheaderbar = $('#task-edit-heading-row-labels'); var fixmetop = edittaskfixedheaderbar.offset().top; $(window).scroll(function() { var currentscroll = $(window).scrolltop(); if (currentscroll >= fixmetop) { edittaskfixedheaderbar.css({ position: 'fixed', top: '0', left: '10' }); } else { edittaskfixedheaderbar.css({ position: 'static' }); } });

wrap code in if statement checks see if element exists:

if ($('#task-edit-heading-row-labels').length > 0) { // element exists... set code here. }

basically $(...) return, without error, regardless of found; if found nothing, .length property equal zero. writing if ($(...).length > 0) neat way handle page-specific stuff, or situation aren't sure if content exists or not, without having tag pages classes or parse url, etc.

javascript jquery

No comments:

Post a Comment