Given the following:
HTML
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<table>
<tr class='foo'><td>one</td></tr>
<tr class='foo'><td>two</td></tr>
<tr class='foo'><td>three</td></tr>
</table>
<script type="text/javascript" src="http://underscorejs.org/underscore.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javscript" src="https://gist.githubusercontent.com/anonymous/d25940992da18e05f3f2d50889f6a4c2/raw/f013565c33d17abb33a4f5ad7717aae090873516/test.js"></script>
</body>
</html>
JS
// Generated by CoffeeScript 1.10.0
(function() {
var hasChildren, rowsWithChildren;
$(function() {
return console.log('starting');
});
$(function() {
var filtered, rows;
console.log('here');
rows = $('tr');
filtered = rowsWithChildren(rows);
return console.log(filtered);
});
rowsWithChildren = function(rows) {
return _.filter(rows, function(r) {
return hasChildren(r);
});
};
hasChildren = function(row) {
return row.children().length === 1;
};
}).call(this);
When I open that HTML page in my Chrome Browser, I see the table on the screen. But, I don't see any console.log ... statements in the output of the Developer Tools Console.
Also, when I look at Dev Tool's Sources, I don't see the JS from gist.github.com....
What's wrong with this HTML?
There's two problems with what you're attempting to do:
There's a typo on the line where you link to the Gist - should be text/javascript not text/javscript.
Github doesn't allow you to hotlink to code/assets hosted on their website - essentially you can't use them as a CDN. Here's a blog post from them explaining this in more detail.
The third script element has a wrong type value. With a wrong value, the loaded file will not be interpreted as JavaScript.
So change:
<script type="text/javscript" ...
to:
<script type="text/javascript" ...
As I remember there is "onready" problem in this version of jQuery (I may be mistaken).
As for "text/javascript" it's unnecessary nowadays.
Try to merge your two $(function(){}) into one, and remove these "returns" inside them. Like this:
(function() {
var hasChildren, rowsWithChildren;
$(function() {
console.log('starting');
var filtered, rows;
console.log('here');
rows = $('tr');
filtered = rowsWithChildren(rows);
console.log(filtered);
});
rowsWithChildren = function(rows) {
return _.filter(rows, function(r) {
return hasChildren(r);
});
};
hasChildren = function(row) {
return row.children().length === 1;
};
}).call(this);
Hope it helps.
Related
I am using a framework called Framework7.
In my index.html, I have some Template7 code, like this format
<script type="text/template7" id="commentsTemplate">
{{#each this}}
<div> test this template 7 code </div>
</script>
However, I want to have this part of code into an another separated file (Just like I can have many other *.js files in, say, a static folder and refer to the file by "static/*.js).
I have tried to use a typical way to import js
<script type="text/template7" id="storiesTemplate" src="js/template.js"></script>
But it doesn't work, there is also no demo/sample code in the documentation.
Any help is appreciated!
You can do it. The idea behind is to include a HTML file in a HTML file. I can tell at least 3 ways that this can happen, but personally I fully validated only the third.
First there is a jQuery next sample is taken from this thread
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>
Another solution, I found here and doesn't require jQuery but still it's not tested: there is a small function
My solution is a pure HTML5 and is probably not supported in the old browsers, but I don't care for them.
Add in the head of your html, link to your html with template
<link rel="import" href="html/templates/Hello.html">
Add your template code in Hello.html. Than use this utility function:
loadTemplate: function(templateName)
{
var link = document.querySelector('link[rel="import"][href="html/templates/' + templateName + '.html"]');
var content = link.import;
var script = content.querySelector('script').innerHTML || content.querySelector('script').innerText;
return script;
}
Finally, call the function where you need it:
var tpl = mobileUtils.loadTemplate('hello');
this.templates.compiledTpl = Template7.compile(tpl);
Now you have compiled template ready to be used.
=======UPDATE
After building my project for ios I found out that link import is not supported from all browsers yet and I failed to make it work on iphone. So I tried method number 2. It works but as you might see it makes get requests, which I didn't like. jquery load seems to have the same deficiency.
So I came out with method number 4.
<iframe id="iFrameId" src="html/templates/template1.html" style="display:none"></iframe>
and now my loadTemplate function is
loadTemplate: function(iframeId, id)
{
var iFrame = document.getElementById(iframeId);
if ( !iFrame || !iFrame.contentDocument ) {
console.log('missing iframe or iframe can not be retrieved ' + iframeId);
return "";
}
var el = iFrame.contentDocument.getElementById(id);
if ( !el ) {
console.log('iframe element can not be located ' + id );
return "";
}
return el.innerText || el.innerHTML;
}
How about lazy loading and inserting through the prescriptions?
(function (Template7) {
"use strict";
window.templater = new function(){
var cache = {};
var self = this;
this.load = function(url)
{
return new Promise(function(resolve,reject)
{
if(cache[url]){
resolve(cache[url]);
return true;
}
if(url in Template7.templates){
resolve(Template7.templates[url]);
return true;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(this.status == 200 && this.response.search('<!DOCTYPE html>') == -1){
cache[url] = Template7.compile(this.response);
resolve(cache[url]);
}else{
reject(`Template ${url} not found`);
}
};
xhr.send();
})
}
this.render = function(url, data)
{
return self.load(url)
.then(function(tpl){
return tpl(data) ;
});
}
this.getCache = function()
{
return cache;
}
}
})(Template7);
Using :
templater.render('tpl.html').then((res)=>{ //res string })
Or :
templater.load('tpl.html').then( tpl => { Dom7('.selector').html( tpl(data) ) } )
It is possible to define your templates in .js-files. The template just needs to be a string.
Refer to this [JSFiddle] (https://jsfiddle.net/timverwaal/hxetm9rc/) and note the difference between 'template1' and 'template2'
var template1 = $$('#template').html();
var template2 = '<p>Hello, my name is still {{firstName}} {{lastName}}</p>'
template1 just extracts the content of the <script> and puts it in a string.
template2 directly defines the string
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.
Using the following code, I get working output:
<html>
<head>
<script type="text/javascript" src="/js/showdown.js"></script>
</head>
<body>
<script type="text/javascript">
var converter = new Showdown.converter();
alert(converter.makeHtml('*test* abc'));
</script>
</body>
</html>
Returning <p><em>test</em> abc</p>
I would now like to add an extension. The github page suggests this can be done with:
<script src="src/extensions/twitter.js" />
var converter = new Showdown.converter({ extensions: 'twitter' });
However, modifying my code to:
<html>
<head>
<script type="text/javascript" src="/js/showdown.js"></script>
<script type="text/javascript" src="/js/twitter.js"></script>
</head>
<body>
<script type="text/javascript">
var converter = new Showdown.converter({ extensions: 'twitter' });
alert(converter.makeHtml('*test* abc'));
</script>
</body>
</html>
Produces the error
"Uncaught Extension 'undefined' could not be loaded. It was either not found or is not a valid extension."
Adding the following code (as listed under the Filter example)
var demo = function(converter) {
return [
// Replace escaped # symbols
{ type: 'lang', function(text) {
return text.replace(/\\#/g, '#');
}}
];
}
Produces an error Uncaught SyntaxError: Unexpected token (
I would like to create an extension like this one https://github.com/rennat/python-markdown-oembed to interpret a ![video](youtube_link), but it's unclear how to begin adding this support.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']});
converter.makeHtml('whatever #meandave2020');
// output "<p>whatever #meandave2020</p>"
I submitted a pull request to update this.
The way we write extensions has changed, I found some help with the following filter example : http://codepen.io/tivie/pen/eNqOzP
showdown.extension("example", function() {
'use strict';
return [
{
type: 'lang',
filter: function(text, converter, options) {
var mainRegex = new RegExp("(^[ \t]*:>[ \t]?.+\n(.+\n)*\n*)+", "gm");
text = text.replace(mainRegex, function(match, content) {
content = content.replace(/^([ \t]*):>([ \t])?/gm, "");
var foo = converter.makeHtml(content);
return '\n<blockquote class="foo">' + foo + '</blockquote>\n';
});
return text;
}
}
]
});
I wrote a code in jquery. I was not running initially, then i checked online jslint for syntax errors. I caught some errors. Now still the code was not working as expected. So i went for firebug. I haven't done a lot of debugging. I am new to it. Here is my code
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
console.log("button clicked");
var a =[];
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
var rows = response.rows;
alert("hello there");
for (var i = 0; i < rows.length; i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = rows[i].elements[j].distance;
}
}
alert(distance[1][3]);
});
});
});
Now, what it should do is Go to this link and get the data from json file and store it inside the 2 dimensional array distance[][]. Finally after storing all the data, it should display the result of "distance[1][2]" as an alert.
Now i dont know whats wrong in this code and how to find the logical errors using firebug. What should make my work easy ?
ps: heres the HTML file
<!doctype html>
<html>
<head>
<title>TakeMeHome</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/jquery-1.9.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.0.custom.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.0.custom.min.js"></script>
</head>
<body>
<center>
<form id="locations">
Your Place:<input id="source" type="text"><br/>
<br/>
<div id="friends">
Friend1:<input id="friend1" type="text"><br/>
<br/>
</div>
<div id="button">
Add!</div>
<br/>
<br/>
<button>GO!</button>
<br/><br/>
<div id="map" style = "width: 500px; height: 500px"><br/>
</form>
</center>
</body>
</html>
Hey here is a working fiddle with your code, and some examples of ways to debug your js :
http://jsfiddle.net/QxP7p/3/
As you see you can do nice stuff like :
console.log("distance : ");
console.log(distance);
Hope it helps
They were a few mistakes as well, couldn't help fixing them
The easiest way to debug is to use firebug and console.log() variables or messages at certain points in your script, so that you can better understand what is going on at various steps of your script. You can see the output in the Console tab of firebug.
You can also add breakpoints and watches from some of the other tabs. For example in the DOM tab you can rightclick on a variable and add a watch, or from the Script tab you can click on a position in your script to set a breakpoint or watch, and it will stop the script at that point and/or show a dump of vars at that point.
I'm having issues getting jQuery to work correctly while testing on Localhost.
The function that's giving me trouble:
function poll() {
$.get(location.href, function(data) {
var x = $('#datadump', data);
alert(x.html());
});
}
Where location.href = http://localhost/polltest.php
The alert merely returns null instead of a random number produced by PHP's rand function. The source of localhost/polltest.php is:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function poll() {
$.get(location.href, function(data) {
var x = $('#datadump', data);
alert(x.html());
});
}
</script>
</head>
<body onload="poll();">
<div id="datadump">
<?php
$val = rand(0, 100);
echo $val;
?>
</div>
</body>
</html>
Any help regarding a way for this to work would be wonderful and appreciated.
There could be multiple ways to achieve the value of the div with id datadump.
One of the ways being
function poll() {
$.get(location.href, function(data) {
x = $(data).filter('#datadump');
console.log(x);
});
}
The reason it is failing for you:
When you have an HTML string which contains <html>, <head>, <body> tags, and you try to do
$(string)
those elements will be ignored. Only those elements which can be put inside a div are valid. Read it in the jQuery documentation.
When passing in complex HTML, some browsers may not generate a DOM
that exactly replicates the HTML source provided. As mentioned, we use
the browser's .innerHTML property to parse the passed HTML and insert
it into the current document. During this process, some browsers
filter out certain elements such as <html>, <title>, or <head>
elements. As a result, the elements inserted may not be representative
of the original string passed.
This issue has been discussed in detail on this link: https://stackoverflow.com/a/5642602/410367
Can you try this way,
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var x = $('#ads');
alert(x.html());
$.get(location.href, function (data) {
var x = $('#ads', data);
alert(data);
alert(x.html());
});
});
</script>
</head>
<body>
<div id="datadump">
<?php
$val = rand(0, 100);
echo $val;
?>
</div>
</body>
Update: I have changed the script little bit similar to your original post. It works fine for me.