I'm having some trouble running some JS inside a html5 body.
Here's what's happening, whenever I remove all instances of the arrays from the JS file I am using, the script loads fine in the index file, however, when I add src to the attribute and/or mention an array name from said file, it breaks. simple as that.
since I'm planning on making a pretty big site, I have already begun organizing my root.
here's a little demo:
rootFolder/
index.htm
js/targetJS.js
here's the code
<script src="js/targetJS.js" type="text/javascript">
document.writeln("<table id='services' class='services' name='services'>");
document.writeln("<tr>");
document.writeln("<th> Preview: </th>");
document.writeln("<th> Description: </th>");
document.writeln("<th> Cost: </th>");
document.writeln("</tr>");
var i = 0;
//for ( i = 0; i < servicePrev.length; i++)
{
if (i % 2 == 0){
document.writeln("<tr class='even' id='even'>");
}
else{
document.writeln("<tr class='odd' id='odd'>");
}
//document.writeln("<td> " + servicePrev[i] + " </td>");
//document.writeln("<td> " + serviceDesc[i] + " </td>");
//document.writeln("<td> " + serviceCost[i] + " </td>");
document.writeln("</tr>");
}
document.writeln("</table>");
</script>
Whenever i add the src in the attribute and the lines that are commented out, the code does not work, however, when I omit the src and the lines that are currently commented out, the code works fine. even JSfiddle reports it working fine.
The contents of the JS file are 3 arrays with 5 indexes.
You need to seperate your tags
<script type="text/javascript" src="awesomescript.js"></script>
and
<script>
// some awesome code here
</script>
Since html5, you are free to name <script type="text/javascript"> or just use <script> for javascript, as text/javascript is default.
Quoted from http://javascript.crockford.com/script.html
The script tag has two purposes:
It identifies a block of script in the page. It loads a script file.
Which it does depends on the presence of the src attribute. A
close tag is required in either case.
The src attribute is optional. If it is present, then its value is a
url which identifies a .js file. The loading and processing of the
page pauses while the browser fetches, compiles, and executes the
file. The content between the and the
should be blank.
So, the script file should be loaded by dedicated script tag without content, the script content should be inserted into another script tag, after all if you have other errors you can check in the console of your broswer
<script src="js/targetJS.js" type="text/javascript"></script>
<script type="text/javascript">
document.writeln("<table id='services' class='services' name='services'>");
document.writeln("<tr>");
document.writeln("<th> Preview: </th>");
document.writeln("<th> Description: </th>");
document.writeln("<th> Cost: </th>");
document.writeln("</tr>");
var i = 0;
//for ( i = 0; i < servicePrev.length; i++)
{
if (i % 2 == 0){
document.writeln("<tr class='even' id='even'>");
}
else{
document.writeln("<tr class='odd' id='odd'>");
}
//document.writeln("<td> " + servicePrev[i] + " </td>");
//document.writeln("<td> " + serviceDesc[i] + " </td>");
//document.writeln("<td> " + serviceCost[i] + " </td>");
document.writeln("</tr>");
}
document.writeln("</table>");
</script>
Related
Ive already searched for infomation how I can do that but I cant fix this problem. I want to add a weather-widget to my webpage. It works using latitude and longitude. I want it should desplay the current weather from where the user is now.
<span id ="long"></span>
<script type='text/javascript' id="weather-link" src='https://darksky.net/widget/default/></script>
<script>const weatherLink = $("#weather-link");
weatherLink.html("<span id=\"" + response.latitude + "," +response.longitude + "\">/uk12/de.js?width=100%&height=350&title=Basel&textColor=333333&bgColor=FFFFFF&transparency=false&skyColor=undefined&fontFamily=Default&customFont=&units=uk&htColor=333333<Color=333333&displaySum=yes&displayHeader=yes</span>");
weatherLink.attr("src", weatherLink.attr("src") + response.city);</script>
The following code I use it to get users information. It works well
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#long").html(response.latitude + ", " + response.longitude );
$("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
</script>
I need to add to src a text that changes using that code above.
THX
I have HTML file that contained my CSS and JS. When creating my flask app I decided to separate out the CSS and JS to separate files in a static directory.
When I have everything in one HTML file, everything works as expected, but when the CSS and JS are in separate files, parts of the JS don't execute.
This is my import for in the HTML file:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='scripts/main.js') }}"></script>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/pure-min.css">
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
</head>
This is the contents of the standalone JS file:
$('#user_button').click(function(event) {
$("#user_id").html($('option:selected').html());
$('.button_div').show();
});
var prodData = [];
var boughtProds = [];
$('.prod_button').click(function(event) {
if (boughtProds.indexOf($(this).data('name')) == -1) {
prodData.push({
name: $(this).data('name'),
price: $(this).data('price'),
quantity: 1,
});
boughtProds.push($(this).data('name'));
} else {
prodData[boughtProds.indexOf($(this).data('name'))].quantity = prodData[boughtProds.indexOf($(this).data('name'))].quantity + 1;
}
var total = 0;
for (var x in prodData) total += prodData[x].price * prodData[x].quantity
total = Math.round(total * 100) / 100
var subtotal = '<tr><td></td><td>Subtotal</td><td>$' + total + '</td></tr>';
var allProds = '';
$.each(prodData, function(k, v) {
allProds = allProds + '<tr><td>' + v.name + '</td><td>' + v.quantity + 'x</td><td># $' + v.price + ' each</td></tr>\n';
});
$('.table_contents > tbody').html(allProds);
$('.table_contents > tfoot').html(subtotal);
});
$(document).ready(
function() {
$('.button_div').hide();
})
The weird thing is that this function works properly on the document load:
$(document).ready(
function() {
$('.button_div').hide();
})
and this function DOES NOT work:
$('#user_button').click(function(event) {
$("#user_id").html($('option:selected').html());
$('.button_div').show();
});
But even weirder is that everything works when it is all in one HTML file.
Any thoughts?
You either need to move <script type="text/javascript" src="{{ url_for('static', filename='scripts/main.js') }}"></script> outside of your <head> tag (e.g., to the end of <body>) or you need to put $('#user_button').click(...); inside $(document).ready(...);.
What's happening is that your browser begins loading your external script files as it processes your <head> tag. As soon as the file is loaded, the browser executes it, binding the click event to #user_button. This happens before it processes your <body> tag, so #user_button isn't yet part of the DOM.
If you tried to inspect $('#user_button') you'd see that it's empty.
console.log($('#user_button'));
This outputs
[]
I have faced similar problem. When inspected network, static js was loading from cache.
When I turned-off cache, it started working.
Therefore you need to restart debug server or turn off cache during development.
Whenever I add the code below as a widget to my blog, the slider (Welcome...) on it will stop working. The slider should scroll through a few different images. I've read that 'no.conflict' will fix this problem but for the life of me haven't a clue where to put the code.
Recent Videos Widget
<script src='http://code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<style type="text/css">
div.PBTytC {clear:both;padding:5px;font-size:12px;}
div.PBTytC.odd {background-color: #;}
div.PBTytC_thumb {position:relative;float:left;margin-right:8px;line-height:1;}
div.PBTytC_thumb img {width:76px;height:78px;border:0px solid #55A66B;}
div.PBTytC_title {font-weight:none;}
</style>
<script type='text/javascript'>
var PBTYoutubeUserName = "XXX";
var PBTYoutubeMAXResults = 3;
var PBTYoutubeAllow = "";
var PBTYoutubeDisallow = "";
var PBTYoutubeWgetIsEmpty = "No entries";
$(document).ready(function() {
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=58c841d14337ba4fbf693abd9701dc49&_render=json&max-results="+PBTYoutubeMAXResults+"&allow="+PBTYoutubeAllow+"&disallow="+PBTYoutubeDisallow+"&user="+PBTYoutubeUserName+"&_callback=?", function(response) {
var htm = "";
for(var i=0;i<response.count;i++) {
var item = response.value.items[i];
htm += '<div class="PBTytC';
if(i%2 == 1) htm += ' odd';
htm += '"><div class="PBTytC_thumb"><a target="_blank" href="' + item.link + '"><img title="' + item.title + '" src="' + item.thumb + '"/></a></div>';
htm += '<div class="PBTytC_title"><a target="_blank" href="' + item.link + '">' + item.title + '</a></div>';
htm += '<div class="PBTytC_description">' + item.description + '</div><div style="clear:both;"></div></div>';
}
if(htm == "") htm = PBTYoutubeWgetIsEmpty;
$("#PBTytWdtLoad").html(htm);
});
});
</script>
<div id="PBTytWdtLoad">Loading...</div>
Here is the link to my blog: Link
Thanks for reading and hopefully helping me out.
Including JQuery twice can cause issues. The code fragment above and your blog both have a script tag for query. Try adding it to your blog without including JQuery again.
As for the plugin not working:
Your site includes JQuery; Then it has a lot of scripts that use JQuery; Then it has a script that changes the JQuery operator so that $ isn't use since this will cause conflicts with other scripts using the variable $ in another way. Considering the amount of scripts on your site I'm surprised you don't have more issues.
Anyway after your last script tag you can't use $ in your scripts you have to use jQuery instead. For example:
jQuery(document).ready(function() {
jQuery.getJSON("http://pipes.yahoo.com/pipes/pipe.run?
If you go through your whole script and change '$' to 'jQuery' then that will help with your script where it is in your page now, with the current page listed at your blog.
Really though, this is just putting a band-aid on a bigger problem. It's worth thinking about what scripts you really need.
I am currently doing this:
<div id="textChange" style="display:none;">Blah blah</div>
<script type="text/javascript">
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
</script>
and would like to move the script to an external JS file. How do I do that? I doesn't seem to be working for me.
Thanks.
Include this script after your #textChange div and it will work. For example before closing </body> tag:
...
<script src="funny-script.js" type="text/javascript"></script>
</body>
This is the simplest method. You could also run this code on DOMContentLoaded or window.onload events, but looking at what your script doing I don't think it makes sence.
1-open notepad or notepad ++ or whatever you use as a text editor.
2-copy the javascript code to the text editor without and tags
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
3-save the files with any name you want and don't forget to add the .js extension to the file for example save the file as "test.js"
4-copy the "test.js" to the same directory as html page.
5-add this line to the html page
<script type="text/javascript" language="javascript" src="test.js"></script>
One way to do this is to create a function and include this in a js file
function style_changer(){
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Now in your html give reference to the js file containing this function for example
<script type="text/javascript" src="yourscriptfilename.js" />
you can include this in your section and should work
Save the a file called script.js with the contents.
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
And place this tag inside your HTML document. Place it just before the </body> so you'll know that the element textChange will exist in the DOM before your script is loaded and executed.
<script type="text/javascript" src="script.js" />
Make sure that script.js is in the same directory as your HTML document.
put this below code in a function
step1:
function onLoadCall()
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Step2:-
call that function on page load
<body onload='onLoadCall()'>
...
</body>
step3:-
now move the script to another file it will work
Put script in a separate file and name it yourScript.js and finally include it in your file
add the code within the script file
function changeFunnyDate(){
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Finally add the script in your file & call the method
<script src="yourScript.js" type="text/javascript"></script>
Take everything between your script tags and put it in another file. You should save this file with a .js file extension. Let's pretend you save it as textChange.js.
Now the simplest thing to do would be to include the script file just after your <div> tag -- so basically where the <script> tags and code were before, write:
<script type="text/javascript" src="textChange.js"></script>
This assumes that 'textChange.js' is in the same folder as your HTML file.
...
However, that would far too easy! It is generally best practice to place <script> tags in the <head> of your HTML file. You can move the line above up into the head but then the script will load before your <div> does--it will try to do what it does and it will fail because it can't find the div. So you need to put something around the code in your script file so that it only executes when the document is ready.
The simplest way to do this (and there may be better ways) is write the following...
window.onload = function () {
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if ((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
This will mean your script is in the head where it should be and that it only performs when your whole page is ready, including the div that you want to act on.
Hope this helps.
This should be simple - don't get what I'm doing wrong! This is a very basic test (I'm new to PERL and Javascript) - this is the CGI file:
#! /usr/local/bin/perl
print "Content-type: text/html\n\n";
print "<html>\n" ;
print "<head>Hello\n";
print '<script type="text/javascript" language="javascript" src="wibble.js">\n';
print "</script>\n";
print "</head>\n";
print "<body>\n";
$fred = "Fred";
$numb = 7;
print <<TEST;
<p>Starting...</p>
<p><script type="text/javascript" language="javascript">
theText = "$fred";
theNum = "$numb";
document.writeln("Direct write...");
document.writeln("Number is: " + theNum);
document.writeln("Text is: " + theText);
testWrite(theNum, theText);
</script></p>
<p>...ending JS</p>
TEST
and in wibble.js:
function testWrite(num1, txt1)
{
document.writeln("In testWrite...");
document.writeln("Number is: " + num1);
document.writeln("Text is: " + txt1);
}
In my browser, I get the first set of writeln's but my function is never called. The error on the webpage says 'Object expected' at line 15 (the 'print <<TEST' line).
I mostly suspect I haven't got the right path in my src element but I've tried every combination I can think of ('.', './', full path etc) - nothing works. The js file is in the same dir as the CGI file.
(I actually originally had the function call with no parameters, hoping that theNum and theText are global and will still work (that was the original point of this test program)).
Please put me out of my misery...
As requested, here is source code from browser:
<html>
<head><script type="text/javascript" language="javascript" src="wibble.js"></script>
</head>
<body>
<p>Starting...</p>
<p><script type="text/javascript" language="javascript">
theText = "Fred";
theNum = "7";
document.writeln("Direct write...");
document.writeln("Number is: " + theNum);
document.writeln("Text is: " + theText);
testWrite(theNum, theText);
</script></p>
<p>...ending JS</p>
</body>
</html>
and this is the actual output on the web page:
Starting...
Direct write... Number is: 7 Text is: Fred
...ending JS
Did you check your server's log to see if wibble.js is ever requested? If it's not, then there's your problem. As well, while not really the problem, this line:
print "<head>Hello\n";
is generating bad html. You can't have "bare" text in the <head> block.
For global JS variables, you use the var keyword.
x = 7; // local
var y = 7; // global