Button not calling function correctly - javascript

I am trying to call a function on a button click, but for some reason the button will not call the function. Dreamweaver does not show any syntax errors. Can anyone tell me why the button is not working?
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
</head>
<head>
<title></title>
<script type="text/javascript">
var imgObj = 0;
var imgObj1 = 0;
var animate;
var animate1;
function init(){
imgObj = document.getElementById('red');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj1 = document.getElementById('blue');
imgObj1.style.position = 'relative';
imgObj1.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left = 0) + Math.floor((Math.random() * 100) + 1) + 'px';
animate = setTimeout(moveRight(), 1000);
imgObj1.style.left = parseInt(imgObj1.style.left = 0) + Math.floor((Math.random() * 100) + 1) + 'px';
animate1 = setTimeout(moveRight(), 1000);
if (imgObj.style.left >= 1000px || imgObj1.style.left >= 1000px)
{
break;
else if
{
imgObj.style.left>= 1000
MessageBox.show("The Red Car has won the Race!");
}
else
{
MessageBox.show("The Blue Car has won the Race!");
}
}
}
</script>
</head>
<body onload = "init()">
<form>
<input type="button" value="Start" onclick="moveRight()" />
<br/><br/><br/><br><br/><br/><br/>
<img id="red" src="redcar.png" alt="Car 1"/>
<br/><br/><br/><br>
<img id="blue" src="bluecar.png" alt ="Car 2" />
</form>
</body>
</html>

Unfortunately there are so many errors that it's difficult to know where to start. The first answer to your question is that the button did nothing because your code doesn't compile. I don't know why Dreamweaver didn't report an error. Chrome's developer tools was more than happy to do so.
Here's a "working" version:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var imgObj = 0;
var imgObj1 = 0;
var animate1;
function init(){
imgObj = document.getElementById('red');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj1 = document.getElementById('blue');
imgObj1.style.position = 'relative';
imgObj1.style.left = '0px';
}
function moveRight(){
var redPosition = parseInt(imgObj.style.left);
imgObj.style.left = redPosition + Math.floor((Math.random() * 20) + 1) + 'px';
var bluePosition = parseInt(imgObj.style.left);
imgObj1.style.left = bluePosition + Math.floor((Math.random() * 20) + 1) + 'px';
if (redPosition >= 1000 || bluePosition >= 1000)
{
if (redPosition >= 1000) {
alert("The Red Car has won the Race!");
}
else
{
alert("The Blue Car has won the Race!");
}
return;
}
animate1 = setTimeout(moveRight, 50);
}
</script>
</head>
<body onload = "init()">
<form>
<input type="button" value="Start" onclick="moveRight()" />
<br/><br/><br/><br><br/><br/><br/>
<img id="red" src="redcar.png" alt="Car 1"/>
<br/><br/><br/><br>
<img id="blue" src="bluecar.png" alt ="Car 2" />
</form>
</body>
</html>

Related

How to make a button move?

I'm going to make 8 buttons move down to the bottom of screen one by one but I have a problem
here is my code :
var i = 0;
var j = 0;
while(i < 7){
i++;
interval[i] = setInterval(interval(), 10);
function interval(){
y[j]++;
if (parseInt(y[j]) >= window.innerHeight) {
if(j == y.length - 1){
debugger;
return clearInterval(interval[j]);
}
j++;
return interval();
}
button[j].style.top = y[j] + "px";
}
console.log(i);
}
var body = document.getElementById("body");
var button = [];
body.style.position = "relative";
var y = [];
for (var i = 0; i < 8; i++) {
y[i] = 0;
button[i] = document.createElement("button");
button[i].onclick = clickme();
button[i].innerHTML = "بازی";
button[i].style.fontFamily = "b nazanin";
button[i].style.fontSize = "32pt";
button[i].style.position = "absolute";
body.appendChild(button[i]);
}
var i = 0;
var j = 0;
var Interval = setInterval(interval(), 10);
function interval(){
y[j]++;
if (parseInt(y[j]) >= window.innerHeight) {
if(j == y.length - 1){
debugger;
return clearInterval(Interval[j]);
}
j++;
return interval();
}
button[j].style.top = y[j] + "px";
}
/*
var button2 = document.createElement("button");
button2.onclick = clickme();
button2.innerHTML = "بازی";
button2.style.fontFamily = "b nazanin";
button2.style.fontSize = "32pt";
body.appendChild(button);
body.appendChild(button2);
body.style.position = "relative";
button2.style.position = "absolute";
button.style.position = "absolute";
*/
function clickme() {
}
<!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>Document</title>
<link rel="stylesheet" href="index.css">
</head>
<body id="body">
</body>
<script src="index.js"></script>
</html>
Code explained :
button is my buttons element array.
y is my button's Tops array.
My problem is that the first button will move 7 times(Number of Is) and anything stop.I don't know what to do.
Please help me.
Ok, I did it with just 2 buttons and it worked :
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var startNext = false;
var y1 = 0;
var y2 = 0;
var interval1 = setInterval(function(){
y1++;
button1.style.top = y1 + "px";
if(y1>= window.innerHeight){
startNext = true;
return clearInterval(interval1);
}
},10);
var interval2 = setInterval(function(){
if(startNext){
y2++;
button2.style.top = y2 + "px";
if(y2 >= window.innerHeight){
return clearInterval(interval2);
}
}
},10);
<!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>Document</title>
<link rel="stylesheet" href="index.css">
</head>
<body id="body" style="position: relative;">
<button id="button1" style="position: absolute;">graege</button>
<button id="button2" style="position: absolute;">ges</button>
</body>
<script src="index.js"></script>
</html>

Got a persistent change font size slider in Jquery but need help to turn into Vanilla js

Now I have this Jquery font rezising slider but need it in vanilla.js. It is working properly but I can not manage turning it into plain Javascript.
My code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1" />
</div>
<div>
<h1>Changing Font Size</h2>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
if (curSize) {
var saveSize = curSize;
$('body').css('font-size', saveSize + 'px');
var setSize = $('body').css('font-size');
}
$('.font-slider input[type="range"]').on("input change", function () {
var newSize = $(this).val(),
defaultSize = $("body").css("font-size"),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
$("body").css("font-size", newSize + "px");
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>
Try:
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
if (curSize) {
var saveSize = curSize;
body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function (e) {
var newSize = this.value,
defaultSize = body.style.getPropertyValue('font-size'),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});

storing high score with javascript

I have practiced one question and this is about checking time to click the shape that comes up. I want to save the the high score and compare with the next one coming up. It is just how to store the high score . It would be great help if somebody give the way to do it. Thank you in advance
<!doctype html>
<html>
<head>
<title> Javasript </title>
<style type="text/css">
#shape {
width: 200px;
height: 200px;
display:none;
position : relative;
}
</style>
</head>
<body>
<h1>Test your reaction </h1>
<p>Click on the boxes as soon as possible and win it </p>
<p>Your time taken <span id="timeTaken"></span></p>
<div id="shape"></div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var top = Math.random() * 400 ;
var left = Math.random() * 400 ;
var width = (Math.random() * 200) + 100 ;
if (Math.random()> 0.5) {
document.getElementById("shape").style.borderRadius = "50%";
} else {
document.getElementById("shape").style.borderRadius = "0%"; }
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.width = width + 'px';
document.getElementById("shape").style.top = top + 'px';
document.getElementById("shape").style.left = left + 'px';
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.display = 'block';
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, Math.random() * 2000 );
}
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = 'none';
var end = new Date().getTime();
var timeTaken = (end - start)/1000;
document.getElementById("timeTaken").innerHTML = timeTaken + "s";
appearAfterDelay();
}
</script>
</body>
</html>

Javascript: code with no animation with requestAnimationFrame?

I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?
<!doctype html>
<html>
<head>
<title> My home page </title>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
//alert(count);
//++count;
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time ;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
</script>
</head>
<body>
<p style ="text-align: center">
<img src ="img/cat.jpg" style ="position: relative">
</p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>
Thank you for the help.
If you look at the console, you will see that the cat is undefined.
This happens because var cat = document.querySelector("img"); is run in the head element and so the img does not exist yet.
If you move the code at the end of the body it will work.
Or you could run your code when the DOMContentLoaded event is fired.
<!doctype html>
<html>
<head>
<title> My home page </title>
</head>
<body>
<p style ="text-align: center">
<img src ="img/cat.jpg" style ="position: relative">
</p >
</body>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
//alert(count);
//++count;
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time ;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
</script>
<script>requestAnimationFrame(animate);</script>
</html>
When the browser see a <script> tag, he stop rendering the page, and run the code inside.
So, the problem in the code that the line var cat = document.querySelector("img"); happen before the img is append to the document, so you query get nothing.
the only change you need to do- is to move the var cat = document.querySelector("img"); to under the body, like so:
</body>
<script>
var cat = document.querySelector("img");
requestAnimationFrame(animate);
</script>
</html>

How do I separate two svgs using raphaël?

I'm a beginner beginner. I can get the behavior that I want to occur, but instead of occurring in two separate SVGs, all the behavior is occurring in 'svg2' although I have selected the respective ids for 'svg1' and 'svg2' (or at least I think I did)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.0/raphael-min.js"></script>
<script src="logic.js"></script>
<title>Forms and Concentric Circles</title>
</head>
<body>
<h1>Forms and Concentric Circles</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
var paper;
disappear = function() {
this.remove();
}
spin = function(r) {
angle = Math.random()*1440 - 720;
initial = { 'transform': 'r0' }
final = { 'transform': 'r' + angle}
r.attr(initial);
r.animate(final, 2000);
}
addMore = function() {
rectNum = $('#howmany').val();
for (step = 0; step < rectNum; step += 1) {
x = Math.random() * 180;
y = Math.random() * 180;
r = paper.rect(x, y, 20, 20);
filled = {
'fill': '#ddf'
}
r.attr(filled);
r.click(disappear);
spin(r);
}
}
radius = 10
morecircles = function() {
paper.circle(100, 100, radius);
radius = radius + 10;
}
setup = function() {
paper = Raphael('svg1', 200, 200);
$('#more').click(addMore);
paper = Raphael('svg2', 200, 200);
$('#another').click(morecircles);
}
$(document).ready(setup);
change the name for the second svg for example
paper2.circle
and in your setup function it should be
paper2.Raphael('svg2',200,200)

Categories