Calling JavaScript Functions - javascript

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

Related

Script is written dynamically with variables inside SRC, but it does not executes as when it's written statically

I've been trying to show a post list in Blogger that varies depending on the month/year. How this exhibition is dynamic, I need to pass these two values (month/year) to a variable inside <script> tag's src attribute – what I'm able to do –, but the script is not executed (even being written inside the HTML). Below, I write how the code works and what I've done until now:
<script>
function textospordata(json) {
// Here the commands that write a list with specific texts go.
}
</script>
<!-- The static script (with fixed values) works. The callback textsbydate() is executed and the texts are listed. -->
<script src="http://mysite.blogspot.com/feeds/posts/default?published-min=2019-05-01T00:00:00&published-max=2019-05-31T23:59:59&orderby=published&alt=json-in-script&callback=textsbydate"></script>
<!-- When it's written dynamically, the script is even created inside the page, but the callback isn't called and so the texts aren't listed. -->
<script>
const urlAno = '2019'; // Year example. The code to get it is another.
const urlMes = '05'; // Month example. The code to get it is another.
const srcUrl = 'http://mysite.blogspot.com/feeds/posts/default?published-min='+urlAno+'-'+urlMes+'-01T00:00:00&published-max='+urlAno+'-'+urlMes+'-31T23:59:59&orderby=published&alt=json-in-script&callback=textsbydate';
var script = document.createElement('script');
script.src = srcUrl;
document.getElementById('body-post').appendChild(script);
</script>
Besides what is inside the snippet, I've already tried to write the <script> tag using document.write("<script src='"+srcUrl+"'></"+"script>");. I've already also tried to insert the code inside a function and call it separately, and besides to try to use the onload and a script.async: false.
In every attempt, the <script> tag is written inside the HTML exactly how it should be written (<script src="http://mysite.blogspot.com/feeds/posts/default?published-min=2019-05-01T00:00:00&published-max=2019-05-31T23:59:59&orderby=published&alt=json-in-script&callback=textsbydate"></script>, like in the example), but the texts are not listed and nothing works when compared to when it is written in the static way.
And at last, I believe the soluction be to do the dynamic script be executed synchronously. I think it must be executed before page's DOM. I've tried to read some answers to similar questions here at S.O., but without success. And in addition, the console does not show any error about it.
What may be wrong in my code?

How Can I execute a PHP function inside a Script tag?

So I have as function for my css that looks like this
function include_css($css="") {
include(SITE_ROOT.DS.'includes'.DS.'stylesheets'.DS.$css);
}
And in the header I use this to call it
<style type="text/css"><?php include_css('public.css'); ?></style>
I would like to do a similar function to call a javascript file to load in ckeditor
function include_javascript($js="") {
include(SITE_ROOT.DS.'includes'.DS.'ckeditor'.DS.$js);
}
But this bit of code doesn't work
<script type="text/javascript"><?php include_javascript('ckeditor.js'); ?></script>
The tool bar doesn't show up when doing it this way. It will show up when I use the website.
<script src="//cdn.ckeditor.com/4.5.11/standard/ckeditor.js"></script>
Why doesn't this work the same way as the Style tag? Since this doesn't work is there a similar way to put PHP into a Script tag?
I put php code inside of script tags frequently for instance to set the initial value of a javascript variable. There is no particular issue with inserting php tags inside of a script tag.
Normally you would load javascript separately to speed page load like this:
<script src="/path-to_js/js-file.js" type="text/javascript"></script>
So something like this should work:
function include_javascript($js="") {
if ($js)
echo "<script src=\"/js-path/$js\" type=\"text/javascript\"></script>";
}
If you are trying to embed the javascript code into your html what you are doing ought to work. I noticed that you are setting a default value for your parameter. Make sure that something is actually passed and that the file actually exists. If the result is
<script></script>
then one of these is most likely the problem.

How to pass element ID variable to jQuery load function

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.

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?
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.

Getting content of a script file using Javascript

I have the following script element in my web page:
<script src="default.js" type="text/javascript"></script>
Using JavaScript, I want to be able to retrieve the content of the script file. I know I could use an ajax request to get the data but then I am getting something from the server that I already have locally.
So what I would prefer to do is retrieve the content from the DOM (if that's possible) or something that has the same result.
Cheers
Anthony
UPDATE
I was trying to simplify the question, maybe a bad a idea, I thought this way would cause less questions.
The real situation I have is as follows, I actually have
<script type="text/html" class="jq-ItemTemplate_Approval">
...
html template that is going to be consumed by jQuery and jTemplate
...
</script>
Now this works fine but it means each time the page loads I have to send down the template as part of the HTML of the main page. So my plan was to do the following:
<script src="template.html" type="text/html"></script>
This would mean that the browser would cache the content of template.html and I would not have to send it down each time. But to do this I need to be able to get the content from the file.
Also in this case, as far as I know, requesting the content via ajax isn't going to help all that much because it has to go back to the server to get the content anyway.
If I understand you correctly, you don't want to use Ajax to load an html template text, but rather have it loaded with the rest of the page. If you control the server side, you can always include the template text in an invisible div tag that you then reference from Javascript:
<div id="template" style="display:none;">
...template text...
</div>
<script>
// pops up the template text.
alert(document.getElementById("template").innerHTML);
</script>
If you are just looking for to load the template so that you can have it cached, you can put the contents in a variable like this:
<script>
var template = "template text..";
</script>
or you can load it using ajax and store the template in a variable so it is accessible. It's pretty trivial in jquery:
var template;
$.get("template.html", function(data){
template = data;
});
unless you load a script as literal text in the page, it does not exist as text. It is interpreted by the browser and melded into the runtime, with any other scripts.
If you want the source you have to fetch it again,if with Ajax get the responseText.
It will come from the browser cache, and doesn't have to be downloaded again.
I think what you want to do is to assign a variable inside template.js. Then you have the variable available for use wherever you want in jquery. Something like:
var tpl = "<div> ... </div>"
Wouldn't this be a simpler solution to your problem? We do this in Ext JS. I think this will work for you in jQuery.
You could get the attribute of the src of the script and then use XHR to get the contents of the JS file. It's a much cleaner way of doing it IMO. e.g.:-
if(window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.status == 200 && xhr.readyState == 4) {
var sourceCode = xhr.responseText;
alert('The source code is:-\n'+sourceCode);
}
}
xhr.open("GET",document.getElementById('scriptID').src,true);
xhr.send(null);
}
Using an iFrame & HTML5 Local Storage
Save the templates for rendering later...
not stoked about the iFrame, but it seems to be working pretty good (haven't ran performance tests yet)
Put the iFrame on the page you want the template on (index.html)
<html>
<head>
<iframe src="mustache.Users.html" onload="this.remove();" class="hidden" id="users_template"></iframe>
</head>
</html>
Make sure the src attribute is set
hide the element until you can get rid of it after it loads
Put this body wrapper around your template (mustache.Users.html)
(don't worry it won't show up in the template)
<body onload="localStorage.setItem('users_template',this.document.body.innerHTML);">
<ul class="list-group" id="users" >
{{#users}}<li>{{name}}</li>{{/users}}
</ul>
</body>
replace 'users_template' with whatever name for your variable
the 'onload' attribute saves the template into localStorage during load
Now You can access your templates from anywhere
localStorage.getItem('users_template')
OR
window.localStorage.getItem('users_template')
What is in the JavaScript file? If it's actual code, you can run functions and reference variables in there just like you had cut and paste them into the webpage. You'll want to put the include line above any script blocks that reference it.
Is this what your looking to accomplish?
Why not use Ajax (well Ajah because its html :-))?
when the server is set up correctly and no no-cache or past expires headers are sent, the browser will cache it.
The way that most JavaScript import files work is they include a script, that immediately calls a function with a parameter of certain text, or of another function. To better illustrate, say you have your main index.html file, set it up like this:
<html>
<head>
</head>
<body>
<script>
let modules = {};
function started(moduleName, srcTxt) {
modules[moduleName] = (srcTxt) //or something similar
}
</script>
<!--now you can include other script tags, and any script tags that will be included, their source can be gotten (if set up right, see later)-->
<script src="someOtherFile.js"></script>
</body>
</html>
now make that other file, someOtherFile.js, and right away when its loaded, simply call that "started" function which should already be declared in the scope, and when thats done, then whatever text is passed, from the file, is stored in the main index.html file. You can even stringify an entire function and put it in, for example:
started("superModule", (function() {
/*
<?myCustomTemplateLanguage
<div>
{something}Entire Javascript / html template file goes here!!{/something}
</div>
?>
*/
}).toString());
now you can access the inner content of the function, and get all the text in between the comments, or better yet, then do other parsing etc, or make some other kind of parsing identifiers at the beginning and end of the comments, as shown above, and get all text in between those

Categories

Resources