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>
Related
I tried set my path with link from web and path of PC and didn't work, ever display this green square my screen:
My game.ejs file:
<!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">
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.min.js"></script>
<title>Document</title>
</head>
<body>
<script>
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'phaser-example',
physics: {
default: 'arcade'
},
scene: {
preload: preload,
create: create,
update: update
}
};
var debug;
var source;
var target = new Phaser.Math.Vector2();
var distanceText;
new Phaser.Game(config);
function preload ()
{
this.load.image('worm', 'assets/worm.png');
}
function create ()
{
source = this.physics.add.image(100, 300, 'worm');
debug = this.add.graphics();
this.input.on('pointerdown', function (pointer) {
target.x = pointer.x;
target.y = pointer.y;
this.physics.moveToObject(source, target, 250);
}, this);
distanceText = this.add.text(10, 10, 'Click to set target', { fill: '#00ff00' });
}
function update ()
{
var distance = Phaser.Math.Distance.Between(source.x, source.y, target.x, target.y);
if (source.body.speed > 0)
{
distanceText.setText('Distância: ' + distance);
if (distance < 4)
{
source.body.reset(target.x, target.y);
}
}
}
</script>
</body>
</html>
That's like I said, nothing worked with url or path from my pc, I just want to display my sprite player on screen without that green square and I saw another questions, but nothing offered me a solution, what can I do?
It seems like it can't find the image its looking for, which means that either it doesn't exist, or more likely it doesn't exist in the location you've provided.
If you're serving this web page from the root (aka it's visible on http://localhost or http://127.0.0.1 than you could try simply adding a / in front of the path, as such: /assets/worm.png, the leading / means it'll search for the asset from the root of your webpage.
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`;
I am trying to make a game with HTML, CSS and JS which involves a typewriting animation.
I want a custom function which when called, typewrites some text. However, there is a problem when using the function multiple times. The function combines the text from the different strings which are inputted. in the function. Please help me find a solution to this. My code is similar to the W3 Schools example code with a few changes.
var txt, speed, i;
function typeWriter() {
if (i < txt.length) {
document.getElementById("text").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
function write(whatToWrite, howFast) {
i = 0;
txt = whatToWrite;
speed = howFast;
typeWriter();
}
//There is a problem when called multiple times
write("hello", 100);
write("world", 100);
html{
background-color: #0a1c08;
color: #ffffff;
font-size: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>The Game of Destiny</title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p id="text"></p>
</body>
</html>
<script src="typewriter.js"></script>
Like the first comment said,setTimeout doesn't block, and the next write is executed immediately. To prevent this behaviour, you need to block the execution somehow. One way would be to use a callback in the timeout function, another to await a Promise. A good explanation can be found in this post.
To solve the problem, I used a custom sleep function, which blocks the execution as long as the typing animation goes. It is not perfect and could use some more refinement, but it works.
var speed;
function typeWriter(i, txt) {
if (i < txt.length) {
document.getElementById("text").innerHTML += txt.charAt(i);
i++;
setTimeout(() => typeWriter(i, txt), speed);
}
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
};
async function wrapper() {
let word = "hello";
speed = 100;
await typeWriter(0, word);
await sleep(word.length * speed);
word = "world";
speed = 200;
await typeWriter(0, word);
}
wrapper()
html{
background-color: #0a1c08;
color: #ffffff;
font-size: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>The Game of Destiny</title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p id="text"></p>
</body>
</html>
<script src="typewriter.js"></script>
setTimeout doesn't block, and the next write is executed immediately after the first write has printed the first character. Then i will be reset to 0, and only the second call of write executes correctly.
This can be fixed by using promises, or simply by chaining the words to type in write function, like this:
var txt = '',
i = 0,
pad = document.getElementById('text'),
speed;
function typeWriter() {
if (i < txt.length) {
pad.insertAdjacentText('beforeEnd', txt.charAt(i));
i++;
setTimeout(typeWriter, speed);
}
}
function write(whatToWrite, howFast) {
txt += whatToWrite;
speed = howFast;
typeWriter();
}
write('hello', 100);
write(' world', 100);
html {
background-color: #0a1c08;
color: #ffffff;
font-size: 20px;
}
<p id="text"></p>
Notice, that txt and i are now initialized at the top scope instead of write function. I've also defined the element to type to outside of the function, and used insertAdjacentText instead of innerHTML. These changes make the code a bit lighter to run, specifically if you're going to type very long texts to the paragraph.
I am using a video input to draw onto a canvas in order to get the color of the pixel in the very middle of the canvas.
With the recent code I have the pixel color and pass it as a color value to draw a line. This line should run from left to right drawing the different colors of the video onto the canvas and add up with every line. But the line seems to be overwritten with every frame. Only one line is displayed which is moving from left to right. Can someone help me understand why and how I can change this behavior?
Thank you very much in advance.
let movie;
let playButton;
let movieInput = "/public/IMG_1569.m4v";
var playing = false;
function setup() {
let canvas = createCanvas(534, 300);
pixelDensity(1);
movie = createVideo(movieInput);
movie.size(width, height);
playButton = createButton("play").addClass("button");
playButton.mouseClicked(playVideo);
}
function draw() {
if (playing) {
movie.loadPixels();
var i = image(movie, 0, 0, width, height);
let pixelColor = get(width / 2, height / 2);
background(255);
let px = frameCount % width;
stroke(pixelColor);
var fineLine = line(px, 0, px, height);
}
}
function playVideo() {
if (playing) {
movie.pause();
playButton.html("play");
} else {
movie.play();
playButton.html("pause");
}
playing = !playing;
}
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/public/style.css">
<title>p5.js example</title>
</head>
<body>
<h1>p5 no.1</h1>
<script src="/lib/p5.js"></script>
<script src="/lib/p5.dom.js"></script>
<script src="/sketch.js"></script>
</body>
</html>
The call to background() clears out old frames.
If you want old frames to stay on the screen, remove the call to background() in your draw() function.
More info can be found in the reference. I'd also recommend reading through your code and making sure you understand every line. It might help to read it out loud, or to write down an English description of every line. That will help you find issues like this in the future.
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.