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?
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
}
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.
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.
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:
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.
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.
Related
What my code does:
It switches out the class of a div when i push a button. So i can push a button and the class changes from "Class" to "SwitchToThisClass" which has a different set of properties.
<script src="JS/SideNav-ShowOrHide.js"></script>
Here is my code, how do i change it so i can put parameters in and i also want to use the same JS file to change multiple classes:
(function() {
var bodyEl = $('body'),
navToggleBtn = bodyEl.find('Class');
navToggleBtn.on('click', function(e) {
bodyEl.toggleClass('SwitchToThisClass');
e.preventDefault();
});
})();
For example like this code that takes parameters and is clean, i want to be able to use the same JS file with different parameters. I want to switch out 'Class' and 'SwitchToThisClass', and take parameters instead.
HTML:
<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>
Outside JS file:
<script>
function getSyncScriptParams() {
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript;
return {
width : scriptName.getAttribute('data-width'),
height : scriptName.getAttribute('data-height')
};
}
</script>
Hope this makes sense, thanks for the help in advance.
In your purpose what you propose does not make much sense since there are better ways and more accessible and that will also allow you to modularize functions and pass parameters. However you have the possibility to add custom attributes to HTML tags if it is your final decision.
As you continue editing your question I continue editing my answer so.
Solution using data HTML attribute. and data HTML attribute documentation.
I personally do not like use it for script tag and I can not recommend it way.
Why? Because your source is a file not a function. A file have not parameters (said in some way). 'Visual' HTML tags/elements or stuff that is structure of the page is more related with this data binding. Unless your intention is to manipulate the tag itself in the first instance. What I think is never.
I would never use it to pass parameters to a contained function in the file.
Of course I am here giving my opinion. The solution exist.
Also you are facing old browsers support in your case.
What I understand you want have some static values in specific html file used to pass throught to a JS function contained in a JS file.
What you can do is first import your JS file that contains your JS function:
<script src="JS/SideNav-ShowOrHide.js"></script>
We suppose you have a function I have call 'changeFunction' in this file. Your function need to have some input parameters and then you can do from your HTML inmediatly after your file import.
<script>
var classFrom = "class1";
var classTo = "class2";
changeFunction(classFrom, classTo);
</script>
or directly:
<script>
changeFunction("class1","class2");
</script>
By other hand if what you need is manage classes of specific items give a look to how to add/remove classes from raw JS
I am fairly new to Jquery and HTML so please bear with me. I have my index.html with a call to jquery-1.9.1.min.js and I want to create a script that would load an outside html file. Index.html is a fairly long file so I want to break up the section for cleaner code and make it easier to modify.
<html class="no-js">
<main>
<section id="testLoad"></section>
</main>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script>$("#testLoad").load("test.html #part-1"); </script>
</body>
</html>
As you can see from the code above it loads the html file fine. What I want to do is set "#part-1" as a variable so that I can call the load script again but call a different ID from another part of the file.
I would also be open to different methods aside from this load function. All I need is to call an external html file (there are about 30 different sections) so it can display that sections data. If I do it this way is there a way to create a header file so that all of these section can have access to the same style sheet?
You'd put your load function inside a named function and pass in an argument:
function loadStuff(divId) {
$("#testLoad").load("test.html #" + divId + '');
}
In your event handler you'd call it:
$(document).ready(function() {
loadStuff('someId');
});
You could also pass in the target ID in a similar manner.
As others have pointed out, this isn't the ideal way to do what's essentially client-side templating.
It seems like you want to be able to combine multiple different "partial" html files, and for this I would recommend you look into Angular which excels at exactly this.
Not sure why you are loading the JQuery js file the way you are. That really doesn't look safe.
Another thing you can do is create an "iffy" as some people call it where it is a script that is automatically called when the page is loaded.
<script>
(function (){
//code goes here
}())
</script>
This code will run when that page is loaded.
One often have form with some dynamic parts, that needs to be initialized onload. E.g. datepickers, enhanced selects, section toggling, hiding/showing conditional elements etc.
Example:
<form>
<input type="text" name="date">
<select name="selection"></select>
</form>
and I want to init datepicker on the date element and Select2 on the selection element.
Where to put the form initialization?
My thoughts:
Init throught global selector:
$(function() {
$('input[name=date]').datepicker();
$('select[name=selection]').select2();
})`.
But I have one js file for the whole web, so this would led to crawling the whole DOM on each page load, even if the element is not present on current page.
Some kind of conditional selector. E.g. give <body> and id and add to my global js file something like this: $(function() { $('input[name=date]', 'body#foo').datepicker(); })
Encapsulate the init for each form into a function (or class method), and call the function from HTML:
<script type="text/javascript">
$(document).ready(initMyForm());
</script>
But I'm guessing, isn't there any better way? What would you suggest, especially for bigger projects with many different forms requiring different javascript initialization?
If for your current project you are running one JS file, or even for medium-size projects where a 'generic' form setup function is appropriate, using a function as you described would be appropriate.
See example below, with the function wrapped as a small jQuery plugin, so you can call this on specific selectors as required, to avoid running through the whole DOM.
;(function($){
$.extend({
initMyForm : function(){
$(this).find('input[name=date]').datepicker();
$(this).find('select[name=selection]').select2();
}
});
})(jQuery);
So you can use this like:
$(document).ready(function(){
$(body).find(form).initMyForm();
});
$("#my-form").initMyForm();
$(".page-content .form").initMyForm();
I am trying to call some javascript functions which I ahve written in some file. Eg.
function OpenPopup() {
alert("OpenPopUp");
return false;
}
when I call this from button from OnClientClick = "OpenPopup()" it is not called but when I put this function on MasterPage it is able to call the function.
I added this is the MasterPages's Head
<script src="Scripts/something.js" type="text/javascript"></script>
Please let me know what can be the possiblities why it is not called.
There should be a ContentPlaceHolder in the pasterpage, in the head section with an id 'head'. You should place a Content tag in the slave page referring to that 'head' section place holder and place this script reference inside that. This way, the < script > tag is placed inside the < head > tag.
You might have given wrong scr for script file.just drag the file path in your master page.Doing so you will get the accurate path for file.
From what I gather from your question, your function call now works with the <script> tag in place, and you are unsure why the tag is necessary.
If you write your javascript function in a file, say "script.js" and then attempt to call the function in an ASP.NET page, the ASP.NET is not aware that script.js exists.
The <script> tag is letting your ASP.NET page know to include the file script.js so that any functions and variables defined in that file can be used. By putting the <script> tag in your MasterPage, you are including it in every page on your site. A better idea might be to include the <script> tag only on the pages in which you intend to use the javascript functions.
I tried using this and it worked
I don't know why but I checked with putting the absolute path instead of relative path and it worked. Thing is I chnaged it to While refrencing to the CSS is working fine with that relative path. I have no clue why it is happening
I want to give a static javascript block of code to a html template designer, which can be:
either inline or external or both
used once or more in the html template
and each block can determine its position in the template relative to the other javascript code blocks.
An example could be image banners served using javascript. I give code to template designer who places it in two places, once for a horizontal banner in the header and once for a vertical banner. The same code runs in both blocks but knowing their positions can determine if to serve a horizontal or a vertical image banner.
Make sense?
Another example: Say you have the same 2 javascript tags in a web page calling an external script on a server. Can the server and/or scripts determine which javascript tag it belongs to?
NOTE: Can we say this is a challenge? I know that I can avoid this puzzle very easily but I come across this on a regular basis.
JavaScript code can locate all <script> elements on the page and it can probably examine the attributes and the content to check from which element it came from. But that's probably not what you want.
What you want is a piece of JavaScript which replaces tags on the page with ad banners. The usual solution is to add a special element, say a IMG, for this and give that IMG an id or a class or maybe even a custom attribute (like adtype="vertical") and then use JavaScript to locate these elements and replace the content by changing the src attribute.
For example, using jQuery, you can should your images like so:
<img src="empty.gif" width="..." height="..." class="ad" adtype="..." />
Then you can locate each image with
$('img.ad')
[EDIT] Well, the server obviously knows which script belongs into which script tag because it inserts the script. So this is a no-brainer.
If the script wants to find out where it is in the DOM, add something which it can use to identify itself, say:
<script>var id= '329573485745';
Then you can walk all script tags and check which one contains the value of the variable id.
If you call an external script, then you can do the same but you must add the ID to the script tag as you emit the HTML:
<script id="329573485745" src="..." />
Then the external script can examine the DOM and lookup the element with this id. You will want to use an UUID for this, btw.
This way, a piece of JS can locate the script tag which added itself to the page.
Best thing would probably be to make an insert once function, and then have him insert only the function call where needed.
Like this:
timescalled=0
function buildad(){
var toinsert="" //Code to generate the desired piece of HTML
document.write(toinsert)
timescalled+=1 //So you can tell how many times the function have been called
}
Now a script block calling the function can simply be inserted wherever a banner is needed
<script type="text/javascript">buildad()</script>
Thanks for the tips everyone but I'll be answering my own question.
I figured out several ways of accomplishing the task and I give you the one which works nicely and is easy to understand.
The following chunk of code relies on outputting dummy divs and jQuery.
<script>
// Unique identifier for all dummy divs
var rnd1="_0xDEFEC8ED_";
// Unique identifier for this dummy div
var rnd2=Math.floor(Math.random()*999999);
// The dummy div
var d="<div class='"+rnd1+" "+rnd2+"'></div>";
// Script which :
// Calculates index of THIS dummy div
// Total dummy divs
// Outputs to dummy div for debugging
var f1="<script>$(document).ready(function(){";
var f2="var i=$('."+rnd1+"').index($('."+rnd2+"'))+1;";
var f3="var t=$('."+rnd1+"').length;";
var f4="$('."+rnd2+"').html(i+' / '+t);";
var f5="});<\/script>";
document.write(d+f1+f2+f3+f4+f5);
</script>
Why not not just place the function call on the page instead of the entire code block? This way you can pass in a parameter to tell it what type of advertisement is needed?
BuildAd('Tower');
BuildAd('Banner');
Javascript itself has no clue of it's position in a page. You have to target a control on the page to get it's location.
I don't think it is possible for JavaScript code to know where it was loaded from. It certainly doesn't run at the point it is found, since execution isn't directly tied to the loading process (code usually runs after the whole DOM is loaded). In fact, in the case of externals, it doesn't even make sense, since only one copy of the code will be loaded no matter how many times it is encountered.
It shouldn't be the same code for each banner - there will be a parameter passed to whatever is serving the image banner which will specify the intended size.
Can you give a specific example of what you need this for?
To edit for your recent example: The simple answer is no. I could help you approach the problem from a different direction if you post details of your problem
The term "static block of code" leaves a lot of room for interpretation.
Inline scripts (e.g., ones that rely on document.write and so must be parsed and executed during the HTML parsing phase) cannot tell where they are in the DOM at runtime. You have to tell them (as in one of the first answers you got).
I think you'll probably find that you need to change your approach.
A common way to keep code and markup separate (which is useful when providing tools to HTML designers who aren't coders) is to have them use a script tag like so:
<script defer async type='text/javascript' src='pagestuff.js'></script>
...which then triggers itself when the page is loaded (using window.onload if necessary, but there are several techniques for being triggered earlier than that, which you want because window.onload doesn't trigger until the images have all loaded).
That script then looks for markers in the markup and manipulates the page accordingly. For instance (this example uses Prototype, but you can do the same with raw JavaScript, jQuery, Closure, etc.):
document.observe("dom:loaded", initPage);
function initPage() {
var verticals = $$('div.vertical');
/* ...do something with the array of "vertical" divs in `verticals`,
such as: */
var index;
for (index = 0; index < verticals.length; ++index) {
vertical.update("I'm vertical #" + index);
}
}
The designers can then have blocks on the page that are filled in by code which they flag up in a way that's normal for them (classes or attributes, etc.). The code figures out what it should do based on the classes/attributes of the blocks it finds when it runs.