Calling a function of en external javascript file - asp.net

In general... How can I make a call on a function of an external java script file?
More specific...
In the head tag i have
<script type="text/javascript" src="JScript/FontSize.js"></script>
The external javascript file, (that i would like to call) FontSize.js contains the following functions.
function checkCookie()
function setCookie(c_name, value, expiredays)
function getCookie(c_name)
function increaseFontSize()
function decreaseFontSize()`
The FontSize.js is located at the ~/Jscript/ directory
I guess the body on load should contain something like
<body onload="/JScript/Fontsize.js/checkCookie()">
Of course nothing works as it should because, i do not know how to make the call to a function to an external js file

You just call it as if it were local :)
<body onload="checkCookie()">
Or, do it in script:
window.onload = checkCookie;
When you declare a function and it's not in another object/namespace, it's just globally available, and you can call it as if it immediately preceded your current code. By default these functions will be on the window object, you can see a short demo here.
For example (doesn't matter where this function's defined, external or not):
function myFunc() { alert('hi'); }
myFunc();
window.myFunc(); //same call, unless there's *another* myFunc in a local-er scope

<html>
<head>
<script type="text/javascript" language="javascript" src="main.js"></script>
</head>
<body>
<!--The extranal main.js file contains samp() function.. -->
<script>
<!-- samp(); -->
</script>
</body>
</html>

Related

Cannot load script in ViewComponent

I created a ViewComponent which display a Table that require some plugin for enable specific functionalities. Inside the ViewComponent I tried to create a specific section:
#section DataTableScripts{
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
unfortunately I discovered that a ViewComponent cannot load a #section.
So I tried to include the script directly in the ViewComponent, but the problem is that the scripts are loaded before of JQuery which is loaded inside the _Layout, specifically:
ViewComponent
<script src="~/js/JQuery/jquery.dataTables.js"></script>
<script src="~/js/JQuery/dataTables.buttons.min.js"></script>
<script src="~/js/JQuery/dataTables.keyTable.min.js"></script>
<script src="~/js/JQuery/dataTables.responsive.min.js"></script>
<script src="~/js/JQuery/dataTables.select.min.js"></script>
<script src="~/js/JQuery/dataTables.bootstrap4.js"></script>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
Layout
<script src="~/js/jquery.min.js"></script>
so in this case I'll get:
jQuery is not defined
How can I manage this situation?
Simply set the Layout for your ViewComponent .
#{
Layout = "/Views/Shared/_Layout.cshtml";
}
#section DataTableScripts{
<div>It works </div>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
Here's the screenshot that works :
[Edit]
This approach does not seems a good way to do that . As #Kirk Larkin says , this will make the Layout render twice . Another patch is to write a new RefinedLayout.cshtml and set the Layout of ViewComponent as the RefinedLayout :
#{
Layout = "_RefinedLayout.cshtml";
}
#section DataTableScripts{
<div>It works </div>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
For more information , refer workaround by MortenMeisler
You are using<script src="~/js/JQuery/jquery.dataTables.js"></script> twice. Just keep it once.
Specifying another layout for viewcomponents with scripts will duplicate scripts. And #section is just ignored during rendering.
So I replaced jquery document ready with plain javascript domcontentloaded and any jquery can be written inside domcontentloaded. Not a permanent good approach but works for me.
<script>
document.addEventListener('DOMContentLoaded', function (event) {
console.log($ === jQuery)
});
</script>

Semantic ui sidebar implementation

Hello how do i implement the sidebar from semantic ui? I would like to use the first example on the list.
http://semantic-ui.com/modules/sidebar.html#/definition
I tried copy-pasting the whole div section and putting it on my html
For the javascript(? not really sure), the
$('.left.demo.sidebar')
.sidebar('toggle')
;
i tried putting it on
button onclick , and
function then using href to call
but sidebar is not showing.. what am i doing wrong
You have to include the jQuery library in the <head></head> section of your page:
<script language="javascript" src="http://code.jquery.com/jquery.min.js"></script>
And the semantic.js file:
<script language="javascript" src="[your path here]/semantic.js"></script>
Which you have to download from:
http://semantic-ui.com/
(It's located inside the folder dist. Copy that file in the desire location and populate src with the right path)
BETWEEN <HEAD></HEAD>:
<script language="javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script language="javascript" src="[your path here]/semantic.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.left.demo.sidebar').sidebar('toggle');
});
</script>
When you add jQuery to your project you can trigger your sidebar by adding this code to your .js file:
$('.element.to.trigger.sidebar').on('click', function () {
$('.left.demo.sidebar')
.sidebar('toggle');
});

jQuery .Load and iis7

I am trying some AJAX calls for the first time. My site is hosted on my own IIS7, (http://myUserName:8078/HomePage.aspx).
Here is the jScript.
<script type="text/javascript" src="jQuery1.4.2.js"/>
<script type="text/javascript">
$(document).ready(LoadText);
function LoadText() {
$("#Content1").load("data.txt");
}
"content1" is a content place holder.
My IIS is set to .net 4 too.
My problem is that the data.txt contents is never loaded. It is in the same directory as the page. I haven't got much experience in IIS so I am wondering if I am missing a setting or something.
Thanks
You can't use a single-tag XHTML-style script tag for JavaScript. Change your first line to:
<script type="text/javascript" src="jQuery1.4.2.js"></script>
For some reason, the script tag can't be shortened down to just a single tag, you have to have separate opening and closing tags.
I recommend you pass the ClientID and file path into the function as arguments, but the code below should work:
<script type="text/javascript" src='<%= Page.ResolveUrl("~/jQuery1.4.2.js")%>'></script>
<script type="text/javascript">
$(document).ready(function() {
LoadText();
});
function LoadText() {
$("#<%= Content1.ClientID %>").load('<%= Page.ResolveUrl("~/data.txt")%>');
}
</script>
Is data.txt in the root folder of your site? If so, the .load() method takes a URL so try "/data.txt"
LoadText() is a function. Try:
$(document).ready(
LoadText();
);
Also I would suggest using lower camel case for function names. Upper camel case functions as in LoadText() suggests by convention that it is a contructor.
$(document).ready(
loadText();
);
You can also log something in the loadText() function to verify that it actually gets executed.
function loadText() {
$("#Content1").load("data.txt");
console.log('tried to load data.txt');
}

Is it possible to load Mootools in a parent frame and then re-use it in iframes?

Example
-- begin: index.html --
<!doctype html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="mootools.js"></script>
</head>
<body>
<iframe src="iframe.html" id="innerFrame">blah</iframe>
</body>
</html>
-- end: index.html --
-- begin: iframe.html --
<!doctype html>
<html>
<head>
<title>iFrame</title>
</head>
<body>
<form>
<input id="inputField" type="text" value="this is text." />
</form>
<script type="text/javascript">
$('inputField').set('value', 'updated text');
</script>
</body>
</html>
-- end: iframe.html --
Currently, $('inputField').set('value', 'updated text'); doesn't work :-\
Yes, assuming the iframe and it's parent window are on the same domain, it is possible to load the Mootools scripts once in the parent, and then programmatically extend the IFrame's window and document, instead of re-loading the script within the iframe. It is not the default behavior, as you've noticed, and probably for good reason - I'm guessing most people will tell you it's more trouble than it's worth.
In fact, the IFrame shortcut element constructor used to do that exact thing, but it was ultimately considered to be too much of a hack and not worth the effort to maintain as part of the framework long-term, so they dropped it - this why the documentation for IFrame is kind of odd ("IFrame Method: constructor, Creates an IFrame HTML Element and extends its window and document with MooTools.", and then right below after the example, "Notes: An IFrame's window and document will not be extended with MooTools methods.").
So, the most straightforward way to have $(..) useable in your iframe is just to have the iframe include the Mootools script. If you're feeling fancy, you could also have your parent window inject the Mootools script into the iframe's HEAD, for example:
index.html
<html>
<head>
<title>Parent</title>
<script type="text/javascript" src="mootools.js"></script>
</head>
<body>
<iframe id="innerFrame"></iframe>
<script type="text/javascript">
var mooFrame = new IFrame("innerFrame", {
src:"iframe.html",
events: {
load: function(){
var mooEl = new Element('script', {
type: 'text/javascript',
src: "mootools.js",
events: {
load: function(){
//passed to mooFrame by the iframe
this.pageReady();
}.bind(this)
}
});
this.contentDocument.head.appendChild(mooEl);
}
}
});
</script>
</body>
</html>
iframe.html
<html>
<head>
<title>Iframe</title>
</head>
<body>
<div id="iframe_element"></div>
<script type="text/javascript">
parent.mooFrame.pageReady = function(){
/* Put your iframe javascript in here */
$('iframe_element').set("text", "Fancy!");
};
</script>
</body>
</html>
Update (July 29th): I was fooling around with this idea again and realized there's a fairly obvious though pretty ham-fisted way to transfer Mootools functionality defined in the parent index.html window to the inner iframe: simply include the entire Mootools source into the parent window (remove the src attribute from the existing script element and add an id), and copy that newly enormous element's text into the new script node that gets injected into the head of the iframe. Inlining the Mootools code in the script element in this fashion gives you access to the contents of the element, which you don't get when the javascript is loaded from an external file via the src attribute.
Of course, this..concept is only relevant if the parent window and iframe are on the same-domain, (same as the code provided above).
The obvious drawback is that the Mootools source isn't cached. I'm not sure if there's a use-case where this method would be more optimal than just including mootools in both parent and iframe. In any event, change the index.html file to this:
<html>
<head>
<title>Parent</title>
<script type="text/javascript" id="mootools_js">
**COPY-PASTE THE CONTENTS OF mootools-core.js HERE**
</script>
</head>
<body>
<iframe id="innerFrame"></iframe>
<script type="text/javascript">
var mooFrame = new IFrame("innerFrame", {
src:"iframe.html",
events: {
load: function(){
var mooEl = new Element('script', {
id: 'mootools_iframe_core',
type: 'text/javascript',
html: $('mootools_js').innerHTML
});
this.contentDocument.head.appendChild(mooEl);
this.pageReady();
}
}
});
</script>
</body>
</html>
My previous answer offered two alternative ways of doing the task in question ("load Mootools in a parent frame and then re-use it in iframes"). The first method didn't "re-use" the Mootools functionality loaded into the parent frame, but was rather an alternative way to load the script in the inner iframe. The second method was just a hacky way of copying over the script by putting the entire mootools core source inline in a script element and then copying that element's content into a script element in the iframe's head (hardly optimal).
This following method does programatically extend the window and document objects of the inner iframe. Again, it is assumed that both the parent page and the iframe are on the same domain.
In my (brief and simple) testing, loading the source in both parent and iframe resulted in 72.1 KB transferred at around 130ms (to finish loading both the parent and iframe pages), while the page that loaded the source and then extended the iframe was 36.8 KB and took around 85ms to load both parent and iframe. (that's with gzip on the server...file size of uncompressed/unminified core source is around 134 kb).
For this method a few trivial additions/edits are made to the mootools core source. Download an uncompressed version of mootools-core-1.3.2.js, and rename it to 'mootools-core-init.js' (or whatever). The following steps assume that you checked all boxes on the core builder page except 'Include Compatibility'.
Add this to the top of the 'mootools-core-init.js' file (above the first self-calling anonymous function):
var initMootoolsCore = function(){
var window = this;
var document = this.document;
Add this to the very bottom of the core js file:
};
initMootoolsCore.call(window);
Do the following find/replace tasks:
1
Find:})();
Replace: }).call(this);
2
Find: if (Browser.Element) Element.prototype = Browser.Element.prototype;
Replace: if (this.Browser.Element) Element.prototype = this.Browser.Element.prototype;
3
Find: var IFrame = new Type
Replace: var IFrame = this.IFrame = new Type
4
Find: var Cookie = new Class
Replace: var Cookie = this.Cookie = new Class
(download | compressed version)
In your parent index.html file, put the following script element in the head
<script type="text/javascript" src="mootools-core-init.js"></script>
Finally, in your iframe.html file, put the following inline script element in the head to extend the iframe's window and document (it must be before any included or inline scripts that need to use Mootools):
<script type="text/javascript">parent.initMootoolsCore.call(window);</script>
No, the iframe.html is an independent page. It does not "inherit" anything from the previous page.

asp.net eval script in ajax html response

I'm using update panel, my response have some javascript like bellow. After a success response, I need to eval it, load it (with external script)
ex: my html response
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript">
alert('asd');
</script>
<div>test</div>
<div>blah blah blah</div>
I'm not sure whether this question is still important for you, however I will try to provide a reasonable answer below.
AJAX framework does not evaluate scripts which are returned via UpdatePanel calls. You have to re-attach external scripts to document, so that browser could request for them and evaluate all inline scripts. You can use a small module I have paste below.
var UpdatePanelEnhancer = function ()
{
var divSelector = '#liveArea';
function evaluateScripts()
{
$(divSelector).find('script').each(function ()
{
if (this.src)
{
$('body').append(this);
}
else
{
var content = $(this).html();
eval(content);
}
});
};
Sys.Application.add_load(evaluateScripts);
} ();
The weak part of it is that you have to provide a selector for the element where module should look for a scripts to evaluate ('liveArea' in example), although you can extend the module and provide some cinfiguration to it. Also, I would strongly recommend you to load external javascripts before. If you cannot do it for some reason you should additionally check whether script is already referenced or not to avoid necessary calls and potentially unexpected behaviors and errors .

Resources