Creating a reusable javascript function instead of copy/paste - javascript

I made a page I need to have in different instances. In short it is used to fill in different parts of a script and then display said script on the page for the user to copy it.
This script below handles the main part of the job, getting a field from HTML and then i can call the result in html to be displayed.
var urlField = document.getElementById('urlField').value;
var resultUrl = document.getElementById('resultUrl');
resultUrl.textContent = urlField;
Problem: there are different fields, eg. url, startdate, enddate, adschedule, etc. so I would like to have a reusable script that just says get the respective field and result the value which is assigned to it in html.
Can I do this somehow? I was researching the function "this" in javascript, but it is too complicated for my current knowledge. Bear in mind that I am in only a very basic level.
You can find the whole codepen to understand the issue better here: https://codepen.io/kmb5/pen/GxZbZq

Add parameters to your re-usable function and then call it whenever you need to use it. Use javascript to get the required data and pass it in as parameters.
reusable.js:
function myFuncWithParameters(parm1, parm2, parm3){
}
Alternatively:
function myFuncWithParameters(myObject){
//access properties from the object: myObject.parm1, myObject.parm2, myObject.parm3
}
Using the object route might make it easier since the order of the properties will not matter like parameters. Regardless of either method you will have to validate the input.
In your html pages, you will need some More JavaScript and HTML to bring in the JS and call it.
<html>
<head>
<title>my page</title>
<script scr="path to reusable js"></script>
<script src="path to this path's js"></script>
</head>
<body>
my page
</body>
</html>
If you look at the script tags, by importing the reusable js you can use it in javascript that was written / imported further down into the page.
In order to ensure you have access to an imported function, you can check if the function you need is defined:
if(typeof(myFuncWithParameters) !== 'undefined' && typeof(myFuncWithParameters) == typeof(Function){
//myFuncWithParameters will definitely be defined and is a function, if we get in here
}else{
//myFuncWithParameters is not defined and/or is not a function
}
In your html page to call the re-usable function...
var parm1 = value;
var parm2 = value;
var parm3 = value;
myFuncWithParameters(parm1, parm2, parm3);
In you decide to use the object:
var myObject = {
'parm1' : 4,
'parm2' : 6
}
//myObject.parm1 == 4
myFuncWithParameters(myObject);

Related

Trying to access a model object inside a script tag

I'm using Asp.Net Core and trying to reference the model from inside a script tag:
<div>
<script>
function calcprices() {
#Model.Price = document.getElementById("price").value;
}
</script>
<button onclick="calcprices()">Recalculate</button>
The error showing in console window is:
ReferenceError: calcprices is not defined
If I have a look at the debugger, it shows the particular section is missing the Model reference:
function calcprices() {
= document.getElementById("price").value;
}
So I'm guessing that's why I'm getting an error. Is it not possible to reference a model like this?
It's not possible to reference your model that way. In Razor, the C# and #Model.x elements are executed as the page is run and outputs are rendered as plain text.
If your #model.Price had a value (say 10 for example) it would be rendered on screen like this:
function calcprices() {
10 = document.getElementById("price").value;
}
You can use them as static values in your javascript (something we've made extensive use of) but you cannot address them as objects.
I'd suggest, if you're trying to update an object in session, use ajax to call a JsonResult method, post your data and return the output in the Json result.

How to redirect to a play framework url from within javascript without hard-coding the url

I need to do something seemingly quite simple.
In the same way that I can, from my scala.html file, create a link to another url, /entry, I need to do that from a javascript file.
i.e., from the scala.html:
<div class="footer">
<a href='#routes.Application.index()'>Home</a>
</div>
from my javascript event:
function() myEvent {
window.location="#routes.Application.entry()"; // DOESN'T WORK!
}
For routing from javascript, I've already had to setup my javascript routes for some ajax work I've already had to do.
My ajax work was calling a method 'findPersons()' so in my Application.java file, I had already:
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter( "appRoutes",
routes.javascript.Application.findPersons()));
}
Because I want to be able to redirect to my GET entry() method, I modified it to look like this:
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter( "appRoutes",
routes.javascript.Application.findPersons(),
routes.javascript.Application.entry()));
}
Additionally I have these in my routes file:
GET /entry controllers.Application.entry()
POST /findPersons controllers.Application.findPersons()
When I am invoking my findPersons method, it is really nice and simple.
It looks like this:
appRoutes.controllers.Application.findPersons().ajax({
data: {
personIdentifier : personIdentifier,
surname : surname,
givenNames : givenNames
},
success : processDBQuery
});
For my simple redirect, I would like to be able to maintain the same loose coupling between my html/javascript code and the urls, as I can the ajax call above.
My redirect needs to occur on an event. Therefore, the easiest and quickest solution would have been simple to write:
function() myEvent {
window.location="/entry";
}
However, then I would be hard-coding the URL (which I have managed to avoid for my ajax call above), no longer maintaining that loose coupling I would so much like to have.
However, I see no examples in the documentation, and from what I have in the generated javascript (for my routes) there is no chance.
Is there any way to achieve what I am after?
thanks for reading!
p.s., I should add; I guess I have also thought of the possibility of using the ajax call that is generated, I guess I can probably fetch the page I want... and there is probably a means of replacing the current document with the entire content of the fetched page. but that just sounds bad.... wrong...
or not?
I was rather hoping for a substitution, as is done in my html
i.e, my link as shown above is generated to look like this:
<div class="footer">
<a href='/'>Home</a>
</div>
In the same way, I hoped there was some means of substitution in the javascript, so that the event function above ends up in being massaged into looking like this:
function() myEvent {
window.location="/entry";
}
Jacques, from the above comments, helped me to realize a work-around.
From within my "assets located" javascript file, I can still refer to page/template located javascript.
Own-file/assets located javascript doesn't seem to be transformed how I expected.
However, Page/template located javascript is transformed exactly how I require.
I can refer to a template located javascript function from my assets located javascript.
This means, I have a little work-around of one extra little function inside the template which does the redirection for me.
i.e.,
myJavascript.js:
function personResultsListClickHandler(personId) {
var fpersonId = personId;
return function() {
window.alert("hello! " + fpersonId);
affectRedirect();
};
}
myTemplate.scala.html
#main("person lookup") {
<script type="text/javascript">
function affectRedirect(){
window.location="#routes.Application.entry()";
} // Need this here so it will be transformed.
// asset located javascript doesn't seem to get transformed like javascript here in template! :(...
</script>
Another possibility is the fact that the Javascript object retrieved by calling:
appRoutes.controllers.Application.entry()
contains a url member. This url member is exactly what I can use to assign to window.location. However, it looks a bit unofficial.. in terms of
1. the member not being documented
2. not sure if the url member will exist in the future
3. the generated javascript is constructing an object dealing with ajax... and i'm just grabbing the URL member from it... it just feels... like a hack.
But i've tested this, and it works. See code below:
function patientResultsListClickHandler(personId) {
var fpersonId = personId;
return function() {
window.location=appRoutes.controllers.Application.entry(personId).url;
// window.location="/entry/" + fpersonId; // the sort of hard-coding of URL that
}; // I wanted to avoid, but don't seem able to.
}
Does anyone else have a better solution?

What is the standard workaround for dynamic js files

Is there a standard workaround for something like this in ASP.NET:
//myinclude.js
$(document).ready(function() {
for(recs=0; recs < {{server-side-value}}; recs++) {
// process records
}
});
Note this is a js file. I know about WinForms ability to insert dynamic quoted scripts into the page. But how about a page's js file that is dependent on server-side values? I know you can use something like:
//myview.cshtml
var instance = new MyObject(<%= ServerSideValue =%>);
and include it on the page to pass it to the js file, but I'm wondering about the architecture of keeping js separate from html code so that an html/css designer can work with the template free of javascript; keeping everything separate. I primarily use MVC now.
What are some of the patterns to deal with this? Is the only solution dynamically inserting js into the actual page or having partial views included separately into the page.? Or is there a way to sprinkle server-side values in separated js? In short, no dynamic js files?
I'm not trying to fix an exact project at this time, I have just been curious about this on past projects.
Thanks...
There are multiple ways to achieve this. One of the ways would be populating your data into a Javascript objects on the HTML page directly.
//myview.cshtml
<script>
var pageData = {
name : '#variable1',
value1: #value1
};
</script>
And, in the javascript file:
//pageUI.js
if (pageData) {
$('#page_tile').html(pageData.name);
}
I am sure you can optimize a whole lot (for example, having a single communication between the server side data and the client side code). At the end of the day, you want to make sure that your javascript code can be resusable.
for example one can do this:
A. have the main .js code read any context-specific parameters from the current window like this (page.js):
!function(window){
var configData = window.MyAppNameConfigData;
// rest app code here..
}(window);
B. the server side script can inject these context-specific data in the page's html like this:
<script>
window.MyAppNameConfigData = {
param1: //..
param2: //..
// etc..
};
</script>
Note if needed make sure that the page.js is enqueued/loaded after the data have been injected/inserted (using a script dependency chain for example)
If it's not "inline" (on the View/Page itself), you could do a Partial View/Page:
Trivial example: _PartialJs.cshtml
$(document).ready(function() {
var foo = "#DateTime.Now.Year";
});
Then in your view:
<script>
#Html.Partial("_PartialJs")
</script>
Renders:
<script>
$(document).ready(function() {
var foo = "2015";
});
</script>
Hth...

Get the name of the HTML document that called a JS function

I'm a beginner with JS.
I am working with some JavaScript on a site, and I just want to use only 1 file of JS for determine the actions off the pages. Something like this:
function registerEvents(){
NameOfHTMLDocument = //?? Get the name of the document that called registerEvents function.
switch(NameOfHTMLDocument)
{
case:"homepage":
hmp_btn = document.getElementById("hmp_btn");
hmp_btn.onclick=otherFunction;
break;
case:"otherPage":
elem = document.getElementById("elemID");
elem.onclick=fooFunction;
break;
//etc...
}
}
This function is called with a <body onload="registerEvents()"> that is "inherited" by all the pages.
The question is, How can I get the "NameOfHTMLDocument"?. Because I don't want that JS begin doing weird things when trying to get elements that don't exist.
I found that I can get the URL of the DOM and then play a little with it to get the string that i want, but i'm not sure if this is the better way of doing it.
It Would be nice if you have a better suggestion.
Firstly I would really suggest that you create separate script tags in html documents for functionality that is used only on that page and common functionality in separate file for several reasons:
No code pollution
Ease of change
Smaller download
Secondly, you can use switch on window.location.pathname DOM variable which is everything after domain
instead of homepage, etc..
i.e.
url = vader.samplesite.com/light/saber/
window.location.pathname = /light/saber/
(look at http://www.developertutorials.com/questions/question/q-242.php )
window.location.pathname
All you need to do is some parsing, but I'm sure you'll figure that out :) If not, leave a comment.
In your <body onload="registerEvents()"> pass the object this (the BODY in the DOM) through your event function such as : <body onload="registerEvents( THIS )">.
In your function itself, call the object you passed like object.ownerDocument.URL to get the URL including the HMTL document name or object.ownerDocument.title to get the page title.

How can I have the same javascript variable on the same page?

Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.
The problem right now is that I can't include the same variables names on the page.
For instance:
<script type="text/javascript">
var ttp_number = "1Z8E26R80281495993"; // Tracking number
var ttp_key="123456";
(function(){
document.write('<div id="ttp"></div>');
s=document.createElement('script');
s.type="text/javascript";
s.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp').appendChild(s);",1);
})()
</script>
Then if they wanted to be able to embed that again, I'd have to change all variable names:
<script type="text/javascript">
var ttp_number_001 = "446888240962"; // Tracking number
var ttp_key_001="123456";
(function(){
document.write('<div id="ttp_001"></div>');
s_001=document.createElement('script');
s_001.type="text/javascript";
s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
})()
</script>
I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.
Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.
So, the ultimate question here...how do I fix that?
Maybe store the ttp_key and ttp_number's in arrays instead?
Why not declare the variables in the function body. Then they're only scoped to that function. You can still set them to different values when you dump the script into the HTML.
I know you mention/imply that the user can edit the function (for some reason) but that just seems like a world of hurt to me, so I'm hoping that that's not actually the case.
Why are you cachebusting with Math.random()? Does the JavaScript at http://c.trackthepack.com/j/e change often? If not, you should let the cache do its job.
But if so, could you make it dynamic enough to inspect the arguments it's called with and use those arguments directly, instead of relaying them via the global window object, so that you load http://c.trackthepack.com/j/e?n=446888240962&k=123456 and it doesn't have to look them up when the script runs?

Categories

Resources