I have been using javascript for the last couple of days and have decided to use it for my website. I also decided to use external functions in a single .js file
function imageLoad() {
var path,domain,cut;
path = window.location.pathname;
domain = "WEBSITE DOMAIN ADDRESS";
cut = path.substring(domain.length,path.length);
/* Still in progress */
}
function pageStart() {
var image-on = 0;
var imgArray = new Array();
alert("boo"); /* Used to check the script will run */
}
Now that's a simple process. Nothing too complex. And I have done the following (it is a code extract of my template)
<script type="text/javascript" src="main_script.js"></script>
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>Grandpa Pixel</title>
</head>
<body onload="pageStart();">
Now that should do the trick. On body loading, it should cause an alert "boo". But it doesn't. It just loads the page normally. However If I make the external script ONLY contain the line alert("boo"), it works perfectly. Can I ask why this is the case? Does this mean you can only have one function per external file?
check this:
function pageStart() {
var image_on = 0;
var imgArray = new Array();
alert("boo"); /* Used to check the script will run */
}
HTML
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>Grandpa Pixel</title>
<script type="text/javascript" src="main_script.js"></script>
</head>
<body onload="pageStart();">
recommended using Firebug or other debuggers.
ERRORS
SyntaxError: missing ; before statement
var image-on = 0;
main_script.js (line 12, col 13)
ReferenceError: pageStart is not defined
pageStart();
SOLUTION
change
var image-on = 0;
with
var imageOn = 0;
it would be cleaner to put the <script> tag into the <header> tag.
Related
I'm a student working on an art project in which I select one of 500 created images to show up on a webpage. I'm very new to coding and only really understand html and css, with very small amount of knowledge in JavaScript. I'm stuck in getting the images to show up, when I inspect it gives me an error saying: Failed to load resource: net::ERR_FILE_NOT_FOUND $selected_image}< I'm not really sure what to do with this, I hope someone would like to help me with this.
Thankyou :)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" media="screen" href="css/main.css">
<!-- <link rel="JavaScript" href="script.js"> -->
<meta charset='utf-8'>
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
<title>Mother</title>
<body>
<div id="container">
<div id="inner_container">
<img id="image_shower"/>
</div>
<div id="button_container">
<button onclick="get_random_image()"></button>
</div>
</div>
<script>
image_array = [
'Lilith10.png',
'Lilith11.png',
'Lilith12.png',
'Lilith13.png',
'Lilith14.png']
function get_random_image(){
random_index = Math.floor(Math.random() * image_array.lenght);
selected_image = image_array[random_index]
document.getElementById('image_shower').src = './images/$selected_image}'}
</script>
</body>
</html>
Javascript template strings are written with oblique quotes, and variables inside it must have brackets around them (you only had the closing one):
document.getElementById('image_shower').src = `./images/${selected_image}`;
EDIT
Even if in the present case this won't stop your code from working (unless you activate "strict mode"), I also recommend that you use the appropriate keywords to declare your variables.
const image_array = [
'Lilith10.png',
'Lilith11.png',
'Lilith12.png',
'Lilith13.png',
'Lilith14.png'
];
function get_random_image() {
const random_index = Math.floor(Math.random() * image_array.length);
const selected_image = image_array[random_index];
document.getElementById('image_shower').src = `./images/${selected_image}`;
}
I'm trying to get some dynamic content to display based on UTMs in my URL. While I can call the function in the browser to get the content to display, it isn't doing so on page load. (Function works, but my timing must be off)
I've tried to change the order in which I call jQuery and my JS file, but either way it doesn't show unless I paste my function into chrome dev tools.
Here's the relevant part of the function:
// regex to find the URL param above
var dynamicContent = getParameterByName('dc');
$(document).ready(function() {
if (dynamicContent == 'fintech') {
$('#fintech').show();
}
else if (dynamicContent == 'martech') {
$('#martech').show();
}
//... excluded remaining options
else {
$('#default-content').show();
}
And the HTML:
<span id="default-content" class="dynamic-content">Tech</span>
<span id="fintech" class="dynamic-content">Fintech</span>
<span id="martech" class="dynamic-content">Martech</span>
<!-- excluded remaining options -->
And here's my header in case there's a different way I should be calling everything:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="assets/dynamic.js" type="text/javascript"></script>
</head>
Again, as copying/pasting my code into dev tools after the page load works, how do I time it so that this function runs on page load?
Thanks.
Maybe try this:
$(window).on('load', function () {
var dynamicContent = getParameterByName('dc');
if (dynamicContent == 'fintech') {
$('#fintech').show();
}
else if (dynamicContent == 'martech') {
$('#martech').show();
}
//... excluded remaining options
else {
$('#default-content').show();
}
});
I keep getting an error saying my function "key" is not defined. Here is the HTML code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
<script language="text/javascript" src="main.js"></script>
</head>
<body onkeypress="key()">
<p>Money: <p id="money">0</p></p>
</body>
</html>
And the JavaScript:
int money = 0;
function key()
{
money += 1;
document.getElementById("money").innerHTML = money;
}
var money = 0;
instead of
int money = 0;
First: text/javascript is not a language supported by the browser's scripting engine, so the browser will ignore the script.
If you were writing HTML 3.2 you would say:
language="javascript"
If you were writing HTML 4 you would say:
type="text/javascript"
It is 2014, so write HTML 5 and don't specify a type or language attribute at all.
Second, int money = 0; is invalid JavaScript. (You seem to be trying to write Java.). So the script will throw an exception and stop at that point.
Use var to declare variables (of any type) in JS.
var money = 0;
I am working on a project where we are trying to implement a jQuery plugin called Footable. It works by calling the function .footable() on the table being selected by jQuery. When I tried to call this function I got a type error: undefined is not a function.
We are also using prototypejs in this project so at first I though that the problem was that footable was using $.() instead of jQuery.(), and it was. I went in and changed the $[.(] to jQuery hoping that it would fix the problem, but I am still unable to call .footable().
You should also know that I am loading footble.js from an Iframe. I'm not sure if that would cause any problems.
I'm not sure what to try next. Any advice is appreciated.
Thanks in advance
UPDATE 1
I have tried entering the following code in the console
var $j = jQuery.noConflict();
$j('<table></table>').footable();
In an environment that successfully loads footable an object is returned with the footable classes. In my enviornment I get a "TypeError: undefined is not a function".
make sure load jquery first, and then footable
and $ is alias from jQuery, so its should not a problem, u can use $() or jQuery()
based on your question, you should use $() or jQuery(), not $.() or jQuery.()
I think you're on the right track with there being a conflict.
Here's a plunk that demonstrates the issue: http://plnkr.co/edit/2sR7F2W0QGJAcXxgez14
In the plunk, if JQuery is still reference by $ and you add the reference to Prototype, you see that Footable stops working. If you use the JQuery NoConflict and then use that instead of $, Footable starts work as expected again.
Here's where I define the scripts:
<head>
<link data-require="bootstrap-css#3.0.2" data-semver="3.0.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" />
<link data-require="jqueryui#*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />
<link rel="stylesheet" href="footable.core.css" />
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="jqueryui#*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>
<script data-require="bootstrap#*" data-semver="3.0.2" src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script>var $j = jQuery.noConflict();</script>
<script src="footable.js"></script>
<script src="footable.filter.js"></script>
<script data-require="prototype#*" data-semver="1.7.1+0" src="//cdnjs.cloudflare.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
</head>
Then when I use JQuery and Call footable():
$j(function() {
window.footable.options.filter.filterFunction = function(index) {
var $t = $j(this),
$table = $t.parents('table:first'),
filter = $table.data('current-filter').toUpperCase(),
columns = $t.find('td');
var regEx = new RegExp("\\b" + filter + "\\b");
var result = false;
for (i = 0; i < columns.length; i++) {
var text = $j(columns[i]).text();
result = regEx.test(text.toUpperCase());
if (result === true)
break;
if (!$table.data('filter-text-only')) {
text = $j(columns[i]).data("value");
if (text)
result = regEx.test(text.toString().toUpperCase());
}
if (result === true)
break;
}
return result;
};
$j('table').footable().bind('footable_filtering', function(e) {
var selected = $j('.filter-status').find(':selected').text();
if (selected && selected.length > 0) {
e.filter += (e.filter && e.filter.length > 0) ? ' ' + selected : selected;
e.clear = !e.filter;
}
});
}
If you want to continue to use $ jquery you could do something like: (jQuery and prototype.js conflict, how to keep jQuery as $?)
(function($) {
$('table').footable();
})(jQuery);
I have two style sheets, one default style and one Christmas style. I would like the Christmas style to be loaded in December and the default to be used in every other month.
I have written the code below which achieves what I want, however if I put it in to a validator I get the error: "document type does not allow element "link" here". I was wondering how I could make this code validate?
<head>
<script type="text/javascript">
var i = new Date();
var m = i.getMonth();
if (m==11) {
document.write('<link rel="stylesheet" type="text/css" href="mystyle-christmas.css" />');
} else {
document.write('<link rel="stylesheet" type="text/css" href="mystyle-default.css" />');
}
</script>
</head>
The validator has problems because you're not using CDATA, thus the validator will parse your javascript. Use the following to solve your problem:
<head>
<script>
//<![CDATA[
// Your code here
// ]]>
</script>
</head>
Btw, the following is a better way to do it:
<head>
<script type="text/javascript">
var i = new Date(),
m = i.getMonth(),
l = document.createElement( 'link' )
l.rel = 'stylesheet'
if ( m === 11 ) {
l.href = 'mystyle-christmas.css'
}
else {
l.href = 'mystyle-default.css'
}
document.getElementsByTagName( 'HEAD' )[ 0 ].appendChild( l )
</script>
</head>
And an even better way is to have your javascript in an external js file.
Try creating the element instead of using document.write:
var christmas = document.createElement("link");
christmas.setAttribute("rel", "stylesheet");
christmas.setAttribute("type", "text/css");
christmas.setAttribute("href", "mystyle-christmas.css");
document.getElementsByTagName("head")[0].appendChild(christmas)