Trying to make a light bulb using HTML & CSS & JS - javascript

<!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>3 Circle</title>
<style>
body {background: black;}
.container {display: flex;}
.circle {
width: 500px;
height: 500px;
-webkit-border-radius: 250px;
-moz-border-radius: 250px;
border-radius: 250px;
background: white;
}
.active {
background: yellow !important;
color: red;
}
</style>
</head>
<body>
<section class="container">
<button class="circle circle1">Circle1</button>
<button class="circle circle2">Circle2</button>
<button class="circle circle3">Circle3</button>
</section>
<script>
let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')
let allCircle = document.querySelectorAll('.circle');
cir1.addEventListener('onClick', onButton1Click);
cir2.addEventListener('onClick', onButton2Click);
cir3.addEventListener('onClick', onButton3Click);
function onButton1Click() {
if (cir1.classList.contains("active")) {
allCircle.classList.remove('active');
} else {
allCircle.classList.remove('active');
cir1.classList.add('active');
}
}
function onButton2Click() {
if (cir2.classList.contains("active")) {
allCircle.classList.remove('active');
} else {
allCircle.classList.remove('active');
cir2.classList.add('active');
}
}
function onButton3Click() {
if (cir3.classList.contains("active")) {
allCircle.classList.remove('active');
} else {
allCircle.classList.remove('active');
cir3.classList.add('active');
}
}
</script>
</body>
</html>
I am trying to make 3 light bulbs represented by circles using HTML & CSS.
So if I turn one light bulb on using the button, the other ones should turn off using the addeventlistener. I can't find ways to make the light bulb turn yellow. Is there anything I am doing wrong? I looked for typos but I can't find any.

A few small things need to changed here.
The event type to be passed to the addEventListener is 'click' rather than 'onClick'.
The variable allCircle returns a list of dom nodes and not a single dom node. So it is essentially a []. Hence properties and methods that are available on a dom node are not accessible on the variable. What you can rather do is write a loop to access each element of the array and then modify their classes one by one
Might also suggest you to put debugger inside your code to see what is happening line by line. This article by Google should help you on using the Chrome dev tools.
This is my first answer on Stack Overflow.
let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')
cir1.addEventListener('click', onButton1Click);
cir2.addEventListener('click', onButton2Click);
cir3.addEventListener('click', onButton3Click);
function removeActive() {
cir1.classList.remove('active');
cir2.classList.remove('active');
cir3.classList.remove('active');
}
function onButton1Click() {
removeActive();
cir1.classList.add('active');
}
function onButton2Click() {
removeActive();
cir2.classList.add('active');
}
function onButton3Click() {
removeActive();
cir3.classList.add('active');
}
body {
background: black;
}
.container {
display: flex;
align-items: flex-start;
}
.circle {
width: 100px;
height: 100px;
max-height: 100px;
-webkit-border-radius: 250px;
-moz-border-radius: 250px;
border-radius: 250px;
background: white;
}
.active {
background: yellow !important;
color: red;
}
<!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>3 Circle</title>
</head>
<body>
<section class="container">
<button class="circle circle1">Circle1</button>
<button class="circle circle2">Circle2</button>
<button class="circle circle3">Circle3</button>
</section>
</body>
</html>

There seem to be two issues here.
When adding an event listener for a click event, it must be called with click that is to be passed as the first parameter to the listener, but you've added onClick
querySelectorAll returns a HTMLCollection. So classList will not be a valid property on it. You might want to loop through the elements from allCircles to remove the class.
I've modified the listener and corrected the classist related fix for the first button here https://jsfiddle.net/gr33nw1zard/y7f5wnda/

should be click event, not 'onClick'.
cir1.addEventListener('click', onButton1Click);

Created one common function for all 3 buttons. onClick event is not available in plain javascript, it's the click that is the correct keyword here. Also, you have to iterate over allCircle's object or use getElementsByClass. This will work for you!
<!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>3 Circle</title>
<style>
body {
background: black;
}
.container {
display: flex;
}
.circle {
width: 500px;
height: 500px;
-webkit-border-radius: 250px;
-moz-border-radius: 250px;
border-radius: 250px;
background: white;
}
.active {
background: yellow !important;
color: red;
}
</style>
</head>
<body>
<section class="container">
<button class="circle circle1">Circle1</button>
<button class="circle circle2">Circle2</button>
<button class="circle circle3">Circle3</button>
</section>
<script>
let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')
let allCircle = document.querySelectorAll('.circle');
cir1.addEventListener('click', onButtonClick);
cir2.addEventListener('click', onButtonClick);
cir3.addEventListener('click', onButtonClick);
function onButtonClick(e) {
const cir = e.toElement;
if (cir.classList.contains("active")) {
Object.keys(allCircle).map(circle => allCircle[circle].classList.remove('active'));
} else {
Object.keys(allCircle).map(circle => allCircle[circle].classList.remove('active'));
cir.classList.add('active');
}
}
</script>
</body>
</html>

The onClick should be edited to click

Related

How do I program a javascript function to switch button colors back and forth?

I'm trying to turn a blue button red by using an onclick, but then I also want the button to turn back to being blue after clicking again using the same onclick function.
How would I do this?
<!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>
<style>
.round {
border-radius: 5px;
color: aliceblue;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
</style>
</head>
<body>
<button id="btn" class="round blue" onclick="clickBtn()">button</button>
<script>
function clickBtn() {
let btn = document.getElementById('btn')
if(btn.classList.contains('blue')) {
btn.classList.remove('blue')
btn.classList.add('red')
} else {
btn.classList.remove('red')
btn.classList.add('blue')
}
}
</script>
</body>
</html>
You can give the button a default background color, then add a click event listener to it which toggles a class that applies a different background color:
document.querySelector('button').addEventListener('click', function(){ this.classList.toggle("red") })
button{
background-color:green;
}
.red{
background-color:red;
}
<button>Hello World!</button>

Why doesn't jQuery function toggleClass() work?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../jquery/jquery.js"></script>
<style type="text/css" rel="stylesheet">
#btn {
background: green;
color: #fff;
padding: 15px;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<script>
$(() => {
$("#btn").click(() => {
if ($("#btn").hasClass("green")) {
$("#btn").css("backgroundColor", "red");
}
else if ($("#btn").hasClass("red")) {
$("#btn").css("backgroundColor", "green");
}
});
});
</script>
<button id="btn">Button</button>
</body>
</html>
I want the button to change its color either to red if it's green or to green if it's red. So I use toggleClass() to implement that.
Question: why doesn't it work?
It is almost certainly working but there are no CSS rules for the class "background" in the code you posted. The function is for adding/removing an entry from the class list of an element, not for directly manipulating style object properties.
If you do switch from .toggleClass() to .css(), you'll find that switching a property from one value to another immediately will have no visible effect. The browser will effectively ignore the first update.
Your are change class name using toggle not the rule within the class. But you can iverride it by adding inline style, like:
$("#btn").css("background", "red");
$(() => {
$("#btn").click(function () {
const bgColor = this.style.backgroundColor;
$(this).css("backgroundColor", bgColor === 'green' ? "red" : "green");
});
});
#btn {
color: #fff;
padding: 15px;
font-size: 24px;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" style="background-color:green;">Button</button>
It is perfectly correct to use the .toggleClass() method...
But the argument is a string of space separated classnames.
And, of course, you have to define those class rules in your style sheet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--script src="../jquery/jquery.js"></script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css" rel="stylesheet">
#btn {
/*background: green;*/
color: #fff;
padding: 15px;
font-size: 24px;
font-weight: bold;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<script>
$(() => {
$("#btn").click(() => {
$("#btn").toggleClass("red green");
});
});
</script>
<button id="btn" class="green">Button</button>
</body>
</html>

jquery draggable, making a div not to go outside of the other div frame

i need a draggable div not to go outside of second div frame, so far i managed to make a "collision" basically returning true or false if draggable div is inside the frame of other div. So the thing now is that i cant get this to work, i was trying to get it to a x = 90(example) when it hits the frame and few more examples , but i just can't get this to work. The draggable div doesn't want to go back to position.
Here is a JSFiddle: https://jsfiddle.net/kojaa/x80wL1mj/2/
<!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="style.css">
<title>Catch a ball</title>
</head>
<body>
<div class="catcherMovableArea" id="catcherMovableArea">
<div id="catcher" class="catcher"></div>
</div>
<script src="script.js"></script>
</body>
</html>
.catcherMovableArea {
position: absolute;
border: 1px solid black;
width: 1900px;
top: 90%;
height: 50px;
}
.catcher {
position: absolute;
width: 250px;
height: 30px;
border-radius: 10px;
background-color: black;
top: 20%;
}
let catcher = $("#catcher");
$(document).mousemove(function(e) {
catcher.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit"
});
let catcherOffset = $(catcher).offset();
let CxPos = catcherOffset.left;
let CyPos = catcherOffset.top;
let catcherYInMovableArea, catcherXInMovableArea = true;
while(!isCatcherYinMovableArea(CyPos)){
catcherYInMovableArea = false;
break;
}
while(!isCatcherXinMovableArea(CxPos)){
catcherXInMovableArea = false;
break;
}
});
function isCatcherYinMovableArea(ypos){
if(ypos < 849.5999755859375 || ypos > 870.5999755859375) {
return false;
} else {
return true;
}
}
function isCatcherXinMovableArea(xpos){
if(xpos < 8 || xpos > 1655 ) {
return false;
} else {
return true;
}
}
By default, the collision option will prevent the element from being placed outside of the window. You want to prevent it from moving outside of a specific element.
To do this, use the within option to select which element should be used for containment.
Example:
let draggable = $("#draggable");
$(document).mousemove(function(e) {
draggable.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit",
within: "#container"
});
});
#container { width: 200px; height: 100px; border-style: solid }
#draggable { width: 50px; height: 50px; background-color: black }
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-rc.1/jquery-ui.js"></script>
<div id="container">
<div id="draggable"></div>
</div>

Capturing return key in contenteditable div

I'm building a programmable calculator that uses a contenteditable div as a place to enter the expression you need evaluated. The div listens for the user to strike the return key, then passes its text content to the calculator engine, clears itself, and then displays the result of the expression.
Everything works as expected on desktop browsers, but under mobile browsers, there is some strange behaviour when the return key is pressed when the caret is not at the end of the text. Sometimes hitting the return key will insert a space or newline, sometimes it will submit and clear everything before the caret, and under Chrome it seems to create a new div element. Any ideas what I'm doing wrong?
I have successfully tested the code in Firefox 59.0.2 and Chromium 65.0.3325.181 running on Ubuntu 17.10, and Firefox 59.0.2 running on Windows 7. I have unsuccessfully tested the code in Firefox 59.0.2 and Chrome 65.0.3325.109 running on Android 8.1.0.
window.addEventListener("load", function () {
"use strict";
var i = document.getElementById("i");
var o = document.getElementById("o");
i.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
e.preventDefault();
o.textContent = i.textContent;
i.textContent = "";
return false;
}
return true;
});
});
div {
font-size: 24px;
padding: 1em;
border: 1px solid black;
min-height: 1em;
box-sizing: content-box;
margin: 1em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=0">
<title>Test</title>
</head>
<body>
<div id="i" contenteditable="true"></div>
<div id="o"></div>
</body>
</html>
EDIT:
After some work, I've made an alternate method of detecting input, copying the text, and clearing the box. It no longer listens for keystrokes but watches for changes in the box itself. It works on desktop but fails in similar ways on mobile. It also has the added problem that it will crash Firefox mobile if you type too quickly. I've tested the code on the same browsers as before.
window.addEventListener("load", function () {
"use strict";
var i = document.getElementById("i");
var o = document.getElementById("o");
var getText;
var input;
getText = function (e) {
var s = [];
e.childNodes.forEach(function (n) { // get every child
switch (n.nodeType) {
case 1: // element, so recurse
s.push(getText(n));
break;
case 3: // text
s.push(n.nodeValue);
break;
}
});
return s.join("");
};
input = function (e) {
if (i.childNodes.length > 1 || (i.firstChild && i.firstChild.nodeType != 3)) { // checking for added <br />
e.preventDefault();
o.textContent = getText(i);
while (i.firstChild) { // clear element
i.removeChild(i.firstChild);
}
// add and remove listener to prevent event from firing on clear
i.removeEventListener("input", input);
setTimeout(function () {
i.addEventListener("input", input, true);
}, 100);
return false;
}
return true;
};
i.addEventListener("input", input, true);
});
div {
font-size: 24px;
padding: 1em;
border: 1px solid black;
min-height: 1em;
box-sizing: content-box;
margin: 1em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=0">
<title>Test</title>
</head>
<body>
<div id="i" contenteditable="true"></div>
<div id="o"></div>
</body>
</html>
EDIT 2 (with workaround):
After some thinking, I realized I don't need to use a contenteditable div, so I've re-worked it to use a styled text input field which works properly.
window.addEventListener("load", function () {
"use strict";
var f = document.getElementById("f");
var i = document.getElementById("i");
var o = document.getElementById("o");
f.addEventListener("submit", function (e) {
e.preventDefault();
o.textContent = i.value;
i.value = "";
return false;
});
});
input[type="text"] {
display: block;
width: 100%;
overflow: auto;
outline: none;
border: none;
border-radius: 0;
box-shadow: none;
box-sizing: content-box;
}
#i, div {
width: calc(100% - 4em - 2px);
min-height: 1em;
font-size: 24px;
padding: 1em;
border: 1px solid black;
min-height: 1em;
margin: 1em;
color: black;
font-family: serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=0">
<title>Test</title>
</head>
<body>
<form id="f" name="f">
<input id="i" name="i" type="text" >
</form>
<div id="o"></div>
</body>
</html>

material refresh click event not working

i use this plugin material-refresh to refresh page it's working fine but when the page is scrolled at the top "TOP = 0" click wont fire and when i scroll it down by 1px it's work normally here an image enplane the problem better
Here the test code
var opts_stream = {
nav: '.page_header',
scrollEl: '.page_content',
onBegin: function() {
console.log("start");
},
onEnd: function() {
console.log("Done");
}
};
mRefresh(opts_stream);
.page_header {
width: 100%;
height: 100px;
background-color: red;
text-align: center;
}
.page_content {
width: 100%;
height: 1200px;
background-color: rgb(190, 190, 190);
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>sdasd</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link href="https://github.com/lightningtgc/material-refresh/blob/master/src/css/material-refresh.styl">
<script src="https://raw.githubusercontent.com/lightningtgc/material-refresh/master/src/js/main.js"></script>
</head>
<body>
<div class="page_header">
Header
</div>
<div class="page_content">
<button type="button" name="button" onclick="alert('test');">Test Button</button>
</div>
</body>
</html>
NOTE : You need to run browser in mobile mood from chrome console to get this plugin to run
in line 304 in touchEnd function in material-refresh.js remove e.preventDefault();
:)

Categories