I've a page "Chess" with a custom template. When I use the cheessboard.js script online there is no problem. When I want use a downloaded version of it and replace <base href="http://chessboardjs.com/" /> with the local path, it produces this errors on the browser:
GET http://localhost/css/chessboard.css (index):4
GET http://localhost/js/chess.js (index):8
GET http://localhost/js/jquery-1.10.1.min.js (index):9
GET http://localhost/js/chessboard.js (index):10
Uncaught ReferenceError: $ is not defined
How to adjust the template Chess.php?
...
<html>
<head>
<base href="http://chessboardjs.com/" />
<link rel="stylesheet" href="/css/chessboard.css" />
</head>
<body>
<div id="board" style="width: 400px"></div>
<script src="/js/chess.js"></script>
<script src="/js/jquery-1.10.1.min.js"></script>
<script src="/js/chessboard.js"></script>
<script>
var init = function() {
var board, game = new Chess();
var makeRandomMove = function() {
var possibleMoves = game.moves();
if (game.game_over() === true || game.in_draw() === true || possibleMoves.length === 0) return;
var randomIndex = Math.floor(Math.random() * possibleMoves.length);
game.move(possibleMoves[randomIndex]);
board.position(game.fen());
window.setTimeout(makeRandomMove, 500);
};
board = new ChessBoard('board', 'start');
window.setTimeout(makeRandomMove, 500);
};
$(document).ready(init);
</script>
</body>
</html>
...
The <base> attribute specifies the base URL to use for all relative URLs contained within a document. And you're probably placing the files inside your theme directory, and we get that with get_stylesheet_directory_uri().
The correct is to use wp_enqueue_scripts to load JS and CSS files, and to do it only on the pages where they are needed. Also, don't enqueue external jQuery from external sources, use the one bundled with WP: wp_enqueue_script('jquery');.
You could also create a shortcode for this. The following is just a raw example with Chessboardjs files inside the directory /wp-content/themes/your-theme/chessboardjs/. And the template page-chess.php is this:
<?php
/**
* Template Name: Chess
*/
$base = get_stylesheet_directory_uri() . '/chessboardjs';
?><html>
<head>
<link rel="stylesheet" href="<?php echo $base; ?>/css/chessboard-0.3.0.min.css" />
<script src="<?php echo $base; ?>/js/chess.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="<?php echo $base; ?>/js/chessboard-0.3.0.min.js"></script>
</head>
<body>
<div id="board" style="width: 400px"></div>
<script>
var init = function() {
var board, game = new Chess();
var makeRandomMove = function() {
var possibleMoves = game.moves();
if (game.game_over() === true || game.in_draw() === true || possibleMoves.length === 0) return;
var randomIndex = Math.floor(Math.random() * possibleMoves.length);
game.move(possibleMoves[randomIndex]);
board.position(game.fen());
window.setTimeout(makeRandomMove, 500);
};
var cfg = {
pieceTheme: '<?php echo $base; ?>/img/chesspieces/wikipedia/{piece}.png',
position: 'start'
};
board = new ChessBoard('board', cfg);
window.setTimeout(makeRandomMove, 500);
};
jQuery(document).ready(init);
</script>
</body>
</html>
Related
I have used JavaScript for a while, but am brand new to Node.js and full stack development, taking on a small project as a hobbyist. I have Heroku set up to host the app at https://midi-writer.herokuapp.com/ and am able to edit my files and update the app (using git commands) through my Mac terminal.
I am having trouble figuring out how to call a JavaScript function in an external file (in /src/js/midiWriter.js) from the index.html page. Using <script type="text/javascript" src="bundle.js"></script> doesn't work (I think that the file is 'bundled' when I push it to Heroku), and I have also tried <script type="text/javascript" src="../src/js/midiWriter.js"></script>
Here is the full code for index.html with the function call at the end of the script.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Heart Beats</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="bundle.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"></link>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
<fieldset>
<h2>EKG File</h2>
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
<hr>
Frequency: <div id="frequency"></div>
Metadata:<div id="metaData"></div>
<div id="midiDownload">A link will appear here after the file has been processed</div>
</fieldset>
</form>
<script type="text/javascript">
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
var metaDataString = '';
document.getElementById("frequency").innerHTML = newArr.frequency + " Hz";
for (i = 0; i < newArr.meta.dashboard_measurements.length; i++){
metaDataString += newArr.meta.dashboard_measurements[i].description + ": "
+ newArr.meta.dashboard_measurements[i].value
+ " " + newArr.meta.dashboard_measurements[i].unit + "<br>";
}
document.getElementById("metaData").innerHTML = metaDataString;
}
midiWriter();
}
</script>
</body>
</html>
Here's the midiWriter.js file:
function midiWriter(){
var MidiWriter = require('midi-writer-js');
var track = new MidiWriter.Track();
track.addEvent([
new MidiWriter.NoteEvent({pitch: ['E4','D4'], duration: '4'}),
new MidiWriter.NoteEvent({pitch: ['C4'], duration: '2'}),
new MidiWriter.NoteEvent({pitch: ['E4','D4'], duration: '4'}),
new MidiWriter.NoteEvent({pitch: ['C4'], duration: '2'}),
new MidiWriter.NoteEvent({pitch: ['C4', 'C4', 'C4', 'C4', 'D4', 'D4', 'D4', 'D4'], duration: '8'}),
new MidiWriter.NoteEvent({pitch: ['E4','D4'], duration: '4'}),
new MidiWriter.NoteEvent({pitch: ['C4'], duration: '2'})
], function(event, index) {
return {sequential: true};
}
);
var write = new MidiWriter.Writer(track);
console.log(write.dataUri());
var app = document.getElementById('midiDownload');
var downloadLink = `Download Link`;
app.innerHTML = downloadLink;
}
I get the Uncaught Reference Error "midiWriter is not defined" with this version.
Please excuse any lame errors! I am brand new to this :)
Simple solution would be like this:
In your html file:
<script src="../src/js/midiWriter.js"></script>
<script>
...
midiWriter();
</script>
What the first line does is set the source of the file you will use and the in the plain script tags, you can use any function or variable that has global scope and is declared in the file whose path you declared in the <script src=""> tag.
Just hired someone on Fiverr to take a look. The problem is that I need to define the external function globally using window.midiWriter = function (){...
I made a chrome extension where my popup button calls a script. The other script uses jQuery but I get an error saying jQuery is not defined.
My popup.html:
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
My popup.js:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('record');
login.addEventListener('click', function() {
chrome.tabs.executeScript({file: 'markStudents.js'});
});
});
myScript.js:
var arrays = []
$.get('Attendance.txt', function(data){
var splitted = data.split("\n"); // --> should return an array for each line
// Loop through all lines
for(var i = 0; i < splitted.length; i++)
{
var line = splitted[i];
// Now you could remove [ and ] from string
var removed = line.replace('[','').replace(']','');
var refined = removed.replace(' ', '');
// Now you can split all values by using , delimiter
var values = refined.split(',');
var array = [];
// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++)
{
var value = values[c];
array.push(value);
}
arrays.push(array);
}
});
var present = arrays[0];
console.log(present);
var absent = arrays[1];
console.log(absent);
var user = present[0];
var pass = absent[0];
var loginField = document.getElementById('fieldAccount');
var passwordField = document.getElementById('fieldPassword');
loginField.value = user;
passwordField.value = pass;
var loginForm = document.getElementById('btn-enter-sign-in');
Is there any way to include my jquery.js in myScript.js?
Console Error
Just import jquery before you import popup.js
Like this
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
Inside Your popup.js, when you load markStudents.js which uses jQuery, you'd again have to load jQuery before same
Like this
document.addEventListener('DOMContentLoaded', function () {
var login = document.getElementById('record');
login.addEventListener('click', function () {
chrome.tabs.executeScript(null, { file: "jquery-3.4.1.min.js" }, function () {
chrome.tabs.executeScript(null, { file: "markStudents.js" });
});
});
});
Just reorder your script tags and put jQuery before your popup.js. That way it will be loaded when you try to call it.
yo can use this code to include another jquery file in your jquery:
$.getScript("file address");
like this:
$.getScript("/assets/pages/scripts/ui-blockui.min.js");
I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.
(Before anything, you should know that my JS skills are very basic)
I'm trying to make my own "rapid sorting" from the game "BrainWars" on smartphones.
Basically what it should do is:
Step 1: randomise one of the 3 pictures available and show the image.
Step 2: if this image is the same as the last one ( do something )
Step 3: If this image is NOT the same as the last one ( do something else )
For now , I have a folder named "images" with 3 png's inside it.
So far I have this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var random_images_array = ['1.png', '2.png', '3.png'];
var lastImage = "";
function getRandomImage(imgAr, path) {
path = path || 'images/'; // Default path hier opgeven
var num = Math.floor(Math.random() * imgAr.length);
var img = imgAr[num];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}
$(function() {
$('#btn').click(function() {
getRandomImage(random_images_array, 'images/');
setTimeout(function() {
getRandomImage(random_images_array, 'images/');
}, 2000);
});
});
</script>
</head>
<body>
<button id="btn">GO</button>
</body>
</html>
How can one achieve this ?
What about creating a lastImage variable...
var random_images_array = ['1.png', '2.png', '3.png'];
var lastImage="";
Then:
var img = imgAr[num];
if (img==lastImage) {do something}
else {lastImage=img; ... document.write(imgStr);}
when i try to use javascript to start the unity webplayer inside a xhtml-file the webpage cant detect the webplayer and asks me to download it.
Same source(generated by unity itself) with .html works fine
why? :O
<script type='text/javascript' src='https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/jquery.min.js'></script>
<script type="text/javascript">
<!--
var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
if (document.location.protocol == 'https:')
unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
-->
</script>
<script type="text/javascript">
<!--
var config = {
width: 512,
height: 260,
params: { enableDebugging:"0" }
};
var u = new UnityObject2(config);
jQuery(function() {
var $missingScreen = jQuery("#unityPlayer").find(".missing");
var $brokenScreen = jQuery("#unityPlayer").find(".broken");
$missingScreen.hide();
$brokenScreen.hide();
u.observeProgress(function (progress) {
switch(progress.pluginStatus) {
case "broken":
$brokenScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$brokenScreen.show();
break;
case "missing":
$missingScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$missingScreen.show();
break;
case "installed":
$missingScreen.remove();
break;
case "first":
break;
}
});
u.initPlugin(jQuery("#unityPlayer")[0], "BulletImages.unity3d");
});
-->
</script>
<div id="unityPlayer">
<div class="missing">
<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
</a>
</div>
</div>
JavaScript isn't allowed to use document.write() on XHTML pages.
Note the offending snippet:
<script type="text/javascript">
<!--
var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
if (document.location.protocol == 'https:')
unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
-->
</script>
You may notice the script in question is performing a very simple operation. If you know your deployment, you can strip it and include the result plainly:
If deploying to HTTP website:
<script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js"></script>
If deploying to HTTPS website:
<script type="text/javascript" src="https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js"></script>
If you're not sure, an ideal fix would be to edit the page's DOM, but a quick and dirty workaround is to edit a node's innerHTML directly.