JQuery – Run script if!
When running a site with a boat load of javascript, you may want to run a script only if a certain something is on the page. Not only could this save on initial loading time, but more importantly if you have an element of one thing on one page and the same named element for something else on another. You don’t want your JQuery to do an action to that if it isn’t intended.
So. Run my enclosed script if! I read somewhere a while back on a nice way of determining if an element exists. Really simple and I definitely cannot take credit for this.
Let’s say you have a div on your index page you have some classes you want to change on page load. But on another page you have some more of those classes.
You could either have an entirely new javascript page for that page || you could do the following.
Create something with a unique id that you don’t plan on using elsewhere on your site, so maybe the page name. <body id=”myPageName”>
Then all you need to do for JQuery is the following:
if ($('#myPageName').length > 0){
//everything you want to run inside here.
}Got any other ideas that would work besides this? Please let me know!
Thank you very much for this hint, I’m a jquery newbie and this made my day!
It is really something new for me…seems interesting
By far the most concise and up to date information I found on this topic. Sure glad that I navigated to your page by accident. I?ll be subscribing to your feed so that I can get the latest updates. Appreciate all the information here
No Problemo!!!
is that easy?
love it,thanks for sharing.
p
Thank you very much for this hint. keep on posting like this examples
[...] JQuery – Run script if! « eligeske When running a site with a boat load of javascript, you may want to run a script only if a certain something is on the page. Not only could this save on initial loading time, but more importantly if you have an element of one thing on one page and the same named element for something else on another. You don’t want your JQuery to do an action to that if it isn’t intended. [...]
any length (!):
if ( $( ‘#element’ ).length ) {
//everything you want to run inside here.
}
oups )
if ( $( yourElementSelector ).length ){
// your beautiful code poetry
}
regards
Thank you, for helping me ^_^
I usually find it simpler to use something like this:
if(document.getElementById(’elementsID’)){
// code in here
}
This will only work with IDs, and there is no hash mark used, just the value in id=”" – this keeps from needing jQuery to process and convert the code to vanilla javascript – possibly negligible performance increase, but it should be faster than using jQuery functions – and of course all your jQuery can still go right inside of it
I think it perfect usage at some situation.