Perform only jquery effects / operations on specific pages

So far, I have deleted all jquery code right inside the document.ready function. I think that for certain situations this is not the best way.

for example: If I want the animation to run when some page loads what is the best way to do this.

$(document).ready(function() { $("#element_1").fadeIn(); $("#element_2").delay('100').fadeIn(); $("#element_3").delay('200').fadeIn(); }); 

If this is correct inside document.ready, then every time the ANY page is loaded, it checks every line and looks for this element. What is the best way to tell jquery to execute only a piece of code on a specific page in order to avoid this problem.

+7
javascript jquery
source share
2 answers

checking if an element exists on the page before performing the animation

 if ($("#element-1").length) { $("#element-1").fadeIn(); } 

etc. with other elements #element_2 and #element_3


to @numediaweb:

current jQuery is() implementation looks like below

 is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, 

therefore, using is() can be smarter, but it’s faster to use only length and even faster to sue document.getElementById().length

+10
source share

Include only the code you want to execute when the DOM is ready for this particular page. $(document).ready(... does not mean that every page should have the same piece of code. This would require different checks to know what needs to be done.

I am sure that you will have common functions that you want to perform on each page, as well as some functions related to specific pages. If so, you can put common functionality in one function and call it from $(document).ready(... so that the only remaining code is specific to that particular page. For example:

 function common() { alert('hello'); } $(document).ready(function() { common(); // do some page-specific stuff }); 

I disagree with doing various checks on each page, so the code knows where we are. This seems cumbersome and completely preventable, for example:

 function doAnimation() { $("#element_1").fadeIn(); $("#element_2").delay('100').fadeIn(); $("#element_3").delay('200').fadeIn(); } $(document).ready(function() { if(window.location.href == 'http://example.com/foo') { doAnimation(); } if(this page has blah) { doBlah(); } }); 

Ideally, this should be:

 $(document).ready(function() { // do stuff for foo.php }); 
0
source share

All Articles