Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only perform jquery effects/operations on certain pages

Up until now i've been dropping all my jquery code right inside the document.ready function. I'm thinking that for certain situations this isnt the best way to go.

for example: If i want an animation to perform when a certain page loads what is the best way to go about that.

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

If this is right inside of document.ready then every time ANY page loads it's going to check each line and look for that element. What is the best way to tell jquery to only perform a chunk of code on a certain page to avoid this issue.

like image 211
Galen Avatar asked Apr 30 '10 16:04

Galen


People also ask

How call jQuery function only once?

jQuery one() Method The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run ONCE for each element.

Is jQuery slower for animations?

jQuery can be several times slower than CSS when talking about animations. CSS animations and transitions have the advantage of being hardware accelerated by the GPU, which is really good in moving pixels.

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.


1 Answers

by checking if elememt exist on the page before execute animation

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

and so on with other elements #element_2 and #element_3


to @numediaweb:

current jQuery is() implementation is like below

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

so, it can be smarter to use is() but it is faster to use just length and even faster to sue document.getElementById().length

like image 78
Luca Filosofi Avatar answered Oct 10 '22 01:10

Luca Filosofi