Applying Transition To Injected html in Javascript - javascript

I've been working with JS for about two weeks, and I'm working on a little project. The goal was to be able to change the color on each individual character in a given string when pressing the button. I've gotten that far.
As you can see, I added spans to each character, so that I can individually edit them. I'm trying to apply a transition to the spans so that when I click the button, the color fades to another color instead of just instantaneously changing. Is that possible?
Here's the codepen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="CSS/textColorV2.css">
</head>
<body>
<p id="letter">Color</p>
<button>Click ME</button>
<script type="text/javascript" src="JS/textColorV2.js"></script>
</body>
</html>
CSS
bodybody {
background-color: #FFE7E0;
}
span{
transition: all 4s;
}
#letter {
font-size: 9em;
position: absolute;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
color:blue;
}
JS
var letter = document.getElementById("letter");
var text = letter.innerHTML;
var button = document.querySelector("button");
button.addEventListener("click", function () {
var newText = "";
for (var i = 0; i < text.length; i++) {
newText += '<span style="color:' + randomColor() + '">' +
text.charAt(i) + '</span>';
letter.innerHTML = newText;
letter.classList.add("trans");
};
});
function randomColor() {
//r
var r = Math.floor(Math.random() * 256);
//g
var g = Math.floor(Math.random() * 256);
//b
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + " ," + g + " ," + b + ")";
}

This is absolutly possible. The key idea here is to separate your string into span elements (per character) at the start of your script, rather than during each click event.
Taking this approach will simplify your implementation - all you need to do in the button click handler is assign a new "random color" to each span element, and leave the CSS transition(s) to the browser to handle:
var letter = document.getElementById("letter");
var text = letter.innerHTML;
var button = document.querySelector("button");
// Convert inner text node to span nodes for each character
// at beginning of script
var text = letter.innerText;
letter.innerText = '';
for(var i = 0; i < text.length; i++) {
var character = text[i];
letter.innerHTML += '<span style="color:' + randomColor() + '">' + character + '</span>';
}
button.addEventListener("click", function () {
// For each span/character of #letter, assign a new random
// color. This causes the browser to handle the CSS color
// transition for you
for(var span of document.querySelectorAll('#letter span')) {
span.style.color = randomColor();
}
});
function randomColor() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + " ," + g + " ," + b + ")";
}
span{
transition: all 4s;
}
#letter {
font-size: 9em;
position: absolute;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
color:blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="CSS/textColorV2.css">
</head>
<body>
<p id="letter">Color</p>
<button>Click ME</button>
</body>
</html>

Here is a more concise version of the same...
const letters = document.querySelectorAll('.letters');
const button = document.querySelector('button');
button.addEventListener('click', () => {
letters.forEach(element => {
element.style.transition = '1s';
element.style.color = randomColor();
});
});
const randomColor = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r} ,${g},${b})`;
};
body {
background-color: #ffe7e0;
}
#wrapper {
font-size: 4em;
position: absolute;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body>
<div id="wrapper">
<span class="letters">C</span>
<span class="letters">o</span>
<span class="letters">l</span>
<span class="letters">o</span>
<span class="letters">r</span>
</div>
<button>Click ME</button>
<script src="index.js"></script>
</body>
</html>

Related

how do i apply magentic effect to all sides (left , right , bottom) it only applies it to the top currently

guys how do i apply the magnetic effect to all sides left,bottom,right. right now it only applies it top part
her the vid of it https://youtu.be/M1F6CR2cs44
i want it to be like this without the color change and also i didnt use the code of this video as its not fitting into my code i used the magentic effect code from another website.
https://www.youtube.com/watch?v=8befSxPPKpY
const btns = document.querySelectorAll(".navv");
btns.forEach((btn) => {
btn.addEventListener("mousemove", function(e){
const position = btn.getBoundingClientRect();
const x = e.pageX - position.left - position.width / 2;
const y = e.pageY - position.top - position.height / 2;
btn.children[0].style.transform = "translate(" + x * 0.3 + "px, " + y * 0.5 + "px)";
});
});
btns.forEach((btn) => {
btn.addEventListener("mouseout", function(e){
btn.children[0].style.transform = "translate(0px, 0px)";
});
});
<!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>store</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.cdnfonts.com/css/metropolis" rel="stylesheet">
</head>
<body>
<nav class="firstnav">
<img src="imgs/logo.png" alt="" class="logo">
<ul>
<li>Shop</li>—
<li>Community</li>—
<li>Catalogue</li>
</ul>
<div class="navv">
<div class="navm" g-component="SampleComponent">
<img src="imgs/menu.png" alt="" id="fanav" onclick="nav()">
</div>
</div>
Cart 0
<script src="script.js"></script>
</nav>
</body>
</html>
The crucial part is that you didn't include your css. The properties of the element (the size of each navv in your example) will determine at which point the mouseover event will be triggered.
To simplify the issue I've added a more minimal example. I have an anchor which contains a span. as you can see as soon as you enter the blue area, the event will be triggered (since you put the event listener on the anchor) and the span will move. If you can't make it work with this example, please include your css.
const btns = document.querySelectorAll(".btn");
btns.forEach((btn) => {
btn.addEventListener("mousemove", function(e){
const position = btn.getBoundingClientRect();
const x = e.pageX - position.left - position.width / 2;
const y = e.pageY - position.top - position.height / 2;
btn.children[0].style.transform = "translate(" + x * 0.3 + "px, " + y * 0.5 + "px)";
});
});
btns.forEach((btn) => {
btn.addEventListener("mouseout", function(e){
btn.children[0].style.transform = "translate(0px, 0px)";
});
});
.btn{
position: relative;
text-align: center;
cursor: pointer;
}
.btn span{
position: relative;
display: inline-block;
color: #000000;
font-size: 1.2em;
font-weight: 500;
text-decoration: none;
width: 120px;
margin: 150px;
border-radius: 8px;
background-color: grey;
transition: transform 0.15s linear;
}
a {
background-color: blue;
}
<a href="#" class="btn">
<span>Hover Me</span>
</a>

Having problems to generate a random array and visualize it using <div> elements in VS Code?

I am a beginner at web dev and am trying to build a sorting visualizer.
I am unable to get the output for generating a visualization of a random array by using the (div)
element of html.
This is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sorting visualizer</title>
<style>
/* *{
margin: 0;
padding: 0;
} */
#array_container{
position: absolute;
left: 100px;
right: 100px;
bottom: 100px;
height: 100%;
width: 100%;
/* margin-left: 50px;
margin-right: 50px; */
background-color: turquoise;
}
</style>
</head>
<body>
<script>
function random_array(min, max){
return Math.floor(Math.random() * (max - min)) + min;
function generate_array(){
var cont = document.getElementById("array_container");
var bar;
var arr = [];
for ( var i = 0; i < 100; i++){
arr.push(random_array(5, 1000));
bar = document.createElement("div");
bar.style = "height:"+arr[i]+";width:2px;margin:0 1px;background-color:pink;display:inline-block;";
cont.appendChild(bar);
}
}
}
</script>
<div id="array_container">
</div>
<button id="btn1" onclick="generate_array">generate</button>
</body>
</html>
please help me by finding the ERROR and also suggest me some other methods for visualizing array in a bar graph format.
A couple minor syntax bugs I found:
You're missing the parenthesis () at the end of your function name when you pass it to the generate button's onclick
The brackets around your functions were offset, which was causing errors
Your code isn't broken beyond those minor syntax bugs, the problem you're facing is that your generated divs aren't respecting the height you're passing them, because you didn't give them a height unit.
You need to specify a unit like px, otherwise the height will get thrown out and ignored.
Working example (You'll want to adjust some other styles if you want them to fit in your box):
function random_array(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function generate_array() {
var cont = document.getElementById("array_container");
var bar;
var arr = [];
for (var i = 0; i < 100; i++) {
arr.push(random_array(5, 1000));
bar = document.createElement("div");
bar.style = "height:" + arr[i] + "px;width:2px;margin:0 1px;background-color:pink;display:inline-block;";
cont.appendChild(bar);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sorting visualizer</title>
<style>
#array_container {
position: absolute;
left: 100px;
right: 100px;
bottom: 100px;
height: 100%;
width: 100%;
background-color: turquoise;
}
</style>
</head>
<body>
<div id="array_container"></div>
<button id="btn1" onclick="generate_array()">generate</button>
</body>
</html>

Evenly distribute points on a circle

I need to distribute points evenly on a circumference of a circle, and I'm out of my wits. The result is not exactly circular but rather spiraly, especially with larger numbers of points. I've researched it vigorously but still can't figure out where I could make a mistake.
window.onload = function() {
var num = 15;
var angle = (2 * Math.PI)/(num+1); var count = 0;
var demo = document.getElementById("demo");
function Dot() {
this.angle = angle * count;
count++;
this.x = Math.cos(this.angle) * 200;
this.y = Math.sin(this.angle) * 200;
}
Dot.prototype.create = function() {
var dot = document.createElement("div");
dot.style.top = this.y + 100 + "px";
dot.style.left = this.x + 200 + "px";
dot.className = "dot";
demo.appendChild(dot);
}
for (var i = 0; i < num; i++) {
var d = new Dot();
d.create();
}
}
.dot {
height: 20px;
width: 20px;
border-radius: 50%;
background: blue;
position: relative;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>Metcalfe's Law Demo</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="container">
<div id="demo">
</div>
</div>
</body>
</html>
The main mistake is bloody simple - just change the style position: relative to position: absolute:
window.onload = function() {
var num = 12;
var angle = (2 * Math.PI)/(num); var count = 0;
var demo = document.getElementById("demo");
console.log(angle)
function Dot() {
this.angle = angle * count;
count++;
console.log(this.angle,count)
this.x = Math.cos(this.angle) * 200;
this.y = Math.sin(this.angle) * 200;
}
Dot.prototype.create = function() {
var dot = document.createElement("div");
dot.style.top = this.y + 200 + "px";
dot.style.left = this.x + 200 + "px";
dot.className = "dot";
demo.appendChild(dot);
}
for (var i = 0; i < num; i++) {
var d = new Dot();
d.create();
}
}
.dot {
height: 20px;
width: 20px;
border-radius: 50%;
background: blue;
position: absolute;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>Metcalfe's Law Demo</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="container">
<div id="demo">
</div>
</div>
</body>
</html>

Javascript creating 5 img in div createElement

I am trying to create 5 images in 5 different places inside my div#leftside. I do create 5 images, but they are in the same position and are not randomly spread inside my div. Here is a code... Can someone help?
<!DOCTYPE html>
<html lang="en">
<head http-equiv="content-type" content="text/html; charset=utf-8">
<title>Matching game</title>
<style type="text/css">
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script type="text/javascript">
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
if (i < 5){
numberOfFaces = document.createElement("img");
i++;
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}
}
</script>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
You were using an if statement when you intended a while loop. Also, you needed to move the positioning logic into the loop.
https://jsfiddle.net/knwL2bn4/
Refactor:
<!DOCTYPE html>
<html lang="en">
<head http-equiv="content-type" content="text/html; charset=utf-8">
<title>Matching game</title>
<style type="text/css">
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script type="text/javascript">
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
while (i < 5){
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
numberOfFaces = document.createElement("img");
i++;
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}
}
</script>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
You should use for loop
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i;
for (i = 0; i < 5; i += 1) {
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
numberOfFaces = document.createElement("img");
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}
}
Not quite sure what you are trying to do there, but I rewrote it in a Fiddle. You might have to tweak it to get it to do what you want:
Fiddle
HTML
<body>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
Javascript
function generateFaces() {
var face;
var theLeftSide = document.getElementById("leftSide");
for (i = 0; i < 5; i++) {
var topvar = (Math.floor(Math.random() * 400));
var leftvar = (Math.floor(Math.random() * 400));
face = document.createElement("img");
face.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
face.style.top = topvar + 'px';
face.style.left = leftvar + 'px';
theLeftSide.appendChild(face);
}
}
generateFaces();
CSS
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}

Javascript/JQuery Math.random to onclick fade to

I am making a simple game for my school project and the basic Idea is when you press a button to start the game random images will fade in and you have to click as many of them as you can in 30 seconds. I am using Math.random and Javascript for if statements and JQuery for its built in onclick and fadeTo. The function is not working however and I dont know why.Here is my html
<!DOCTYPE html>
<html>
<head>
<title>My test game</title>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Click as many as you can in 30 seconds</h1>
<input id="clickMe" type="button" value="clickme"onclick="randomNumFunc();" />
<!-- Game Area -->
<div id="game-area">
<div id="circle1"></div>
</div>
<!-- Javascript/Jquery -->
<script src="js/JQuery.js"></script>
<script src="js/script.js"></script>
</body>
CSS:
body {
background-color: #CEF6F5;
}
#game-area {
border: 5px solid black;
height: 500px;
background-color: white;
}
#circle1 {
-moz-border-radius: 50px/50px;
-webkit-border-radius: 50px 50px;
border-radius: 50px/50px;
border: solid 21px #f00;
width: 50px;
height: 50px;
opacity: 0.5;
}
and Javascript/Jquery:
/* RNG variable */
var randomNum = Math.floor((Math.random() * 3) + 1);
/* Picture Assignments */
var pic1 = 1;
var pic2 = 2;
var pic3 = 3;
/* RNG Code */
function randomNumFunc() {
document.getElementById('#circle1').innerHTML;
if (randomNum == 1) {
$(document).ready(function() {
$(document).fadeTo('fast', 1);
});
$(document).onclick(function() {
$(document).fadeTo('fast', 0);
});
}
}
Your <input> element should be,
<input id="clickMe" type="button" value="clickme"/>
And the javaScript/jQuery code look like,
$(document).ready(function() {
var randomNum = Math.floor((Math.random() * 3) + 1);
$('#clickMe').click(function(){
if(randomNum == 1){
$('#circle1').fadeTo('fast', 1);
}
else{
$('#circle1').fadeTo('fast', 0);
}
})
});
I think that this is what you want:
script.js:
$(document).ready(function() {
var pic1 = 1;
var pic2 = 2;
var pic3 = 3;
var randomNum = Math.floor((Math.random() * 3) + 1); //every time you click it, will be generate a new randonNum
console.log(randoNum); //It will show in console the number
$('#clickMe').click(function() {
if (randomNum == 1) {
$('#circle1').fadeIn('fast');
} else {
$('#circle1').fadeOut('fast');
}
});
});
and you can remove the onClick method in the input:
<input id="clickMe" type="button" value="clickme" />

Categories

Resources