Run jQuery code only in a specific div
jquery
Solution
Wrap the code in this:
if ( $('#component-homepage').length ) {
// code
}
the `.length` method returns the number of elements in the jQuery object, so as long as there is more than one element with this ID, this will translate to a Boolean value of `true`, and thus run the code.
Source(s)
.length - jQuery API
Problem
I have a homepage with the id component-homepage in the body. This page has a few animations in the footer, navigation and another element. These elements have the same name on all the other pages. I would like to execute the jQuery code (the js file will contain more then just this code) when the elements are in the #component-homepage. ``` // This could should be on all the pages $("nav li:last-child").addClass('last-child'); // This code should only be used when the id #component-homepage is in the body // Homepage navigatie fadeIn + contentblok animatie $('#content_home').hide(); $('nav').hide().fadeIn(1200, function(){ var result = $("#content_home").outerHeight(); $('#content_home_container').css({"margin-top": -Math.abs(result), "height": (result)}); $('#content_home').css({"margin-top": (result),"display":"block"}).animate({marginTop: '0px'},1000); }); // Homepage navigatie animatie + url click event $('nav a').click(function(event){ event.preventDefault(); var href = this.href; $('nav').animate({ marginTop: '-635px'}, 1000, function(){ window.location = href; }); $('footer').fadeOut(200); }); ``` I tried wrappen the code in this: ``` $('#component-homepage').ready(function(){ // code }); ``` But it does not seem to work.