Yax
Yax

Reputation: 2189

Page Specific JavaScript Function on Several Files of HTML

I have about 10 pages of HTML and each has a link to indexJS.js. I have a function loadMoreOnScroll() in the js file that is meant to run only for my index.html. But the loadMoreOnScroll() is run on all the pages as users scroll to the bottom.

How do I restrict loadMoreOnScroll() to only run for index.html?

Upvotes: 0

Views: 71

Answers (4)

Dee
Dee

Reputation: 36

I'm assuming you're invoking loadMoreOnScroll from within your indexJS.js file, correct?

If so, the solution is to remove the function call from your javascript file and instead call it directly from index.html.

indexJS.js

// Create the function but don't call it here
function loadMoreOnScroll(){...}

index.html

<script src="indexJS.js></script>
<script>
    // call the function
    loadMoreOnScroll();
</script>

Edit:

A few other people suggested adding a body class and targeting your page that way. This approach is fine, and may work well in many scenarios but just keep in mind two things:

  1. This works well for if you need to call your function on only one or two pages. Any more and you'll have to maintain a growing list of body classes within indexJS.js.

  2. Using the body class as a hook decouples the function call from the page that its applies to.

In other words, the body class will have functionality tied to it that's not immediately obvious if you're only looking at the HTML. If you're working on the code yourself, you'll probably be ok, but in a team environment, it could be error-prone. (Or if you revisit the code after a few months). It all depends on the scope of your project.

Upvotes: 0

Tymek
Tymek

Reputation: 3113

Add classes to distinguish pages.

<body class="index">...

And with JavaScript:

if(document.body.className.match(/\bindex\b/)){
    // code
}

of jQuery:

if($("body").hasClass("index")){
    // code
}

Upvotes: 1

ron tornambe
ron tornambe

Reputation: 10780

You can just remove the loadMoreOnScroll() function from indexJS and create a new JavaSscript file with loadMoreOnScroll() in it. Be sure to include a reference to the new file in the index.html.

Upvotes: 1

Shan Robertson
Shan Robertson

Reputation: 2742

Add a class to the body tag on the index then in javascript you can do something like

if(document.querySelector('body').className === 'myclass'){
 loadMoreOnScroll();
}

Note: this assumes you have no other classes on the body. You could use a data attribute and do getAttribute('data-page') or something to similar effect.

Upvotes: 1

Related Questions