Reputation: 849
Can someone explain this to me. I have 1 js file on my site, using mainly jQuery, all my js code uses elements that are on all pages, EXCEPT for 1 js code that targets an element that is only on one page.
So when I go to that one page, I get no JavaScript errors, however when I go to any other page it gives me a $..Undefined
error for that element. I am using a .offset().top
code for that element. I'm assuming that's because if you only target an element that's on one page I should just include a script on that page alone and not put it in my js file??? Does that include all jquery functions or just something specific to using .offset()
and/or others? Is my assumption correct?
Upvotes: 0
Views: 292
Reputation: 48212
If you are trying to access a function of an element that is not there, you will get an error regardless of the function you are using.
Solutions:
Like you said, you can put the specific code in a separate .js file and include that file only in the appropriate HTML page.
You could check for the element's existence and only then proceed with manipulating it. E.g.:
var elem = document.getElementById("mySpecialElement"); if (elem) { /* Element exists, it is safe to manipulate it */ $(elem).offset()... }
Upvotes: 1
Reputation: 2865
What I like to do is write my js pages like so:
var initMyFunction = function(){
*code for initMyFunction*
};
var initMyOtherFunction = function(){
*code for initMyOtherFunction*
};
And then in my mark up I can call which function I want to run on that page, so long as I call it after I call my script.
<!-- Scripts -->
<script src="js/main.js"></script>
<!-- Inits -->
<script>initMyFunction();</script>
It has the benefit of only running the code you need ran on that page, instead of running all your js on every page.
Upvotes: 1
Reputation: 4810
As you suggested, you could put it in a <script>
tag in that page, however you could also simply check if the element exists before attempting to perform your operation.
Upvotes: 0
Reputation: 104775
Just put a quick check for that element in your JS file. Example, the element only on one page:
<span id="coolSpan">span stuff</span>
JS:
if ($("#coolSpan").length) {
//element exists, bind the handler
$("#coolSpan").click(function() {
console.log("I exist!");
});
}
Upvotes: 1