Changing onClick of a span when it is clicked using JS - javascript

I've created a program that randomly spawns a span (in the form of a circle). I want to change the onClick of the previous span class when clicked on.
I've already attempted to set the id of the new span element to something that creates recursively (span.id = "a" + t; t++;) or something like that.
<!doctype html>
<link href="https://fonts.googleapis.com/css?
family=Montserrat" rel="stylesheet">
<link rel="icon" type="image/jpg" href="/vNidjVg-
_400x400.jpg"/>
<style>
body{
background-color: #010417;
font-family: 'Montserrat', sans-serif;
}
#keyframes a{
0% {opacity: 0;}
100%{opacity: 1;}
}
button{
background-color: #010417;
border-radius: 10px;
border: 4px solid white;
color: white;
padding: 10px 26px;
font-size: 20px;
}
</style>
<div id="myDIV">
<script>
document.title = prompt("I don't know what to make the
document's title, so what do you want it to be called?");
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
var but = 2;
var x = 0
function button(){
if(but === 2){
myFunction();
but = 0;
}else{}
}
var t = 0;
var q = -1;
function myFunction() {
var para = document.createElement("SPAN");
para.style.position = "absolute";
x = getRndInteger(0, (window.innerWidth - 60))
para.style.left = x + "px"
var p = getRndInteger(0, (window.innerHeight - 60))
para.style.top = p + "px"
para.style.display = "inline-block;"
para.style.height = "50px"
para.style.width = "50px"
para.style.backgroundColor="red"
para.style.borderRadius = "50px"
para.style.border = "1px solid black"
para.style.animation = "1s a linear"
para.id = "a" + t;
document.getElementById("a" + q).onclick=f
q++
t++;
para.onclick=myFunction
document.getElementById("myDIV").appendChild(para);
}
function f(){}
</script>
</div>
<center>
<button class="1" id="button" onClick="button();">Start</button></center>
I expect the output of this to be the previous span class to be disabled (onclick set to f())

Firstly, you should define as much of the style of your elements as possible in CSS instead of defining it in Javascript.
Secondly, when a onclick is called in JS, the first parameter of the function should be event which is a representation of the click event that just appeared. Here in the onclick you can get the clicked element with event.toElement which allows you to redefine onclick.
I think what you are trying to do should look like something like this :
var container = document.getElementById("container");
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
function spawn() {
var span = document.createElement("SPAN");
span.style.left = getRndInteger(30, (container.offsetWidth - 30)) + "px";
span.style.top = getRndInteger(30, (container.offsetHeight - 30)) + "px";
span.onclick = fA;
container.appendChild(span);
}
function fA(event) {
var span = event.toElement
alert("first click here");
span.onclick = fB;
}
function fB(event) {
alert("second click here");
}
div#container {
width: 300px;
height: 300px;
}
div#container span {
width: 30px;
height: 30px;
position: absolute;
border-radius: 100%;
background-color: red;
}
<button onclick="spawn()">Spawn a span</button>
<div id="container"></div>

Related

RGB Color Game if block sometime work and sometime won't work

Hey I am try to create a RGB Color game, here I am facing a Issue that when I refers the tab then inside my randomDiv() function there is a If block(color_fix) which is sometime working and sometime won't working you can check through clicking on refresh tab button inside console, please solve this problem
let first_div = document.getElementById('first_div');
let h4 = document.querySelector('h4');
let h1 = document.createElement('h1');
let color_div = document.querySelector('#color_div');
let createDiv;
h4.style.alignItems = 'center';
h4.append(h1);
let valueRGB = rgb();
h1.innerText = valueRGB.toUpperCase();
h1.style.alignItems = 'center';
first_div.style.backgroundColor = rgb();
function rgb() {
let r = Math.floor(Math.random() * 255 + 0);
let g = Math.floor(Math.random() * 255 + 0);
let b = Math.floor(Math.random() * 255 + 0);
return (`rgb(${r}, ${g}, ${b})`);
}
function threeRandomNumber() {
let threeRandomNumber = Math.floor(Math.random() * 3 + 1);
return threeRandomNumber;
}
function divCreate() {
createDiv = document.createElement('div');
createDiv.classList = 'dynamacily_create_div';
createDiv.style.backgroundColor = `${rgb()}`;
return createDiv;
}
function randomDiv() {
let color_fix = threeRandomNumber();
console.log('outter Background ' + color_fix);
for (let i = 0; i < 3; i++) {
let div_fix = threeRandomNumber();
if (div_fix === 1) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 1) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
} else if (div_fix === 2) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 2) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
} else {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 3) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
}
}
}
randomDiv()
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
display: flex;
justify-content: center;
}
h4,
h5 {
color: #ffffff;
font-size: 40px;
}
#first_div {
width: 900px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
flex-direction: column;
}
#color_div {
height: 400px;
width: 100%;
background-color: black;
display: flex;
flex-direction: row;
justify-content: center;
}
.dynamacily_create_div {
width: 200px;
height: 200px;
border-radius: 25px;
margin: 10px;
border: 1px solid red;
}
<body>
<main>
<div id="first_div">
<h4>THE GREAT</h4>
<h5>GUESSING GAME</h5>
</div>
<div id="second_div">
<button id="newColor">New Color</button>
<button id="playAgain">Play Again</button>
<button id="tryAgain">Try Again</button>
<button id="correct">Correct</button>
<button id="easy">Easy</button>
</div>
<div id="color_div">
</div>
</main>
<script src="app.js"></script>
</body>
Some logical branches are ignored by you.
Both div_fix and color_fix are returned by threeRandomNumber().
div_fix can be any one of [1,2,3].
color_fix can be any one of [1,2,3]. They can be the same or not.
While div_fix===1 and color_fix===2 , code is missing.
While div_fix===1 and color_fix===3 , code is missing.
Please check and fix your problem.
if (div_fix === 1) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 1) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}else{
// Here!! maybe color_fix === 2 or color_fix === 3, Do sth.
}
}

Programatically resize the H div and C div along with the resizer

When I click-drag (#cssNav) to the right, it is not moving proportionately along with the #html and #css div.
This might be something very obvious, but still am not able to figure it out, what am I missing here, please help?
Note: I don't want to use display:flex
codepen
$("#htmlNav").on("mousedown", dragStartH);
$("#cssNav").on("mousedown", dragStartH);
$("#jsNav").on("mousedown", dragStartH);
function dragStartH(e) {
e.preventDefault();
dragMeta = {};
dragMeta.pageX0 = e.pageX;
dragMeta.elem = this;
dragMeta.offset0 = $(this).offset();
dragMeta.codeWindow = "#" + $(e.target).attr("id").replace("Nav", "");
function handle_dragging(e) {
var change = e.pageX - dragMeta.pageX0;
var left = dragMeta.offset0.left + change;
$(dragMeta.elem).offset({ left: left });
$("#css").width($("#css").width() - change + "px");
$("#html").width($("#html").width() + change + "px");
}
function handle_mouseup(e) {
$("body")
.off("mousemove", handle_dragging)
.off("mouseup", handle_mouseup);
}
$("body").on("mouseup", handle_mouseup).on("mousemove", handle_dragging);
}
$(document).ready(function() {
var widthPercent = ($(window).width() - 30) / 3;
$("#html").width(widthPercent + "px");
$("#css").width(widthPercent + "px");
$("#js").width(widthPercent + "px");
});
html, body {
height: 100%;
margin: 0;
}
.container{
width:100%;
height: 100%;
background-color:#343;
display: flex;
flex-direction: column;
color: #fff;
margin: 0;
}
#preview, #code{
background-color:#433;
height: 50%;
width: 100%;
margin: 0;
}
#code{
border-bottom: #333 solid 2px;
width: 100%
}
#previewNav, #codeNav{
background-color:#bbb;
height: 10px;
width: 100%;
cursor: row-resize;
}
#html{
background-color: #BFB;
}
#css{
background-color: #FBB;
}
#js{
background-color: #BBF;
}
#html, #css, #js{
float: left;
width: 32%;
height: 100%;
}
#htmlNav, #cssNav, #jsNav{
background-color:#bbb;
float: left;
height:100%;
width: 10px;
cursor: col-resize;
z-index:10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="codeNav"></div>
<div id="code">
<div id="htmlNav"></div>
<div id="html">H</div>
<div id="cssNav"></div>
<div id="css">C</div>
<div id="jsNav"></div>
<div id="js">J</div>
</div>
<div id="previewNav"></div>
<div id="preview">P</div>
</div>
This is how I would do it:
Keep track of which handle you press with navTypeand check if the user is holding its mouse down with dragging.
Then when the user moves the mouse in the document and it is holding its mouse down (dragging) it will move the #html, #css and #js accordingly
Change your javascript into this:
var mouseX, prevMouseX, navType, change;
var dragging = false;
$("#cssNav").mousedown(function () {
dragging = true;
navType = "css";
});
$("#jsNav").mousedown(function () {
dragging = true;
navType = "js";
});
$(document).mousemove(function (e) {
mouseX = e.pageX;
if(dragging){
e.preventDefault();
change = mouseX - prevMouseX;
if(navType == "css" && ($("#css").width() - (change)) > 0 && ($("#html").width() + (change)) > 0){
var hw = $("#html").width();
var cw = $("#css").width();
$("#html").width(hw + change);
$("#css").width(cw - change);
} else if(navType == "js" && ($("#css").width() + (change)) > 0 && ($("#js").width() - (change)) > 0){
var cw = $("#css").width();
var jw = $("#js").width();
$("#css").width(cw + change);
$("#js").width(jw - change);
}
}
prevMouseX = mouseX;
}).mouseup(function () {
dragging = false;
}).mouseleave(function () {
dragging = false;
});

TypeError: Cannot read property 'innerHTML' of null

I am trying to retain the best time value under the id "bestTime", but I keep on getting the following error in Chrome: Cannot read property 'innerHTML' of null at showBestTime.
Not sure what I am doing wrong, I have attached the code below. I am trying to process the best time in the function showBestTime. Thanks in advance!
<html>
<head>
<title>Reaction tester</title>
</head>
<style type="text/css">
#page-container{
width: 1000px;
margin: 0 auto;
height: 800px;
}
body{
margin: 0;
padding: 0;
font-family: Helvetica, Arial, freesans, sans-serif;
}
#shape{
width: 200px;
height: 200px;
background-color: red;
display: none;
position: relative;
}
.time{
font-weight: bold;
}
</style>
<body>
<div id="page-container">
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p class="time">Your time: <span id="timeTaken"></span></p>
<p class="time">Best time: <span id="bestTime">10</span>s</p>
<div id="shape"></div>
</div>
<script type="text/javascript">
var start=new Date().getTime();
function getRandomColor() {
var letters= "0123456789ABCDEF";
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()*800;
var width=(Math.random()*400)+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.top=top+"px";
document.getElementById("shape").style.left=left+"px"; document.getElementById("shape").style.width=width+"px"; document.getElementById("shape").style.height=width+"px";
document.getElementById("shape").style.display="block";
start=new Date().getTime();
}
function appearAfterDelay(){
setTimeout(makeShapeAppear, (Math.random() * 2000));
}
function showBestTime(y){ if(y<document.getElementById("besttime").innerHTML){
document.getElementById("besttime").innerHTML=y;
}
}
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();
showBestTime(timeTaken);
}
</script>
</body>
</html>
You have made a spelling mistake in your selector. You have provided besttime as your selector instead of bestTime. I have added the working code along with.
<html>
<head>
<title>Reaction tester</title>
</head>
<style type="text/css">
#page-container {
width: 1000px;
margin: 0 auto;
height: 800px;
}
body {
margin: 0;
padding: 0;
font-family: Helvetica, Arial, freesans, sans-serif;
}
#shape {
width: 200px;
height: 200px;
background-color: red;
display: none;
position: relative;
}
.time {
font-weight: bold;
}
</style>
<body>
<div id="page-container">
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p class="time">Your time: <span id="timeTaken"></span></p>
<p class="time">Best time: <span id="bestTime">10</span>s</p>
<div id="shape"></div>
</div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = "0123456789ABCDEF";
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() * 800;
var width = (Math.random() * 400) + 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.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = width + "px";
document.getElementById("shape").style.height = width + "px";
document.getElementById("shape").style.display = "block";
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, (Math.random() * 2000));
}
function showBestTime(y) {
if (y < document.getElementById("bestTime").innerHTML) {
document.getElementById("bestTime").innerHTML = y;
}
}
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();
showBestTime(timeTaken);
}
</script>
</body>
</html>
You have span:
<span id="bestTime">
and you query it with
document.getElementById("besttime")
and bestTime is not equal to besttime, so change to:
document.getElementById("bestTime")

Javascript Animation trouble

My code is for a website where when you press the movement button the two squares will move and if you press the change colour button both squares will alternate colours. The shapes do these actions at the same time. However, only one square does this while the other does nothing... please help?
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: CadetBlue;
}
div#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: Maroon;
}
</style>
<style>
#containertwo {
width: 400px;
height: 400px;
position: relative;
background: CadetBlue;
}
div#animatetwo {
width: 50px;
height: 50px;
position: absolute;
left: 350px;
top: 0px;
background-color: Olive;
}
</style>
<body>
<p>
<button onClick="myMove()">Movement</button>
</p>
<p>
<button onClick="button_click()">Change Colour</button>
</p>
<div id ="container">
<div id ="animate"></div>
<div id ="animatetwo"></div>
</div>
<div id="box" onClick="button_click();"></div>
<script>
var colors = ["Maroon","Olive"];
function button_click() {
var box = document.getElementById("animate");
var background_color = box.style.backgroundColor;
var i = colors.indexOf(background_color);
if (i === colors.length-1) {
i = -1;
}
animate.style.backgroundColor = colors[i+1];
}
</script>
<div id="box" onClick="myMove();"></div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
<div id="box" onClick="button_click();"></div>
<script>
var colorstwo = ["Maroon","Olive"];
function button_clicktwo() {
var box = document.getElementById("animatetwo");
var background_color = box.style.backgroundColor;
var i = colorstwo.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatetwo.style.backgroundColor = colorstwo[i+1];
}
</script>
<div id="box" onClick="myMove();"></div>
<script>
function myMovetwo() {
var elem = document.getElementById("animatetwo");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
Ok... I'll talk about the problem you're having first, then I'll try to give you some advice.
1) First of all upon clicking the "Movement" button you're only calling the myMove() function which is only responsible for moving the animated div, as you select it with:
var elem = document.getElementById("animate");
So if you desire to move both at the same time make sure you're activating the right functions, since I imagine you wanted to call myMovetwo() at the same time perhaps you could do:
function move() {
myMove();
myMovetwo();
}
That way you would call move() and both calls will run.
2) Now about your code, you should really consider isolating the different aspects of your page, and by that I mean isolating CSS, HTML and JavaScript, you can do that using the <link> tag to import your styles and the <script src="path"></script> tag to include your javascript code.
The other advice would be to remove onclick from your html tags and get the click event from your javascript code.
There are some great sources to learn this basics concepts, perhaps codecademy is a great one for starters https://www.codecademy.com/courses/html-javascript-css/0/1
Cheers!

How do I pass arguments to a 'setTimeout' function?

How can I make these functions use variables for the id? I can't get the setTimeout to work when I do.
<script type="text/javascript">
function changeBarAWidth() {
var bar = document.getElementById('firstbar');
bar.style.width = lengthA + "px";
}
function increaseBarA() {
if (lengthA < fullBarA) {
changeBarAWidth();
lengthA = (lengthA + 2);
setTimeout("increaseBarA()", 10); // <-- How do I pass "firstbar"?
}
}
function resetLengthA() {
lengthA = 0;
changeBarAWidth();
}
var barA = 'firstbar';
var percentA = 80;
var fullBarA = (percentA * 2);
var lengthA = 0;
</script>
<style type="text/css">
ul {
list-style-type: none;
}
.bar {
width: 50px;
height: 5px;
background-color: red;
}
.back {
background-color: black;
height: 5px;
width: 200px;
}
</style>
</head>
<body onload="increaseBarA()">
<ul>
<li class="back">
<p class="bar" id="firstbar"></p>
</li>
</ul>
<button onClick="increaseBarA()">Test Change</button>
<button onClick="resetLengthA()">Reset</button>
I had to use a setTimeout(function() { YourFuncwith(params); }, 10);.
Here is the script. If anybody would like copy, please do:
// functions to show poll reults, div width increase every tenth of a second,
// looks like poll is sliding.
// length is name of global length variable you declare, mine are at bottom of script
// I will use php to dynaimcally give variable values based on poll results.
function changeBarWidth(id, length) {
var bar = document.getElementById(id);
bar.style.width = length + "px";
}
/* max is how long you want the poll to slide to, my background is 200px
* so I set to (percent*2);
*/
function increaseBar(id, max, length) {
var full = max;
if (length < full) {
changeBarWidth(id, length);
length = (length + 2);
setTimeout(function() {
increaseBar(id, max, length);
}, 10);
}
}
var barA = 'firstbar';
var percentA = 80;
var fullBarA = (percentA * 2);
var lengthA = 0;
var lengthB = 0;
ul {
list-style-type: none;
}
.bar {
width: 50px;
height: 5px;
background-color: red;
}
.back {
background-color: black;
height: 5px;
width: 200px;
}
<body onload="increaseBar(barA, percentA, lengthA)">
<div id="pollresults">
<ul>
<li class="back">
<p class="bar" id="firstbar"></p>
</li>
<li class="back">
<p class="bar" id="secondbar"></p>
</li>
</ul>
</div>
<button onClick="increaseBar('secondbar',fullBarA,lengthB)">Test Change</button>
</body>

Categories