Javascript does not seem to be called - javascript

im having a problem with a javascript file possibly failing to load or containing errors
HTML Code:
<head>
<title>TEMPLATE</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="author" content="Adam Bullock">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="js/main.js"></script>
</head>
Javascript Code:
/*
* NavBar_ArrowSlider moves an arrow depending on the users move selection on
* the navigation bar
*
* The script takes a position an moves the slider image to a set margin
*
* NavElement - number of list item
* MouseEvent - if users moves out of the name bar the icon will move back to
* its default position
* DefaultPosition - number of list item
*/
function navBar_arrowSlider(navElement, mouseEvent, defaultPosition) {
var arrow = document.getElementById(navBarSlider);
var navElementPosition = ["90px","295px","493px","695px"];
// DEBUG
alert("Positon:" + navElement + " Move Event:" + mouseEvent + " default position:" + defaultPositon);
// END OF DEBUG
if (mouseEvent === "mouseOver") {
var position = navElementPosition[navElement];
arrow.style.marginLeft=navElementPosition;
} else {
var position = navElementPosition[defaultPosition];
arrow.style.marginLeft=navElementPosition;
}
}
im at a lost as to why this is not working, because i cant seem to see any errors atm, bare in mind i have been working solid for the past 14 hours :/ life of a programmer
Any help would be appreciated
Thanks
Bull

You cannot have JavaScript code in <script> tags that loads external JavaScript. You need to break them up:
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">navBar_arrowSlider(0,'moveOver',0)</script>

A <script> element can have either a "src" attribute or JavaScript content, but not both.

Related

rotating a square on the click of a button in javascript

I made a program to rotate a square made with h1 tag on the click of a button. but it is not working. could anybody take a look at this code and say what is wrong here.
// storing a button which has the id rotate1 in a variable
let button = document.querySelector("#rotate1");
// storing the square which has an id 'square' in a variable
let square = document.querySelector("#square");
let degree = 0;
// calling a function rotate on every 10 milliseconds
let a = setInterval(rotate , 10);
// defing rotate function
function rotate(){
button.onclick = ()=>{
//stop calling when the variable degree is greater than or equal to 360deg. I am doing this for stopping the square from rotating when it has comnpleted a rotation.
if(degree>=360){
clearInterval(a);
}
// else incrementing degree and rotating the square.
else{
degree++;
rotate1.style.transform = "rotateX("+degree+"deg)"
}
}
}
when i click the button the square is not rotating. Why is it not rotating. I tried my best to explain the question. could anybody tell me whats wrong here and how to solve it.
html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel = "stylesheet" href = "practise.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="square"></h1>
<button id="rotate1">Rotate</button>
<script src="practise.js"></script>
</body>
</html>
currently you rotate the button #rotate1 not h1 then it rotate the element based on click not setInterval, but you can write it like below
// storing a button which has the id rotate1 in a variable
let button = document.querySelector("#rotate1");
// storing the square which has an id 'square' in a variable
let square = document.querySelector("#square");
let degree, interval;
// defing rotate function
function rotate() {
//stop calling when the variable degree is greater than or equal to 360deg. I am doing this for stopping the square from rotating when it has comnpleted a rotation.
if (degree >= 360) {
clearInterval(interval);
}
// else incrementing degree and rotating the square.
else {
degree++;
square.style.transform = "rotateX(" + degree + "deg)"
}
}
button.onclick = () => {
degree = 0;
interval = setInterval(rotate, 10);
}
h1{display: block;width: 100px;height: 100px;background: red;}
<h1 id="square"></h1>
<button id="rotate1">Rotate</button>
Beat me to it but here's my solution...
// storing a button which has the id rotate1 in a variable
let button = document.getElementById("rotate1");
// storing the square which has an id 'square' in a variable
let square = document.getElementById("square");
let degree = 0;
button.onclick = function(event) {
degree += 360;
square.style.transform = "rotate("+degree+"deg)";
}
#square {
height:50px;
width:50px;
background-color:red;
transition:0.4s ease all;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel = "stylesheet" href = "practise.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="rotate1">Rotate</button>
<div id="square"></div>
<script src="practise.js"></script>
</body>
</html>

I dont know whats wrong with this simple javascript code, I have checked this over and over again but does not work

Simple image expanding on mouseover and opposite on mouseout, I checked the code over and over, putting alert messages at each line to see if its working, alert message work all the way to the end but there is no effect on the image. I am so confused, I dunno whats wrong.
var side = 200;
var a = 20;
var t = 0;
function expand() {
console.log("expand is ok");
clearInterval(t);
t = setInterval(grow, 20);
}
function grow() {
console.log("Entered grow");
if (side < 300) {
console.log("entered if loop");
side = side + a;
document.getElementById("new").style.width = side;
console.log("After statement")
} else
clearInterval(t);
console.log("clear")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zoom in Zoom out</title>
</head>
<body>
<img src="../images/women.jpg" id="new" alt="Women" onmouseover="expand()" width=2 00px>
</body>
</html>
To expand on my comment:
The issue is you're trying to assign a raw number such as 200 to the width CSS property.
If you look at CSS, you'd spell "200 pixels" as
foo {
width: 200px;
}
so similarly you'll need to endow the dynamic manipulation with an unit (pixels here):
foo.style.width = `${width}px`;

Load own model in TensorFlow.js for object detection

I have a question about using TensorFlow.js to detect objects with webcam. Currently I am using the pre-trained model coco-ssd.
index.html:
<html lang="en">
<head>
<title>Multiple object detection using pre trained model in TensorFlow.js</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Import the webpage's stylesheet -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Multiple object detection using pre trained model in TensorFlow.js</h1>
<p>Wait for the model to load before clicking the button to enable the webcam - at which point it will become visible to use.</p>
<section id="demos" class="invisible">
<p>Hold some objects up close to your webcam to get a real-time classification! When ready click "enable webcam" below and accept access to the webcam when the browser asks (check the top left of your window)</p>
<div id="liveView" class="camView">
<button id="webcamButton">Enable Webcam</button>
<video id="webcam" autoplay width="640" height="480"></video>
</div>
</section>
<!-- Import TensorFlow.js library -->
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs/dist/tf.min.js" type="text/javascript"></script>
<!-- Load the coco-ssd model to use to recognize things in images -->
<script src="https://cdn.jsdelivr.net/npm/#tensorflow-models/coco-ssd"></script>
<!-- Import the page's JavaScript to do some stuff -->
<script src="script.js" defer></script>
</body>
</html>
script.js:
const video = document.getElementById('webcam');
const liveView = document.getElementById('liveView');
const demosSection = document.getElementById('demos');
const enableWebcamButton = document.getElementById('webcamButton');
// Check if webcam access is supported.
function getUserMediaSupported() {
return !!(navigator.mediaDevices &&
navigator.mediaDevices.getUserMedia);
}
// If webcam supported, add event listener to button for when user
// wants to activate it to call enableCam function which we will
// define in the next step.
if (getUserMediaSupported()) {
enableWebcamButton.addEventListener('click', enableCam);
} else {
console.warn('getUserMedia() is not supported by your browser');
}
// Enable the live webcam view and start classification.
function enableCam(event) {
// Only continue if the COCO-SSD has finished loading.
if (!model) {
return;
}
// Hide the button once clicked.
event.target.classList.add('removed');
// getUsermedia parameters to force video but not audio.
const constraints = {
video: true
};
// Activate the webcam stream.
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
video.srcObject = stream;
video.addEventListener('loadeddata', predictWebcam);
});
}
// Store the resulting model in the global scope of our app.
var model = undefined;
// Before we can use COCO-SSD class we must wait for it to finish
// loading. Machine Learning models can be large and take a moment
// to get everything needed to run.
// Note: cocoSsd is an external object loaded from our index.html
// script tag import so ignore any warning in Glitch.
cocoSsd.load().then(function (loadedModel) {
model = loadedModel;
// Show demo section now model is ready to use.
demosSection.classList.remove('invisible');
});
var children = [];
function predictWebcam() {
// Now let's start classifying a frame in the stream.
model.detect(video).then(function (predictions) {
// Remove any highlighting we did previous frame.
for (let i = 0; i < children.length; i++) {
liveView.removeChild(children[i]);
}
children.splice(0);
// Now lets loop through predictions and draw them to the live view if
// they have a high confidence score.
for (let n = 0; n < predictions.length; n++) {
// If we are over 66% sure we are sure we classified it right, draw it!
if (predictions[n].score > 0.66) {
const p = document.createElement('p');
p.innerText = predictions[n].class + ' - with '
+ Math.round(parseFloat(predictions[n].score) * 100)
+ '% confidence.';
p.style = 'margin-left: ' + predictions[n].bbox[0] + 'px; margin-top: '
+ (predictions[n].bbox[1] - 10) + 'px; width: '
+ (predictions[n].bbox[2] - 10) + 'px; top: 0; left: 0;';
const highlighter = document.createElement('div');
highlighter.setAttribute('class', 'highlighter');
highlighter.style = 'left: ' + predictions[n].bbox[0] + 'px; top: '
+ predictions[n].bbox[1] + 'px; width: '
+ predictions[n].bbox[2] + 'px; height: '
+ predictions[n].bbox[3] + 'px;';
liveView.appendChild(highlighter);
liveView.appendChild(p);
children.push(highlighter);
children.push(p);
}
}
// Call this function again to keep predicting when the browser is ready.
window.requestAnimationFrame(predictWebcam);
});
}
Now I would like to customize the script to use my own model, which I previously created and trained with Tensorflow for Python. I have already converted it with the converter tfjs_convert into a .json format.
Files of my own model
How do I modify my code so that my own model is now used? I have already tried a few things, but unfortunately have not made any progress.
You can use loadGraphModel from #tensorflow/tfjs-converter to load from Json.
I love this example.

Morphing with Velocity.js doesnt work

Hej,
i have this plunker: http://plnkr.co/edit/bKzi6rU3lIXT4Nz2wkR8?p=info
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="stilovi/main.css">
<title>Testing</title>
</head>
<body>
<div id="avengers"></div>
</body>
<script src="snap.svg-min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://rawgit.com/julianshapiro/velocity/master/velocity.min.js"></script>
<script>
function fetchXML(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function(evt) {
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
callback(xhr.responseXML);
}
};
xhr.send(null);
};
/*var list = ["test3.svg","test.2svg"];*/
//fetch the document
fetchXML("test3.svg", function(newSVGDoc) {
//import it into the current DOM
var n = document.importNode(newSVGDoc.documentElement, true);
document.getElementById("avengers").appendChild(n);
var ironman = document.getElementsByTagName("polygon");
var ironmanlist = Array.prototype.slice.call(ironman);
/*alert(ironmanlist.length);*/
ironmanlist.forEach(function(elem, i) {
/*for (var index = 0; index < elem.points.length; ++index){
//2.test case morphing each point (not working)//
console.log(elem.points[index]);
$.Velocity(elem.points[index],{x:100,y:100},{duration:Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000}, "ease-in-out");
//3.test case morphing each point in another way (not working)//
/*$(elem.points[index])
.velocity({x:100,y:100},{duration:Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000}, "ease-in-out");
console.log(elem.points[index]);
}*/
//1. working test case (translation)//
console.log(elem.points[0].x);
$.Velocity(elem, {
translateX: -300
}, {
duration: Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000
}, "ease-in-out");
//$.Velocity(elem,{rotateZ:"45deg"},{duration:Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000}, "ease-in-out");
console.log(elem.points[0].x);
//End of 1. working test case//
});
console.log(ironmanlist);
});
</script>
</html>
With my code, and some examples. What I want to do is morph each polygon from one SVG image, into another polygon from another SVG image. The translation works, but I'm not sure how to do a morph.
Can anyone help, or check the code and tell me what I am doing wrong?
There are a lot of polygons, and I need it to be fast so i went with velocity.js for this.
I was also thinking of maybe moving it all to three.js, and maybe convert it to a format that would be best to use with three.js. But if it is a possibilty to use it as svg and keep a great performance i would do so.
As far as I'm aware, velocity.js doesn't support this as (taken from their website):
In general, Velocity can animate any property that takes a single numeric value.
As SVG paths usually (always?) consist of multiple values, morphing is way beyond their current scope.
However, I can highly recommend Snap for morphing SVG paths.

clientWidth and clientHeight delayed on Android default browser?

I am using jqtouch.js (with zepto.js) and testing the onorientationchange event:
http://www.ebi.ac.uk/~mp/test_orientation.html
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<!-- Local jqTouch -->
<link rel="stylesheet" href="lib/jqtouch-1.0-b4-rc/themes/css/apple.css" title="jQTouch">
<!-- <style type="text/css" media="screen">#import "lib/jqtouch-1.0-b4-rc/themes/css/jqtouch.css";</style> -->
<script src="lib/jqtouch-1.0-b4-rc/src/lib/zepto.min.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/jqtouch-1.0-b4-rc/src/jqtouch.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQTouch({});
</script>
</head>
<body>
<h1>Hello World</h1>
<script>
window.onorientationchange = function() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
alert("WIDTH: " + w + " -- HEIGHT: " + h);
}
</script>
</body>
</html>
Opening this page with the default Android browser I get the clientWidth and clientHeight numbers reversed (when changing the orientation to landscape, I get more height than width, and vice-versa).
If I insert a short delay:
http://www.ebi.ac.uk/~mp/test_orientation_delay.html
<script>
window.onorientationchange = function() {
setTimeout(function() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
alert("WIDTH: " + w + " -- HEIGHT: " + h);
}, 500);
}
</script>
The clientWidth and clientHeight are properly retrieved.
This doesn't happen with Safari (iOS5) or Chrome (they don't need the short delay to display the correct numbers).
Is there an alternative way to safely retrieve these numbers consistently (without having to introduce an arbitrary delay that can be enough or not)?
M;
Possibly too late, but I think this has to do with the fact that when the event fires you're still looking at the BEFORE state. The new state will occur AFTER the event, as the event only tells you "I am ABOUT to change orientation, but didn't do it yet."

Categories

Resources