Moving JavaScript from mark-up to separate .js file - javascript

My Javascript/html code looks like following which works great and shows country name in Part 1 below.
When i am trying to convert the code in .JS file it doesnt work means doesnt shows the country name in Part 2.. not sure what is wrong in the code
Part 1
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</body>
Part 2
// JavaScript Document
document.write("<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'></script>");
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
document.write("<script type='text/javascript' src='http://smart-ip.net/geoip-json?callback=GetUserInfo'></script>");
Here is the HTML of PArt 2
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude </title>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</table>

Include the jQuery reference as a real script tag in your HTML still - and remove the document.write.
Also ; on the end of your var list... Perhaps.
Your <head> tag should be
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude
</title>
<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'>
</script>
<script src="test.js" type="text/javascript"></script>
</head>
As Paul notes document.write is deprecated. You should always try to include <script> tags rather than manipulating the DOM. I think that the way you were doing it would mean that the jQuery code in your file would be executing before jQuery had loaded - due to the fact that you are writing the tag directly to the DOM immediately before your code. So there will not have been time to parse it. I would think that this code would have raised an error in fact.

Related

Link JavaScript object within HTML

How would I be able to pull the data from the JS script within my HTML? I am wanting to pull the "Title", "Description", and "Link" objects and display them within my HTML code.
Here is the code:
<div class="roadMap" id="roadMap"></div>
<script src="/siteassets/bootstrap3/js/jquery-1.8.3.min.js"></script>
<script src="/publiccdnlib/PnP-JS-Core/pnp.min.js"></script>
<script type="text/javascript" src="/publiccdnlib/es6-Promise/es6-promise.auto.js"></script>
<script type="text/javascript" src="/publiccdnlib/fetch/fetch.min.js"></script>
<script src="/publiccdnlib/slick/slick.min.js"></script>
<script src="/publiccdnlib/CommonJS/CommonJS.js"></script>
<script src="/publiccdnlib/knockout/knockout.js"></script>
<script src="/publiccdnlib/knockout/knockout.simpleGrid.3.0.js"></script>
<script src="/publiccdnlib/toastr/toastr.min.js"></script>
<script src="/publiccdnlib/dialog/open-sp-dialog.js"></script>
<!--END Scripts for O365-->
<script>
$pnp.setup({
baseUrl: "https://fh126cloud.sharepoint.com/TrainingResourceCenter/O365Training"
});
$pnp.sp.web.lists.getByTitle("O365RoadMap").items.get().then(function(z) {
console.log(z);
var result = z.results.map(a => ({
Title: `${a.Title}`,
Description: `${a.Description}`,
Link: `${a.Link}`
}))
console.log(result);
document.getElementById("roadMap").innerHTML = JSON.stringify(result, null, 2)
})
</script>
<html lang="en">
<body>
<div>
/* Code goes here */
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
I see you are using jQuery so I will answer relative to it.
Using jQuery you can put text wherever you want using the text method.
For example, if you want to put the Title data in your div you could do:
$("div").text(result.Title);
The code above will place result.Title in every div on the page (which you only have one of.).
There are so many jQuery methods you could use as-well, such as append, prepend, and html. Append will put the text after the existing content of an element. Prepend puts the text before existing content of an element. Html with replace the html inside of an element.
So if you wanted to construct the HTML elements then place them on the DOM (the web page) you could do:
$(document).ready(function(){
var head = '<h1>${result.Title}</h1>';
var desc = '<p>${result.Description}</p>';
var link = '<a src="${result.Link}">${result.Link}</a>';
$("div").html(head + desc + link);
});
To put your Title, Description, and Link on the DOM. Hope this help you, good luck!

javascript module not being found

I have a bunch of web pages where I have an identical construct:
<html>
<head>
<script src="sorttable.js"></script>
<noscript>
<meta http-equiv="refresh" content="60">
</noscript>
<script type="text/javascript">
<!--
var sURL = unescape(window.location.pathname);
function doLoad()
{
setTimeout( "parent.frames['header_frame'].document.submitform.submit()", 60*1000 );
}
function refresh()
{
window.location.href = sURL;
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.replace( sURL );
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.reload( true );
}
//-->
</script>
</head>
<body>
.
.
.
<script type="text/javascript">
window.onload = function() { sorttable.innerSortFunction.apply(document.getElementById("OpenFace-2"), []); doLoad(); }
</script>
</body>
</html>
This works perfectly in every page except for one, where when the onload function runs it cannot find the sorttable code (which is loaded from sorttable.js up at the top). All these pages are part of the same application and are all in the same dir along with the js file. I do no get any errors in the apache log or the js console until that page loads, when I get:
sorttable.innerSortFunction is undefined
I can't see what makes this one page different. Can anyone see what is wrong here, or give me some pointers on how I can debug this further?
The code I pasted in is from the source of the page where it does not work, but it is identical as the pages where it does work.
Looks like on that page the table with id OpenPhace-2 by which you try to sort have no needed class: sortable
The function innerSortFunction of sorttable object will be present only if there is any table with sortable class exists.

String.format not a function

I'm using HTML publisher in hope to have a html page with some javascript codes running on hudson. The HTML code is like this:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../stringformat.js"></script>
<script type="text/javascript">
......
sql=String.format("/.csv? select from table where exchange=`ABC......")
</script>
</head>
However, after a successful build, my html page doesn't show what it suppose to, and as I check the error console, it says
Error: TypeError: String.format is not a function
I have put my stringformat.js into the top folder, as the HTML publisher doesn't seem to allow the file to contain anything other than HTML files.
Can anyone tell me why the String.format is not loaded properly? Thanks!
PS: stringformat.js is the file i got from
http://www.masterdata.se/r/string_format_for_javascript/
The code should be working properly as this piece of code works outside the hudson
try code:
<html>
<head>
<title>String format javascript</title>
<script type="text/javascript">
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var _myString = String.format("hi {0}, i'am {1}","everybody", "stackoverflower");
function show(){
alert(_myString);
}
</script>
</head>
<body>
<input type="button" name="btnTest" id="btnTest" value="Test string format" onclick="show();" />
</body>
</html>

Splitting up a Javascript snippet

The recommendation of the open source web analysis software Piwik is to put the following code at the end of the pages you want to track, directly before the closing </body> tag:
<html>
<head>
[...]
</head>
<body>
[...]
<!-- Piwik -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://piwik.example.com/" : "http://piwik.example.com/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 4);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src="http://piwik.example.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
<!-- End Piwik Tracking Code -->
</body>
</html>
Under the following assumptions:
https is never used
we don't care that the page loads slower because the script is loaded before the DOM
is it okay to convert the above to the following:
HTML file:
<html>
<head>
[...]
<script src="http://piwik.example.com/piwik.js" type="text/javascript"></script>
</head>
<body>
[...]
<noscript><p><img src="http://piwik.example.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
</body>
</html>
Custom Javascript file with jQuery:
$(document).ready(function() {
try {
var piwikTracker = Piwik.getTracker("http://piwik.example.com/piwik.php", 4);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
}
catch(err) {
}
}
Are there any differences?
You are deferring the tracking until the page is fully loaded. Inline Javascript is executed when the browser finds it, so you'll have different number of visits depending on where you call piwikTracker.trackPageView();. The latter you call it, the lesser number of visits/actions will be counted.
Now, what do you consider a visit/action? If a user click on a link on your page, before the page fully loads, do you consider it a visit?

what if jquery.js is include into the page twice?

If I introduce the jquery.js into the page twice(unintentional OR intentional), what will happen?
Is there any mechanism in jquery that can handle this situation?
AFAIK, the later one jquery will overwrite the previous one, and if there is some action binding with the previous one, it will be cleared.
What can I do to avoid the later one overwrite the previous one?
===edited===
I couldn't understand WHY this question got a down vote. Could the people who give the down vote give out the answer?
==edited again==
#user568458
u r right, now it's the test code:
<html>
<head>
</head>
<body>
fast<em id="fast"></em><br>
slow<em id="slow"></em><br>
<em id="locker"></em>
</body>
<script type="text/javascript">
function callback(type){
document.getElementById(type).innerHTML=" loaded!";
console.log($.foo);
console.log($);
console.log($.foo);
$("#locker").html(type);
console.log($("#locker").click);
$("#locker").click(function(){console.log(type);});
$.foo = "fast";
console.log($.foo);
}
function ajax(url, type){
var JSONP = document.createElement('script');
JSONP.type = "text/javascript";
JSONP.src = url+"?callback=callback"+type;
JSONP.async = JSONP.async;
JSONP.onload=function(){
callback(type);
}
document.getElementsByTagName('head')[0].appendChild(JSONP);
}
</script>
<script>
ajax("http://foo.com/jquery.fast.js", "fast");
ajax("http://foo.com/jquery.slow.js", "slow");
</script>
</html>
it produced the result:
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast test:19
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast
the token "$" of the previous one(jquery.fast.js) is overwrite by the later(jquery.slow.js) one.
Is there any method to avoid the overwriting?
I did try this code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#try').click(function() {
alert('ok');
});
});
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<button id="try">Try me</button>
</body>
</html>
Nothing happend. On click I've got an alert. Same result if the second jquery.js loaded in body tag before or after the button.

Categories

Resources