i copied this little javascript game from github i started editing i made some new levels and whole new graphic design for the game. basiclly i did it for fun made new keybinds for the keyboard since it's playable for keyboard only.
then i had this idea to create a button that acts like a keyboard or directly make the character move
i tried but it don't work
so here is my "controller.js" which is responsible for the character movements
with"htmlfile.html"
const Controller = function() {
this.left = new Controller.ButtonInput();
document.getElementById("clickMe").onclick = this.right = new Controller.ButtonInput();;
this.up = new Controller.ButtonInput();
this.keyDownUp = function(type, keycode) {
var down = (type == "keydown") ? true : false;
//old//
switch(keycode) {
case 37: this.left.getInput(down); break;
case 38: this.up.getInput(down); break;
case 39: this.right.getInput(down); break;
// case 81: this.left.getInput(down); break;
// case 90: this.up.getInput(down); break;
// case 68: this.right.getInput(down);
//new//
}
};
};
//new//
//1- document.getElementById("clickMe").onclick = doFunction;
//2-document.getElementById("demo").onclick =
this.keyDownUp = function(type, button) {
var down = (type == "keydown") ? true : false;
$("input[type='button']").click(function() {
switch(button) {
case '1': this.left.getInput(down); break; //notice BREAK
case '2': this.right.getInput(down); break;
case '3': this.up.getInput(down); break;
}
});
}
Controller.prototype = {
constructor : Controller
};
Controller.ButtonInput = function() {
this.active = this.down = false;
};
Controller.ButtonInput.prototype = {
constructor : Controller.ButtonInput,
getInput : function(down) {
if (this.down != down) this.active = down;
this.down = down;
}
};
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.min.js"></script>
<!-- Added this meta tag 04/07/2018 -->
<meta name = "viewport" content = "user-scalable=no,width=device-width">
<link href = "rabbit-trap.css" rel = "stylesheet" type = "text/css">
<!--input type="text" id="demo-->
<title>Rabbit Trap</title>
</head>
<body>
<br>
<br>
<br>
<br>
<br>
<!center>
<!-- Added a menu to navigate projects from the main page -->
<div id = "menu">
<p>menu</p>
<div id = "menu-list">
<br>
part1
part2
part3
part4
part5
part6
part7
</div>
</div>
<canvas></canvas>
<!-- Since Rabbit Trap is a multi-part series and I didn't feel like writing
html and css for every single part, I decided to dynamically add the appropriate
js file containing the game logic for each part based on url parameters. -->
<script type = "text/javascript">
let part = String(window.location).split("?")[1];
/* Added on 03/09/2018 to allow reusing scripts from previous parts. */
let parts = {
"01":["01/controller-01.js", "01/display-01.js", "01/engine-01.js", "01/game-01.js", "01/main-01.js"],
"02":["02/controller-02.js", "02/display-02.js", "01/engine-01.js", "02/game-02.js", "02/main-02.js"],
"03":["02/controller-02.js", "03/display-03.js", "01/engine-01.js", "03/game-03.js", "03/main-03.js"],
"04":["02/controller-02.js", "04/display-04.js", "01/engine-01.js", "04/game-04.js", "03/main-03.js"],
"05":["02/controller-02.js", "05/display-05.js", "01/engine-01.js", "05/game-05.js", "05/main-05.js"],
"06":["02/controller-02.js", "05/display-05.js", "06/engine-06.js", "06/game-06.js", "06/main-06.js"],
"07":["02/controller-02.js", "05/display-05.js", "06/engine-06.js", "07/game-07.js", "07/main-07.js"],
};
switch(part) {
case "01": case "02": case "03": case "04": case "05": case "06": case "07": break;
default:
part = "05";
}
//new//
//<input type="button" value="button" id="movebutton" /> <!--removed inline JS-->
//new//
for (let index = 0; index < parts[part].length; index ++) {
let script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", parts[part][index]);
document.head.appendChild(script);
}
let menu = document.getElementById("menu");
let menu_list = document.getElementById("menu-list");
menu.addEventListener("click", function(event) {
menu_list.style.display = (menu_list.style.display == "none") ? "grid" : "none";
});
menu_list.style.display = "none";
</script>
<input id="clickMe" type="button" value="clickme" onclick="right" />
<input type="button" value="Change" id="1">
<input type="button" value="Change" id="2">
<input type="button" value="Change" id="3">
<!/center>
<!--new-->
<input type="button" value="button" id="demon" /?> <!--removed inline JS-->
<button id="demo" onclick="right">right</button>
</body>
</html>
sorry i know it's soo dirty code but i will try to clear the junk my self
all i need is help to create a button for movements "left,right,up"
thank you if you make it to the end and i appreciate your help
Here is an example on moving a square using both keyboard and mouse(button elements)
var pos = [0, 0], box = document.querySelector("#box"),
directions = {"37": "Left", "38": "Up", "39": "Right", "40": "Down"};
document.querySelector("#controls").onclick =
document.querySelector("body").onkeyup = function(e) {
var direction = e.type === "click" && e.target.nodeName === "BUTTON" ?
e.target.textContent : directions[e.keyCode];
switch(direction) {
case "Right": {
box.style.left = `${pos[0] + 50 > 300 ? 300 : pos[0] += 50}px`;
break;
}
case "Left": {
box.style.left = `${pos[0] - 50 < 0 ? 0 : pos[0] -= 50}px`;
break;
}
case "Down": {
box.style.top = `${pos[1] + 50 > 300 ? 300 : pos[1] += 50}px`;
break;
}
case "Up": {
box.style.top = `${pos[1] - 50 < 0 ? 0 : pos[1] -= 50}px`;
break;
}
}
};
#container {
width: 350px;
height: 350px;
background-color: orange;
border-radius: 10px;
position: relative;
}
#box {
width: 50px;
height: 50px;
background-color: blue;
border-radius: 10px;
position: absolute;
top: 0;
left: 0;
}
#controls {
margin-top: 10px;
width: 350px;
display: flex;
flex-wrap: wrap;
border-radius: 50%;
overflow: hidden;
box-shadow: 1px 1px 2px #333, -7px -2px 1px #ccc;
}
#controls button {
width: 50%;
height: 40px;
cursor: pointer;
font: bold 24px monospace;
color: white;
text-shadow: 0 0 1px black, -0 -0 1px black;
}
#controls .solo {
width: 100%;
}
#controls button:hover {
outline: none;
background-color: lightgreen;
}
<div id="container">
<div id="box"></div>
</div>
<div id="controls">
<button class="solo">Up</button>
<button>Left</button><button>Right</button>
<button class="solo">Down</button>
</div>
Related
If you calculate (45 - 5), the calculator will return 40 but if you click on the 5 it will concatenate 40 and 5 and it will make '405', I wanted the calculator to clear the display when I press the 5 to start a new operation so that the user doesn't have to manually clear the calculator with AC, I know I need to program a method that checks if an operation has been completed or not but I can't get it to work, can you help me? what I need to do? what code do i need to write to make this work? my github: https://github.com/JackHeroes/Calculator
class CalcController{
constructor(){
this._timeEl = document.querySelector('#time');
this._dateEl = document.querySelector('#date');
this._historicEl = document.querySelector('#historic');
this._displayCalcEl = document.querySelector('#display');
this._audio = new Audio('/audio/click.wav');
this._audioOnOff = false;
this._currentDate;
this._locale = 'pt-BR';
this._operation = [];
this._readyToClear = false;
this._lastNumber = '';
this._lastOperator = '';
this.initialize();
this.initButtonsEvents();
this.initKeyboard();
}
initialize(){
this.playAudio(true);
this.setDisplayDateTime();
setInterval(() =>{
this.setDisplayDateTime();
}, 1000);
this.setLastNumberToDisplay();
document.querySelector('#audio').addEventListener('click', e =>{
this.toggleAudio();
})
let icon = document.querySelector('#audio');
icon.addEventListener('click', e =>{
if(icon.classList.contains('bi-volume-up-fill')){
icon.classList.remove('bi-volume-up-fill');
icon.classList.add('bi-volume-mute-fill');
} else{
icon.classList.remove('bi-volume-mute-fill');
icon.classList.add('bi-volume-up-fill');
}
});
}
toggleAudio(){
this._audioOnOff = !this._audioOnOff;
}
playAudio(){
if(this._audioOnOff){
this._audio.currentTime = 0;
this._audio.play();
}
}
initKeyboard(){
document.addEventListener('keyup' , e =>{
this.playAudio();
switch(e.key){
case 'Escape':
this.clearAll();
break;
case 'Backspace':
this.clearEntry();
break;
case '+':
case '-':
case '*':
case '/':
this.addOperation(e.key);
break;
case 'Enter':
case '=':
this.calc();
break;
case ',':
case '.':
this.addDot();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.addOperation(parseInt(e.key));
break;
}
});
}
setDisplayDateTime(){
this.displayTime = this.currentDate.toLocaleTimeString(this._locale)
this.displayDate = this.currentDate.toLocaleDateString(this._locale, {day: '2-digit', month: 'long', year: 'numeric'})
}
setLastNumberToDisplay(){
let lastNumber = this.getLastItem(false);
if(!lastNumber) lastNumber = [0];
this.displayCalc = lastNumber;
}
addEventListenerAll(element, events, fn){
events.split(' ').forEach(event =>{
element.addEventListener(event, fn, false);
});
}
clearAll(value){
let alreadyCalled = false;
if (!alreadyCalled) {
this._operation = [];
this._lastNumber = '';
this._lastOperator = '';
this.setLastNumberToDisplay();
if(value) this.addOperation(value);
this._readyToClear = false;
alreadyCalled = true;
}
}
clearEntry(){
this._operation.pop();
this.setLastNumberToDisplay();
}
ClearLast(){
}
getLastOperation(){
return this._operation[this._operation.length-1];
}
setLastOperation(value){
this._operation[this._operation.length-1] = value;
}
isOperator(value){
return (['+','-','*','/'].indexOf(value) > -1);
}
pushOperation(value){
this._operation.push(value);
if(this._operation.length > 3){
this.calc();
}
}
addOperation(value){
if(isNaN(this.getLastOperation())){
if(this.isOperator(value)){
this.setLastOperation(value);
} else{
this.pushOperation(value);
this.setLastNumberToDisplay();
}
} else{
if(this.isOperator(value)){
this.pushOperation(value);
} else{
let newValue;
if(this.getLastOperation().toString() !== '0'){
newValue = this.getLastOperation().toString() + value.toString();
} else{
newValue = value.toString();
}
this.setLastOperation(newValue);
this.setLastNumberToDisplay();
}
}
if (this._readyToClear){
this.clearAll(value);
this._readyToClear = false;
return
}
}
addDot(){
let lastOperation = this.getLastOperation();
if(typeof lastOperation === 'string' && lastOperation.split('').indexOf('.') > -1) return;
if(this.isOperator(lastOperation) || lastOperation === undefined){
this.pushOperation('0.');
} else{
this.setLastOperation(lastOperation.toString() + '.');
}
this.setLastNumberToDisplay();
}
getResult(){
return eval(this._operation.join(''));
}
getLastItem(isOperator = true){
let lastItem;
for(let i = this._operation.length - 1; i >= 0; i--){
if(this.isOperator(this._operation[i]) == isOperator){
lastItem = this._operation[i];
break;
}
}
if(lastItem == 0){
return lastItem;
} else if(!lastItem){
lastItem = (isOperator) ? this._lastOperator : this._lastNumber;
}
return lastItem;
}
calc() {
let last = '';
this._lastOperator = this.getLastItem();
if (this._operation.length < 3) {
let firstItem = this._operation[0];
this._operation = [firstItem, this._lastOperator, this._lastNumber];
} else if (this._operation.length > 3) {
last = this._operation.pop();
this._lastNumber = this.getResult();
} else if (this._operation.length == 3) {
this._lastNumber = this.getLastItem(false);
}
let result = this.getResult();
this._operation = [result];
if (last) this._operation.push(last);
this.setLastNumberToDisplay();
}
setError(){
this.displayCalc = 'Erro';
}
execBtn(value){
this.playAudio();
switch(value){
case 'ac':
this.clearAll();
break;
case 'ce':
this.clearEntry();
break;
case 'cl':
this.ClearLast();
break;
case 'division':
this._readyToClear = false;
this.addOperation('/');
break;
case 'multiplication':
this._readyToClear = false;
this.addOperation('*');
break;
case 'subtraction':
this._readyToClear = false;
this.addOperation('-');
break;
case 'addition':
this._readyToClear = false;
this.addOperation('+');
break;
case 'dot':
this.addDot();
break;
case 'equal':
this.calc();
this._readyToClear = true;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.addOperation(parseInt(value));
break;
default:
this.setError();
break;
}
}
initButtonsEvents(){
let buttons = document.querySelectorAll('#buttons > section > button');
buttons.forEach((btn, index) =>{
this.addEventListenerAll(btn, 'click drag', e =>{
let textBtn = btn.className.replace('btn-', '');
this.execBtn(textBtn);
});
});
}
get displayTime(){
return this._timeEl.innerHTML;
}
set displayTime(value){
return this._timeEl.innerHTML = value;
}
get displayDate(){
return this._dateEl.innerHTML
}
set displayDate(value){
return this._dateEl.innerHTML = value
}
get displayHistoric(){
return this._historicEl.innerHTML
}
set displayHistoric(value){
return this._historicEl.innerHTML = value
}
get displayCalc(){
return this._displayCalcEl.innerHTML;
}
set displayCalc(value){
if (value.toString().length > 10){
this.setError();
return false;
}
this._displayCalcEl.innerHTML = value;
}
get currentDate(){
return new Date();
}
set currentDate(value){
this._currentDate = value;
}
}
window.calculator = new CalcController;
#font-face {
font-family: 'Digital-7';
src: url('/font/digital-7.ttf');
}
#calculator-container {
height: 100vh;
width: 100vh;
}
#calculator {
background-color: #B5ACEA;
border-radius: .5rem;
box-shadow: 0px 10px 0px 0px #8468EC;
width: fit-content;
}
#audio {
color: #F5F5F5;
cursor: pointer;
font-size: 2rem;
}
#display-container {
background-color: #3D2C8D;
border-radius: .5rem;
box-shadow: inset 0px 5px 0px 0px #1C0C5B;
font-family: 'Digital-7', sans-serif;
height: fit-content;
}
#time,
#date,
#historic,
#display {
color: #F5F5F5;
}
#historic {
height: 1rem;
}
#display {
font-size: 3rem;
height: 4rem;
}
#buttons button {
background-color: #3D2C8D;
border-radius: .5rem;
box-shadow: 0px 5px 0px 0px #1C0C5B;
color: #F5F5F5;
font-size: 1.5rem;
height: 5rem;
margin-bottom: .5rem;
margin-top: .5rem;
transition-duration: 1s, .1s;
transition-property: background-color, transform;
transition-timing-function: ease;
width: 5rem;
}
#buttons button:hover {
background-color: #1C0C5B;
}
#buttons button:active {
transform: translateY(5px);
}
#buttons .btn-ac,
#buttons .btn-ce,
#buttons .btn-cl,
#buttons .btn-equal {
background-color: #8468EC;
}
#buttons .btn-equal {
flex-grow: 2;
}
<!DOCTYPE html>
<html lang="pt-br">
<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>Calculator</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.10.3/font/bootstrap-icons.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container-fluid d-flex justify-content-center align-items-center" id="calculator-container">
<div class="container-fluid p-4" id="calculator">
<section class="mb-2">
<i class="bi bi-volume-up-fill" id="audio"></i>
</section>
<section class="display mb-2" id="display-container">
<div class="d-flex justify-content-between ps-2 pe-2 pt-2">
<p class="m-0" id="time"></p>
<p class="m-0" id="date"></p>
</div>
<div class="d-flex justify-content-end ps-2 pe-2">
<p class="m-0" id="historic"></p>
</div>
<div class="d-flex justify-content-end ps-2 pe-2 pb-2">
<p class="m-0" id="display">0</p>
</div>
</section>
<div id="buttons">
<section class="d-flex gap-2">
<button class="btn-ac">AC</button>
<button class="btn-ce">CE</button>
<button class="btn-cl"><i class="bi bi-x-octagon"></i></button>
<button class="btn-division">รท</button>
</section>
<section class="d-flex gap-2">
<button class="btn-7">7</button>
<button class="btn-8">8</button>
<button class="btn-9">9</button>
<button class="btn-multiplication">x</button>
</section>
<section class="d-flex gap-2">
<button class="btn-4">4</button>
<button class="btn-5">5</button>
<button class="btn-6">6</button>
<button class="btn-subtraction">-</button>
</section>
<section class="d-flex gap-2">
<button class="btn-1">1</button>
<button class="btn-2">2</button>
<button class="btn-3">3</button>
<button class="btn-addition">+</button>
</section>
<section class="d-flex gap-2">
<button class="btn-0">0</button>
<button class="btn-dot">.</button>
<button class="btn-equal">=</button>
</section>
</div>
</div>
</div>
<script src="/js/controller/CalcController.js"></script>
<script src="/js/calculator.js"></script>
</body>
</html>
Your code needs some additional state (by this I mean data or information) so that it knows if it should clear the display when a new button is pressed. A simple boolean variable would suffice such as shouldClear which the code sets to true when you press equals and back to false again after pressing any other button and clearing the display.
Every time i add the rats at the top dont fall down. I saw other people had this problem and it had to do with adding px to certain things. i have that in some of my code but i have no clue where else it needs it.
CSS
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Balloons Toss</title>
<meta charset="utf-8" />
<meta name="Author" content="Tyler Chretien" />
<meta name="Author" content="Karishma" />
<meta name="Author" content="Eric Nguygen" />
<meta name="robots" content="noindex, nofollow" />
<style>
#SPAN_1:hover{color:blue;}
#SPAN_1{color:black;}
#SPAN_2:hover{color:blue;}
#SPAN_2{color:black;}
table.center {
margin-left:auto;
margin-right:auto;
width: 560px;
text-align: center;
}
#font-face{
font-family: memes;
src: url(DeterminationSansWeb.woff);
}
body{
font-family: memes, sans-serif;
background-color: black;
}
.blackbox{
color: white;
width: 300px;
}
td{
height: 900px;
}
img, body{
-khtml-user-select: none;
-o-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
img {
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
}
</style>
JavaScript
<script>
var numberOfMonster= 0, setupScore, setupMonster, names=["rat.gif"],
catleft = 325, catright= 250, ratleft, ratright, countElement, howfast=
10, score = 0;
/*This function is the initial setup for the game aka score, sound,
monster spawn */
function myFunction()
{
spawntheMonster( 0 );
document.all.coolscore.innerHTML= 0;
setupScore=setInterval(function(){score++;
document.all.coolscore.innerHTML=score;}, 1000 );
setupMonster=setInterval(function(){spawntheMonster( 0 );}, 3000 );
document.getElementById('sound').play();
}
/*Next four function are deticated for moving the cat and setting
boundaries */
function leftArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.right.substring(element.style.right.length
- 2 , 0 )) > 0 ) {
element.style.right = parseInt(element.style.right) -
20 + 'px';
}
}
function rightArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.right.substring(element.style.right.length -
2
, 0 )) < 480 ) {
element.style.right = parseInt(element.style.right)
+ 20 + 'px';
}
}
function upArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.top.substring(element.style.top.length - 2
,
0 )) > 0 ) {
element.style.top = parseInt(element.style.top) -
20 + 'px';
}
}
function downArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.top.substring(element.style.top.length - 2 ,
0 )) < 740 ) {
element.style.top = parseInt(element.style.top) +
20 + 'px';
}
}
/* connects the id's of arrow keys and w,a,s,d to the previous
functions to be able to move */
function movetheguy(event){
switch (event.keyCode) {
case 39:
leftArrowPressed();
break;
case 37:
rightArrowPressed();
break;
case 38:
upArrowPressed();
break;
case 40:
downArrowPressed();
break;
case 68:
leftArrowPressed();
break;
case 65:
rightArrowPressed();
break;
case 87:
upArrowPressed();
break;
case 83:
downArrowPressed();
break;
}
}
/* sets spawn, attributes, and clickablity of the rats */
function spawntheMonster(monster){
var widthrandom = Math.floor(Math.random() * 112 )* 5 - 20;
widthrandom = "position:absolute; right: "+widthrandom+"; top:
000;";
var z = document.createElement("IMG");
z.setAttribute("src", names[monster]);
z.setAttribute("style", widthrandom);
z.setAttribute("width", "40");
z.setAttribute("height", "54");
z.setAttribute("id", numberOfMonster+"mon");
z.setAttribute("onLoad", "setInterval(moveguydown, 100, this);");
z.setAttribute("onClick", "this.style.top=parseInt(this.style.top)-75;");
document.getElementById("back1").appendChild(z);
numberOfMonster++;
}
/* moves the rats */
function moveguydown(moveMonster){
if(parseInt(moveMonster.style.top)>= 900 ){
moveMonster.style.top= -500;
moveMonster.style.right=Math.floor(Math.random() * 112 )* 5 -
20; //check this
}
else
moveMonster.style.top=parseInt(moveMonster.style.top)+howfast;
overlap(moveMonster);
}
/* randomly spawns the rats */
function randomspawn(){
spawntheMonster(Math.floor(Math.random() * names.length));
}
/* This function displays the end screen and resets game*/
function die(){
var highscore=document.all.coolscore.innerHTML;
var count;
for(count= 0 ; count<numberOfMonster; count++){
countElement=document.getElementById(count+"mon");
document.getElementById("back1").removeChild(countElement);
}
numberOfMonster = 0;
document.all.coolscore.innerHTML=
"GAME OVER<br><span onClick='location.reload();'>Click to restart!
</span><br>SCORE: "+score+
"<font size='5'><br>Thanks to<br>Cat By: PRguitarman<br>Sound By: Jay
Man<br>Rats By: Yacht Club Games";
clearInterval(setupScore);
clearInterval(setupMonster);
}
/* Compares hit boxes and checks to see if you die */
function overlap(obj){
catleft =parseInt(cat.style.right)+ 75;
catright=parseInt(cat.style.right);
ratleft =parseInt(obj.style.right)+parseInt(obj.width);
ratright=parseInt(obj.style.right);
cattop =parseInt(cat.style.top);
catbot=parseInt(cat.style.top)+ 150;
rattop =parseInt(obj.style.top)+parseInt(obj.height);
ratbottom=parseInt(obj.style.top);
if(rattop<catbot && ratbottom>cattop && ratright<catleft &&
ratleft>catright)
die();
}
/* Switches difficulty and sound */
function twospeeds(){
if(howfast== 30 ){//fast
back1.style.backgroundImage="url('large0.gif')";
howfast= 10;}
if(howfast== 10){//WAY too fast
back1.style.backgroundImage="url('large2.gif')";
howfast= 30;
document.getElementById('sound').src="sun.mp3";
document.getElementById('sound').play();
}
}
</script>
</head>
html
<body onKeyDown="" onkeyup="movetheguy(event);" >
<table class="center" style="position: relative;">
<tbody><tr>
<td id="back1" style="vertical-align: text-top; font-size:400%;
background-
image: url('large0.gif'); position: relative;">
<div class = "no-copy" id="coolscore">
<span onclick="myFunction();" id="SPAN_1">CLICK HERE
TO START</span>
<span onclick="twospeeds();" id="SPAN_2" style="font-
size:42px;">Click here for Insane mode</span>
<span style="font-size:24px;"><br>Use the Arrow Keys
or WASD to move<br>Click on the rats to move them up</span>
</div>
<br><br><br><br><img alt = "cat" src="cat.gif" width="75" height="150"
id="cat" style="position: absolute; right: 250px; top: 500px">
</td>
</tr>
</tbody>
</table>
<audio id="sound" hidden src="sound.mp3" >
</audio>
<audio id="sound2" hidden src="sun.mp3" >
</audio>
<footer style="border-top: 1px solid blue">
<a href="http://elvis.rowan.edu/~chretient7/"
title="Link to my home page">
Tyler Chretien
</a>
<span style="float: right;">
HTML5 /
<a href="http://jigsaw.w3.org/css-validator/check/referer?profile=css3">
CSS3 </a>
</span>
</footer>
</body>
</html>
https://github.com/Crouton18/game/blob/master/balloon.html
You can check by removing the in the code how it suppose to work. But in general the rats need to be falling down and when the cat gets hit the game ends.
Because the HTML tag is XHTML. Use this doctype instead:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
I am trying to highlight the single line of text in <textarea> with time delay. And I am wondering if I can choose a different color? The thing I wanted is when I click on the first <button>, the first line is highlighted into blue, click on the second <button>, 1 second later, the second line is highlighted into blue, lastly click on the third <button>, 2 second later, the third line is highlighted into yellow. I noticed I have a bug that I clicked on the button 3 times then the highlight doesn't work, but it is okay for me, I just want to know how to make the time delay and highlight with a different color. Thank you very much.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function() {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
You can use setTimeout() to set the delay in highlighting the text based on button id.
And ::selection css selector to style the portion of an element that is selected.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function(e) {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
var time = 0;
var tar_id = e.target.id;
var colors;
if(tar_id == 'line1' ) { colors = 'red'; }
else if(tar_id == 'line2' ) { time = 1000; colors = 'blue'; }
else if(tar_id == 'line3' ) { time = 2000; colors = 'green'; }
setTimeout(function(){
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
$('body').addClass(colors);
}, time);
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
.red ::selection {
color: red;
background: yellow;
}
.blue ::selection {
color: blue;
background: red;
}
.green ::selection {
color: green;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
I have two groups of quiz.
The first group is correct but the second group is not showing the line between two points.
The users click the point on the left and click the point on the right, then JavaScript creates a "canvas" line from the first element to the second element.
(I apologise for my english, it's my second language)
(function($) {
$.fn.connect = function(param) {
var _canvas;
var _ctx;
var _lines = new Array(); //This array will store all lines (option)
var _me = this;
var _parent = param || document;
var _lengthLines = $(_parent + ' .group1 .node').length;
var _selectFirst = null;
//Initialize Canvas object
_canvas = $('<canvas/>')
.attr('width', $(_me).width())
.attr('height', $(_me).height())
.css('position', 'absolute');
$(_parent).prepend(_canvas);
//$(_canvas).insertBefore(_parent);
this.drawLine = function(option) {
//It will push line to array.
_lines.push(option);
this.connect(option);
};
this.drawAllLine = function(option) {
/*Mandatory Fields------------------
left_selector = '.class',
data_attribute = 'data-right',
*/
if (option.left_selector != '' && typeof option.left_selector !== 'undefined' && $(option.left_selector).length > 0) {
$(option.left_selector).each(function(index) {
var option2 = new Object();
$.extend(option2, option);
option2.left_node = $(this).attr('id');
option2.right_node = $(this).data(option.data_attribute);
if (option2.right_node != '' && typeof option2.right_node !== 'undefined') {
_me.drawLine(option2);
}
});
}
};
//This Function is used to connect two different div with a dotted line.
this.connect = function(option) {
_ctx = _canvas[0].getContext('2d');
//
_ctx.beginPath();
try {
var _color;
var _dash;
var _left = new Object(); //This will store _left elements offset
var _right = new Object(); //This will store _right elements offset
var _error = (option.error == 'show') || false;
/*
option = {
left_node - Left Element by ID - Mandatory
right_node - Right Element ID - Mandatory
status - accepted, rejected, modified, (none) - Optional
style - (dashed), solid, dotted - Optional
horizantal_gap - (0), Horizantal Gap from original point
error - show, (hide) - To show error or not
width - (2) - Width of the line
}
*/
if (option.left_node != '' && typeof option.left_node !== 'undefined' && option.right_node != '' && typeof option.right_node !== 'undefined' && $(option.left_node).length > 0 && $(option.right_node).length > 0) {
//To decide colour of the line
switch (option.status) {
case 'accepted':
_color = '#0969a2';
break;
case 'rejected':
_color = '#e7005d';
break;
case 'modified':
_color = '#bfb230';
break;
case 'none':
_color = 'grey';
break;
default:
_color = 'grey';
break;
}
//To decide style of the line. dotted or solid
switch (option.style) {
case 'dashed':
_dash = [4, 2];
break;
case 'solid':
_dash = [0, 0];
break;
case 'dotted':
_dash = [4, 2];
break;
default:
_dash = [4, 2];
break;
}
/*
console.log($(option.left_node));
$(option.left_node)
$(option.right_node).data('connect',true);
*/
//If left_node is actually right side, following code will switch elements.
$(option.right_node).each(function(index, value) {
_left_node = $(option.left_node);
_right_node = $(value);
_left_node.attr('data-connect', true);
_right_node.attr('data-connect', true);
if (_left_node.offset().left >= _right_node.offset().left) {
_tmp = _left_node
_left_node = _right_node
_right_node = _tmp;
}
//Get Left point and Right Point
_left.x = _left_node.offset().left + _left_node.outerWidth();
_left.y = _left_node.offset().top + (_left_node.outerHeight() / 2);
_right.x = _right_node.offset().left;
_right.y = _right_node.offset().top + (_right_node.outerHeight() / 2);
//Create a group
//var g = _canvas.group({strokeWidth: 2, strokeDashArray:_dash});
//Draw Line
var _gap = option.horizantal_gap || 0;
_ctx.moveTo(_left.x, _left.y);
if (_gap != 0) {
_ctx.lineTo(_left.x + _gap, _left.y);
_ctx.lineTo(_right.x - _gap, _right.y);
}
_ctx.lineTo(_right.x, _right.y);
if (!_ctx.setLineDash) {
_ctx.setLineDash = function() {}
} else {
_ctx.setLineDash(_dash);
}
_ctx.lineWidth = option.width || 2;
_ctx.strokeStyle = _color;
_ctx.stroke();
});
//option.resize = option.resize || false;
} else {
if (_error) alert('Mandatory Fields are missing or incorrect');
}
} catch (err) {
if (_error) alert('Mandatory Fields are missing or incorrect');
}
//console.log(_canvas);
};
//It will redraw all line when screen resizes
$(window).resize(function() {
console.log(_me);
_me.redrawLines();
});
$(_parent + ' .group1 .node span').click(function() {
//console.log($(this).attr('data-connect'));
//[data-use="false"]
_this = this;
if ($(_this).attr('data-connect') != 'true' && $(_this).attr('data-use') == 'false') {
$(_parent + ' .group1 .node span').attr('data-use', 'false');
$(_this).attr('data-use', 'true');
_selectFirst = _this;
} else if ($(_this).attr('data-connect') == 'true') {
//console.log($(this).attr('data-id'));
//console.log(entry);
_lines.forEach(function(entry, index) {
if ($(_this).attr('data-id') == entry.id_left) {
$(entry.left_node).attr('data-use', 'false').attr('data-connect', 'false')
$(entry.right_node).attr('data-use', 'false').attr('data-connect', 'false')
_lines.splice(index, 1)
}
});
_me.redrawLines();
}
});
$(_parent + ' .group2 .node span[data-use="false"]').click(function() {
if ($(_parent + ' .group1 .node span[data-use="true"]').length == 1 && _selectFirst != null) {
if ($(this).attr('data-connect') != 'true') {
_me.drawLine({
id_left: $(_selectFirst).attr('data-id'),
id_right: $(this).attr('data-id'),
left_node: _selectFirst,
right_node: this,
horizantal_gap: 10,
error: 'show',
width: 1,
status: 'accepted'
});
$(_selectFirst).attr('data-use', 'false');
$(_selectFirst).attr('data-connect', 'true');
$(this).attr('data-use', 'false');
$(this).attr('data-connect', 'true');
}
}
});
this.redrawLines = function() {
_ctx.clearRect(0, 0, $(_me).width(), $(_me).height());
_lines.forEach(function(entry) {
entry.resize = true;
_me.connect(entry);
});
};
return this;
};
}(jQuery));
.clearfix {
clear: both;
}
body {
padding: 0px;
margin: 0px;
}
.nodes {
width: 500px
}
.node {
width: 100px;
background: #ddd;
color: #fff;
margin-bottom: 10px;
}
.group1 span {
background: #666;
border-radius: 50%;
width: 10px;
height: 10px;
margin-top: 5px;
}
.group2 span {
border: 1px solid #666;
border-radius: 50%;
width: 10px;
height: 10px;
margin-top: 5px;
}
.node span:hover {
background: #ff0000;
cursor: pointer;
}
.group1 {
float: left;
}
.group2 {
float: right;
}
.group2 .node span {
float: left;
position: relative;
left: -15px;
}
.group1 .node span {
float: right;
position: relative;
right: -15px;
}
.node span[data-connect=true] {
background: #ff00ff !important;
}
.node span[data-use=true] {
background: #ff0000 !important;
}
<div id="parentNodes_11">
<div class="nodes">
<div class="group1">
<div class="node">1<span class="node1" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">2 <span class="node2" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">3 <span class="node3" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="group2">
<div class="node">A <span class="node4" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">B <span class="node5" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">C <span class="node6" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
<br>
<div id="parentNodes_12">
<div class="nodes">
<div class="group1">
<div class="node">1<span class="node1" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">2 <span class="node2" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">3 <span class="node3" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="group2">
<div class="node">A <span class="node4" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">B <span class="node5" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">C <span class="node6" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#parentNodes_11 .nodes').connect('#parentNodes_11');
$('#parentNodes_12 .nodes').connect('#parentNodes_12');
});
</script>
This is due to the use of absolute coordinates for lines instead of relative ones, so your lines doesn't fit on the canvas.
You can just do the parent offset adjustment and it will work like this:
(function($) {
$.fn.connect = function(param) {
var _canvas;
var _ctx;
var _lines = new Array(); //This array will store all lines (option)
var _me = this;
var _parent = param || document;
var _lengthLines = $(_parent + ' .group1 .node').length;
var _selectFirst = null;
//Initialize Canvas object
_canvas = $('<canvas/>')
.attr('width', $(_me).width())
.attr('height', $(_me).height())
.css('position', 'absolute');
$(_parent).prepend(_canvas);
//$(_canvas).insertBefore(_parent);
this.drawLine = function(option) {
//It will push line to array.
_lines.push(option);
this.connect(option);
};
this.drawAllLine = function(option) {
/*Mandatory Fields------------------
left_selector = '.class',
data_attribute = 'data-right',
*/
if (option.left_selector != '' && typeof option.left_selector !== 'undefined' && $(option.left_selector).length > 0) {
$(option.left_selector).each(function(index) {
var option2 = new Object();
$.extend(option2, option);
option2.left_node = $(this).attr('id');
option2.right_node = $(this).data(option.data_attribute);
if (option2.right_node != '' && typeof option2.right_node !== 'undefined') {
_me.drawLine(option2);
}
});
}
};
//This Function is used to connect two different div with a dotted line.
this.connect = function(option) {
_ctx = _canvas[0].getContext('2d');
//
_ctx.beginPath();
try {
var _color;
var _dash;
var _left = new Object(); //This will store _left elements offset
var _right = new Object(); //This will store _right elements offset
var _error = (option.error == 'show') || false;
/*
option = {
left_node - Left Element by ID - Mandatory
right_node - Right Element ID - Mandatory
status - accepted, rejected, modified, (none) - Optional
style - (dashed), solid, dotted - Optional
horizantal_gap - (0), Horizantal Gap from original point
error - show, (hide) - To show error or not
width - (2) - Width of the line
}
*/
if (option.left_node != '' && typeof option.left_node !== 'undefined' && option.right_node != '' && typeof option.right_node !== 'undefined' && $(option.left_node).length > 0 && $(option.right_node).length > 0) {
//To decide colour of the line
switch (option.status) {
case 'accepted':
_color = '#0969a2';
break;
case 'rejected':
_color = '#e7005d';
break;
case 'modified':
_color = '#bfb230';
break;
case 'none':
_color = 'grey';
break;
default:
_color = 'grey';
break;
}
//To decide style of the line. dotted or solid
switch (option.style) {
case 'dashed':
_dash = [4, 2];
break;
case 'solid':
_dash = [0, 0];
break;
case 'dotted':
_dash = [4, 2];
break;
default:
_dash = [4, 2];
break;
}
/*
console.log($(option.left_node));
$(option.left_node)
$(option.right_node).data('connect',true);
*/
//If left_node is actually right side, following code will switch elements.
$(option.right_node).each(function(index, value) {
_left_node = $(option.left_node);
_right_node = $(value);
_left_node.attr('data-connect', true);
_right_node.attr('data-connect', true);
if (_left_node.offset().left >= _right_node.offset().left) {
_tmp = _left_node
_left_node = _right_node
_right_node = _tmp;
}
//Get Left point and Right Point
_left.x = _left_node.offset().left + _left_node.outerWidth();
_left.y = _left_node.offset().top + (_left_node.outerHeight() / 2) - _left_node.parents('.nodes').offset().top;
_right.x = _right_node.offset().left;
_right.y = _right_node.offset().top + (_right_node.outerHeight() / 2) - _right_node.parents('.nodes').offset().top;
//Create a group
//var g = _canvas.group({strokeWidth: 2, strokeDashArray:_dash});
//Draw Line
var _gap = option.horizantal_gap || 0;
_ctx.moveTo(_left.x, _left.y);
if (_gap != 0) {
_ctx.lineTo(_left.x + _gap, _left.y);
_ctx.lineTo(_right.x - _gap, _right.y);
}
_ctx.lineTo(_right.x, _right.y);
if (!_ctx.setLineDash) {
_ctx.setLineDash = function() {}
} else {
_ctx.setLineDash(_dash);
}
_ctx.lineWidth = option.width || 2;
_ctx.strokeStyle = _color;
_ctx.stroke();
});
//option.resize = option.resize || false;
} else {
if (_error) alert('Mandatory Fields are missing or incorrect');
}
} catch (err) {
if (_error) alert('Mandatory Fields are missing or incorrect');
}
//console.log(_canvas);
};
//It will redraw all line when screen resizes
$(window).resize(function() {
console.log(_me);
_me.redrawLines();
});
$(_parent + ' .group1 .node span').click(function() {
//console.log($(this).attr('data-connect'));
//[data-use="false"]
_this = this;
if ($(_this).attr('data-connect') != 'true' && $(_this).attr('data-use') == 'false') {
$(_parent + ' .group1 .node span').attr('data-use', 'false');
$(_this).attr('data-use', 'true');
_selectFirst = _this;
} else if ($(_this).attr('data-connect') == 'true') {
//console.log($(this).attr('data-id'));
//console.log(entry);
_lines.forEach(function(entry, index) {
if ($(_this).attr('data-id') == entry.id_left) {
$(entry.left_node).attr('data-use', 'false').attr('data-connect', 'false')
$(entry.right_node).attr('data-use', 'false').attr('data-connect', 'false')
_lines.splice(index, 1)
}
});
_me.redrawLines();
}
});
$(_parent + ' .group2 .node span[data-use="false"]').click(function() {
if ($(_parent + ' .group1 .node span[data-use="true"]').length == 1 && _selectFirst != null) {
if ($(this).attr('data-connect') != 'true') {
_me.drawLine({
id_left: $(_selectFirst).attr('data-id'),
id_right: $(this).attr('data-id'),
left_node: _selectFirst,
right_node: this,
horizantal_gap: 10,
error: 'show',
width: 1,
status: 'accepted'
});
$(_selectFirst).attr('data-use', 'false');
$(_selectFirst).attr('data-connect', 'true');
$(this).attr('data-use', 'false');
$(this).attr('data-connect', 'true');
}
}
});
this.redrawLines = function() {
_ctx.clearRect(0, 0, $(_me).width(), $(_me).height());
_lines.forEach(function(entry) {
entry.resize = true;
_me.connect(entry);
});
};
return this;
};
}(jQuery));
.clearfix {
clear: both;
}
body {
padding: 0px;
margin: 0px;
}
.nodes {
width: 500px
}
.node {
width: 100px;
background: #ddd;
color: #fff;
margin-bottom: 10px;
}
.group1 span {
background: #666;
border-radius: 50%;
width: 10px;
height: 10px;
margin-top: 5px;
}
.group2 span {
border: 1px solid #666;
border-radius: 50%;
width: 10px;
height: 10px;
margin-top: 5px;
}
.node span:hover {
background: #ff0000;
cursor: pointer;
}
.group1 {
float: left;
}
.group2 {
float: right;
}
.group2 .node span {
float: left;
position: relative;
left: -15px;
}
.group1 .node span {
float: right;
position: relative;
right: -15px;
}
.node span[data-connect=true] {
background: #ff00ff !important;
}
.node span[data-use=true] {
background: #ff0000 !important;
}
<div id="parentNodes_11">
<div class="nodes">
<div class="group1">
<div class="node">1<span class="node1" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">2 <span class="node2" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">3 <span class="node3" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="group2">
<div class="node">A <span class="node4" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">B <span class="node5" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">C <span class="node6" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
<br>
<div id="parentNodes_12">
<div class="nodes">
<div class="group1">
<div class="node">1<span class="node1" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">2 <span class="node2" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">3 <span class="node3" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="group2">
<div class="node">A <span class="node4" data-connect="false" data-id="0" data-use="false"></span></div>
<div class="node">B <span class="node5" data-connect="false" data-id="1" data-use="false"></span></div>
<div class="node">C <span class="node6" data-connect="false" data-id="2" data-use="false"></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#parentNodes_11 .nodes').connect('#parentNodes_11');
$('#parentNodes_12 .nodes').connect('#parentNodes_12');
});
</script>