Hi all
I have a small jQuery snippet which finally works, I have this code within a global js file which triggers on every page. How can I make it run only when it finds the correct ID?
I would like to run the below only with the page that has the page ID of #listings
$('.placeholder').before('<div class="napp"><img src="images/napp.png"></div>');
I’m working with other peroples code and came across, below, which has all different snippets running for that page under different self.initialize. Example: self.initializeArticle, self.initializeFrontage and so on.
self.initializeFrontpage = function() {
$('.placeholder').before('<div class="napp"><img src="images/napp.png"></div>'); // example
}
How can I add my own self.initialize? What does it mean? And where does the Frontpage, Article come from?
Many thanks,
Barry
Hi there,
I would like to run the below only with the page that has the page ID of #listings
Could you elaborate on this?
Where should the id occur?
Do you mean in the url, e.g. http://mypage.com#listings, or do you mean when an element with an id of #listings is present on the page?
Yes Pullo
when an element with an id of #listings is present on the page
ID or a class which will on the body tag.
Keep in mind I might need to add multiple classes overtime if I decide to use this on other pages.
<body id="listings">
?
Thanks
Hi,
Then you just need to get a reference to ‘#listings’ and check it’s length property to see if it exists on the page:
if ($('#listings').length){
$('.placeholder').before('<div class="napp"><img src="images/napp.png"></div>');
}
Great!
I was doing some searching myself and what you have posted confirms 
if ($("#listings")[0]){
$('.placeholder').before('<div class="napp"><img src="images/napp.png"></div>');
}
Is one better that the other? Whats the difference?
if ($('#listings').length){
// or
if ($("#listings")[0]){
Cheers,
Barry
The using the length property seems to be the preferred way to test whether an element exists on a page, but essentially they both do the same thing.
$(“#listings”)[0] will return the actual element that was matched.