How to monitor what the user clicks - javascript

I am currently having trouble figuring out how am i supposed to monitor every click of the user.
My little game does this :
You have 5 buttons, 1 start button and 4 buttons that will be highlighted in a random order.
After that i want the user to click the buttons in the order that they have been highlighted (in 10 seconds time, i haven't implemented the 10 seconds time yet).
I don't know how to restrict the user to only be able to press buttons only in the given time and to see what buttons he presses just with JavaScript and Jquery (if you can't restrict at least to see what buttons he presses ).
I will then retain the order in which he pressed the buttons in the array "input" .
Here is my code :
HTML :
<!DOCTYPE html>
<html lang="ro">
<head>
<link href="my.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="jquery-1.11.0.js"></script>
<script src="Joculet.js" type="text/javascript"> </script>
<meta charset="utf-8">
<title> Joculet </title>
</head>
<body>
<div id ='tot'>
<button type='button' class='cls1' id='id1'></button>
<button type='button' class='cls2' id='id2'></button>
<button type='button' class='cls3' id='id3'></button>
<button type='button' class='cls4' id='id4'></button>
<button type='button' id='start'>Click Me!</button>
</div>
</body>
</html>
CSS:
.tot{
position: absolute;
width: 100%;
height: 100%;
}
.cls1{
position: absolute;
background-color: red;
width: 12%;
height: 12%;
border: 2px solid black;
}
.cls2{
position: absolute;
background-color: yellow;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
}
.cls3{
position: absolute;
background-color: #00FF00;
width: 12%;
height: 12%;
border: 2px solid black;
margin-top: 12%;
}
.cls4{
position: absolute;
background-color: #3090C7;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
margin-top: 12%;
}
#start{
position: absolute;
margin-left: 12%;
margin-top: 23%;
}
.cls12{
position: absolute;
background-color: #C24641;
width: 12%;
height: 12%;
border: 2px solid black;
}
.cls22{
position: absolute;
background-color: #FFFFCC;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
}
.cls32{
position: absolute;
background-color: #6AFB92;
width: 12%;
height: 12%;
border: 2px solid black;
margin-top: 12%;
}
.cls42{
position: absolute;
background-color: #893BFF;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
margin-top: 12%;
}
and the most important JS :
var k = 1;
var g = 1;
var nrmax = 8;
ordine = new Array();
var j = 0;
input = new Array();
$(document).ready(function () {
$('#start').click(function () {
game();
})
function game() {
if(k <= nrmax){
if(g <= k){
var x = Math.floor((Math.random() * 4) + 1);
ordine[j++] = x;
change1(x);
}
else {
alert('Felicitari ai castigat runda');
g = 1;
k++;
j = 0;
ordine = new Array();
setTimeout(function(){game();},2000);
}
}
else alert('Felicitari ai castigat jocul');
}
function change1(y) {
var z = 'cls' + y;
var t = 'cls' + y + 2;
$("." + z).removeClass(z).addClass(t);
setTimeout(function() { change2(y); }, 500);
}
function change2(y) {
var z = 'cls' + y + 2;
var t = 'cls' + y;
$("." + z).removeClass(z).addClass(t);
g++;
setTimeout(function(){game();},500);
}
});
any help is apreciated, you can also find the code here for a better view http://jsfiddle.net/6qDap/1181/

I think I understood your questions correctly. I did not include the timer but here is how you could maintain the order of clicked buttons in the input array.
http://jsfiddle.net/6qDap/1184/
$('button').click(function(){
input.push( $(this).attr('id') );
console.log(input);
});
Don't forget to check the console to view the output. Hope this helps! Let me know if you have any questions or if I misunderstood.

If I understand you right - you want to time a user clicking 4 buttons within 10 sec. I would start a javascript timer when the user clicks start.
setTimeout(disablebuttonsaftertimeout, 10000);
Then disable the buttons after the timer expires.

"I don't know how to restrict the user to only be able to press buttons only in the given time and to see what buttons he presses" - are asking two things here
I don't know how to restrict the user to only be able to press buttons only in the given time - if time is over, disable/hide buttons
see what buttons he presses - every time he presses a button store the id of a button in the array
also to restrict the user from pressing any other buttons, add a class "wrong" to buttons that he can't press and on click check if $(this).hasClass('wrong') return 0;

Related

How to submit an list when one of the list item is selected

hello i am creating a search bar that has auto complete feature can someone tell how to auto submit when one of the option is selected
some other possible solutions are autosubmit when the input field contains $
{i will add a $ swmbol in each of the array}
you can check the whole program on codepen by clicking here
https://codepen.io/simplyrajatgupta/pen/wvmXPJv
here is the codes
let suggestions = [
"Channel",
"CodingLab",
"CodingNepal",
"YouTube",
"YouTuber",
"YouTube Channel",
"Blogger",
"Bollywood",
"Vlogger",
"Vechiles",
"Facebook",
"Freelancer",
"Facebook Page",
"Designer",
"Developer",
"Web Designer",
"Web Developer",
"Login Form in HTML & CSS",
"How to learn HTML & CSS",
"How to learn JavaScript",
"How to become Freelancer",
"How to become Web Designer",
"How to start Gaming Channel",
"How to start YouTube Channel",
"What does HTML stands for?",
"What does CSS stands for?",
];
// getting all required elements
const searchWrapper = document.querySelector(".search-input");
const inputBox = searchWrapper.querySelector("input");
const suggBox = searchWrapper.querySelector(".autocom-box");
const icon = searchWrapper.querySelector(".icon");
let linkTag = searchWrapper.querySelector("a");
let webLink;
// if user press any key and release
inputBox.onkeyup = (e)=>{
let userData = e.target.value; //user enetered data
let emptyArray = [];
if(userData){
icon.onclick = ()=>{
webLink = `https://www.google.com/search?q=${userData}`;
linkTag.setAttribute("href", webLink);
linkTag.click();
}
emptyArray = suggestions.filter((data)=>{
//filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
});
emptyArray = emptyArray.map((data)=>{
// passing return data inside li tag
return data = `<li>${data}</li>`;
});
searchWrapper.classList.add("active"); //show autocomplete box
showSuggestions(emptyArray);
let allList = suggBox.querySelectorAll("li");
for (let i = 0; i < allList.length; i++) {
//adding onclick attribute in all li tag
allList[i].setAttribute("onclick", "select(this)");
}
}else{
searchWrapper.classList.remove("active"); //hide autocomplete box
}
}
function select(element){
let selectData = element.textContent;
inputBox.value = selectData;
icon.onclick = ()=>{
webLink = `https://www.google.com/search?q=${selectData}`;
linkTag.setAttribute("href", webLink);
linkTag.click();
}
searchWrapper.classList.remove("active");
}
function showSuggestions(list){
let listData;
if(!list.length){
userValue = inputBox.value;
listData = `<li>${userValue}</li>`;
}else{
listData = list.join('');
}
suggBox.innerHTML = listData;
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
background: #644bff;
padding: 0 20px;
}
::selection{
color: #fff;
background: #664AFF;
}
.wrapper{
max-width: 450px;
margin: 150px auto;
}
.wrapper .search-input{
background: #fff;
width: 100%;
border-radius: 5px;
position: relative;
box-shadow: 0px 1px 5px 3px rgba(0,0,0,0.12);
}
.search-input input{
height: 55px;
width: 100%;
outline: none;
border: none;
border-radius: 5px;
padding: 0 60px 0 20px;
font-size: 18px;
box-shadow: 0px 1px 5px rgba(0,0,0,0.1);
}
.search-input.active input{
border-radius: 5px 5px 0 0;
}
.search-input .autocom-box{
padding: 0;
opacity: 0;
pointer-events: none;
max-height: 280px;
overflow-y: auto;
}
.search-input.active .autocom-box{
padding: 10px 8px;
opacity: 1;
pointer-events: auto;
}
.autocom-box li{
list-style: none;
padding: 8px 12px;
display: none;
width: 100%;
cursor: default;
border-radius: 3px;
}
.search-input.active .autocom-box li{
display: block;
}
.autocom-box li:hover{
background: #1bb361;
color: white;
}
.search-input .icon{
position: absolute;
right: 0px;
top: 0px;
height: 45px;
;
width: 45px;
text-align: center;
line-height: 45px;
font-size: 20px;
color: white;
cursor: pointer;
background: #1a74f2;
right: 5px;
top: 5px;
bottom: 5px;
border-radius: 5px;
}
.search-input
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Autocomplete Search Box | CodingNepal</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<form action="https://www.google.com/search?q=">
<div class="wrapper">
<div class="search-input">
<a href="" target="_blank" hidden></a>
<input type="text" id="ra"placeholder="Enter question or chapter...">
<div class="autocom-box">
<!-- here list are inserted from javascript -->
</div>
<div class="icon" id="ca"type="submit"><i class="fas fa-search"></i></div>
</div>
</div>
</form>
<script src="js/suggestions.js"></script>
<script src="js/script.js"></script>
<script>
var input = document.getElementById("ra");
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementsByClassName("ca").click();
}
});
</script>
</body>
</html>
Instead write code for clicking search button, you can just call window.open('http://url-goes-here.com').
inputBox.onkeydown = (e) => {
let firstSuggestion = suggestions.filter(el =>
el.toLowerCase().includes(e.target.value.toLowerCase()))[0];
if((e.keyCode == 13) && firstSuggestion)
e.preventDefault();
window.open(`https://www.google.com/search?q=${firstSuggestion}`)
}
}
This function make input that matched with first suggestion auto-submitted when enter key pressed. If you wanna use this function, make sure you delete another function that also record enter key in input.
.onkeydown make any key pressed in inputBox will be 'record'. If the key pressed is enter (enter keycode = 13) and first suggestion exist (not null), so you will be redirect to google url + first suggestion query.
firstSuggestion in here, defined as filtered suggestion list, which only include suggestion that contains character of your search query.

Creating health bar that increases in value based on users level

Hello I am trying to create a healthbar that scales in max value based on the users level.
But I am kinda stuck with it because everytime the healthbar ends up in not having the right length based on the users level and it's health. The system works like this: the user starts at level 1 with a health value of 150 and increases + 10 everytime the user levels up, the max level that exists is 32.
Now I know this might be possible to do with a loop but I am not sure on how do this correctly:
This is the code for the health bar. The user_level is the users level and I am trying to change the element style based on his health, but at the same time that it would match with the current level of the user.
for (let i = 0; i < user_level.value; i++) {
playerhealthbar.style.width = user_health // Something here but I dont know how to.
}
This is the CSS code if it helps. What happens is that the greenbar should shrink so that the red bar underneath becomes visible.
#playerhealth {
position: absolute;
bottom: 0;
left: 0;
height: 45px;
width: 325px;
background: lightgreen;
}
#playerhealthbar {
position: absolute;
height: 50px;
width: 330px;
border: rgb(255, 255, 255) 3px solid;
border-radius: 3px;
margin-right: 20px;
display: inline-block;
margin-top: 442px;
margin-left: 70px;
background: rgb(158, 31, 31);
}
#playerhealthvalue{
position: absolute;
margin-top: 500px;
margin-left: 220px;
font-size: 30px;
color: black;
}
The complete outerbar stays the same. But the greenbar thats inside the whole frame shrinks in size when the health goes down.
So the first thing you have to calculate is what the current maximum health value is. This is given by currentMaxHealth = 150 + 10 * (level-1).
The percent of the green bar is playerHealth / currentMaxHealth * 100.
The whole logic can be done with just custom properties calc and var.
So the CSS could look like this:
function setCurrentHealth(val) {
let root = document.documentElement;
root.style.setProperty('--curr-health', val);
}
function setUserLevel(level) {
let root = document.documentElement;
root.style.setProperty('--user-level', level);
}
document.querySelector('#level').addEventListener('input', (evt) => {
setUserLevel(evt.target.value)
})
document.querySelector('#health').addEventListener('input', (evt) => {
setCurrentHealth(evt.target.value)
})
:root {
--user-level: 1;
--curr-health: 10;
--base-health-level: 150;
--additional-health-per-level: 10;
}
.current-health {
width: calc(var(--curr-health) / (var(--base-health-level) + var(--additional-health-per-level) * (var(--user-level) - 1)) * 100%);
height: 100%;
background-color: green;
}
.health-bar {
border: 1px solid black;
width: 300px;
height: 20px;
}
<div class="health-bar">
<div class="current-health">
</div>
</div>
Level: <input value="1" id="level"><br>
Health: <input value="10" id="health">

How can a span id that div classes are applied to be looped?

I'm new to coding, and I'm trying to learn the basics. I wanted to practice what I learned by making flashcards (nothing complicated like saving it, importing it, or exporting it). So far, I made a table that the user can edit. I know how to gather data from the table, but I don't know how to make a CSS flashcard appear every time the user adds a card to the table. I am aware that the code will not work since I put the CSS in JavaScript since this code is just meant to show what I am trying to do. Also, if I am taking a completely wrong approach, please let me know. Thank you! Please excuse the poor variable naming, I was just testing some things.
<script>
function getFlashcardValue() {
for (var repeat = 0; repeat < 200; repeat++) {
var Table = document.getElementById('flashcardsTable');
var column1 = 0;
var column2 = 1;
var numberOfFlashcards = 2;
for (var row = 0; row < numberOfFlashcards; row++) {
var Cells = Table.rows.item(1).cells;
var Question1 = Cells.item(column1).innerHTML;
var Cells1 = Table.rows.item(1).cells;
var Answer1 = Cells.item(column2).innerHTML;
document.getElementById("myFlashcardQuestion" + row).innerHTML = Question1;
document.getElementById("myFlashcardAnswer" + row).innerHTML = Answer1;
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<span id="myFlashcardQuestion1"></span>
</div>
<div class="flip-card-back">
<span id="myFlashcardAnswer1"></span>
</div>
</div>
</div>
}
}
}
</script>
<p style = "font-size: 25px">Hover over the flashcard to flip it!</p>
<style>
.flip-card {
background-color: transparent;
width: 350px;
height: 175px;
margin: auto;
padding: 5px 5px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
background-color: lightblue;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front, .flip-card-back {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.flip-card-front {
background-color: lightblue;
width: 350px;
height: 175px;
color: black;
font-size: 35px;
text-alignment: center;
}
.flip-card-back {
background-color: red;
color: white;
font-size: 35px;
text-alignment: center;
transform: rotateY(180deg);
}
</style>
So first of all you can create a code snippet in stackoverflows editor (see below), or use jsfiddle and post a shared-link.
It depends on which action the user has to do after he enters the data.
If it is, for example, a button click, then it is possible to call a function that shows the user's input in the flashcard. Now if you want that for every single Q&A you have to create Elements in the for loop and edit them there. Here a little example.
var allCards = document.getElementById("allCards");
for (var i = 1; i <= 5; i++) { //i used 5, you should use length of data
var question = document.createElement("div");
question.textContent = "Question " + i;
question.classList.add("flip-card");
allCards.appendChild(question);
}
.flip-card {
background-color: lightblue;
width: 350px;
height: 175px;
margin: 10px auto;
padding: 5px 5px;
font-size: 35px;
text-align: center;
}
<div id="allCards"></div>
Edit:
As promised, here is an example of how you can set up the flip cards.
https://jsfiddle.net/ybu59hfp/1/
Your concern should now be resolved. If you have any further questions, feel free to write to me in the chat or read a little about JavaScript on the Internet.

Mouseover popup speech bubble

I'm new to javascript/css and would like to make a version of a mouseover popup similar to the one that displays over the underlined words here: http://st.japantimes.co.jp/essay/?p=ey20141219
I can see the code that is used, but I'm not sure where/how to add in my own speech bubble image when I edit the code for my own project.
Here is an example of the code used on the referenced page:
HTML:
<a style="cursor:pointer;" onclick="showChuPopup(event,'<b>’Twas</b><br />It was の省略');return false;" onmouseover="showChuPopup(event,'<b>’Twas</b><br />It was の省略');" onmouseout="endChuPopup();">’Twas</a>
Javascript:
function showChuPopup(e,text){
if(document.all)e = event;
var obj = document.getElementById('chu_popup');
var obj2 = document.getElementById('chu_popup_text');
obj2.innerHTML = text;
obj.style.display = 'block';
var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);/*
if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)st=0;*/
var leftPos = e.clientX - 100;
if(leftPos<0)leftPos = 0;
obj.style.left = leftPos + 'px';
obj.style.top = e.clientY - obj.offsetHeight -1 + st + 'px';} function endChuPopup() {
document.getElementById('chu_popup').style.display = 'none';} function touchHandler(e){
document.getElementById('chu_popup').style.display = 'none';}
Thanks for any help or ideas.
There are a few ways to go about this, but I'll recommend two options and provide links to both!
First, check out the answer on this question to see if this is what you want:
jQuery Popup Bubble/Tooltip
Second, have you thought about just using a tooltip with CSS? They're not hard to implement at all, and you can absolutely bind data to them.
(Shamelessly stolen from: https://www.w3schools.com/css/css_tooltip.asp, I would recommend poking around here and also looking into Bootstrap if you're a beginner!)
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
top: 150%;
left: 50%;
margin-left: -60px;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent black transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>

Javascript popup in html table

I have a 10 x 10 with data table that is created using html tags. If it is possible to create a onClick function to each cell? I mean, if I click on a cell, then it gives me its value in a n alert window? If yes, then how?
Plain JS - assuming <table id="table1">:
window.onload=function() {
var cells = document.getElementById('table1').getElementsByTagName('td');
for (var i=0, n=cells.length;i<n;i++) {
cells[i].onclick=function() { alert(this.innerHTML) }
}
}
A good example could be found here
HTML CODE:
<div id='page-wrap'>
Your content goes here.
<a id='show' href='#'>show overlay</a>
JavaScript & JQuery:
$(document).ready(function() {
$("#show").click(function() {
showPopup();
});
$("#popup").click(function() {
$(this).hide();
$("#mask").hide();
});
});
function showPopup() {
// show pop-up
$("#mask").fadeTo(500, 0.25);
// show the popup
$("#popup").show();
}
---------------------------------------
CSS CODE:
* { margin: 0, padding 0}
#mask{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
display: none;
z-index: 10000;
}
#popup
{
width: 200px;
height: 200px;
margin: 10px auto;
border: 1px solid #333;
background-color: #ffffdd;
cursor: pointer;
padding: 10px;
position: relative;
z-index: 10001;
display: none;
}
[![enter image description here][1]][1]

Categories

Resources