Javascript global variable inside class function - javascript

I'm not really used to es5, so i'm having a bit of trouble since i'm forced to use es5 in my case. the problem is when I do, updateScoreboard({"name":"foo","bgColor":{"r":47.0,"b":79.0,"a":255.0,"g":79.0}})
to create a new panel on the scoreboard, my isPlayerInScoreboard function is returning false because playerName2 is somehow a global variable and not bound to the function PlayerPanel, you can see what I mean by invoking updateScoreboard({"name":"foo","bgColor":{"r":47.0,"b":79.0,"a":255.0,"g":79.0}})
and then logging out "playerName2", which I don't think should be a global variable but somehow is
edit: also when I do this
updateScoreboard({"name":"foo","bgColor":{"r":47.0,"b":79.0,"a":255.0,"g":79.0}})
updateScoreboard({"name":"bar","bgColor":{"r":47.0,"b":79.0,"a":255.0,"g":79.0}})
in my panels array, all the object's getPlayerName method returns the last inputted name, so in this case if I did panels[0].getPlayerName() it'd return "bar" which is should return "foo"
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: rgba(25, 25, 25, 0.50);
font-family: "Arial";
}
.tab {
margin: 1px auto;
width: 95%;
height: 30px;
background-color: white;
}
#title-header {
/*display:inline-block;*/
/*color: white;*/
font-size: 25px;
color: white;
/*border-top: 1px solid white;*/
/*border-bottom: 1px solid white;*/
margin:0 auto;
/*vertical-align: middle;*/
text-align:center;
/*white-space: nowrap;*/
}
.player-img {
display: inline-block;
/*width: 50px;*/
}
.player-name {
display: inline-block;
position: relative;
bottom: 10px;
color: white;
}
</style>
</head>
<body>
<div id="title-header">
<h1>SleekRP</h1>
</div>
<div class="main-scoreboard">
<div class="tab">
<div class="player-img">
<img src="https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg">
</div>
<p class="player-name">test</p>
</div>
<!-- <div class="tab"></div>
<div class="tab"></div>
<div class="tab"></div>
<div class="tab"></div> -->
</div>
<script>
var panels = [];
function setTitle(title){
document.getElementById("title-header").innerText = title
}
function isPlayerInScoreboard(name){
for (var i=0; i<panels.length; i++){
if (panels[i].getPlayerName() == name) {
return true
}
}
return false
}
function updateScoreboard(plyInfo){
if (!isPlayerInScoreboard(plyInfo.name)) {
PlayerPanel(plyInfo)
}
}
function PlayerPanel(plyInfo){
// Create element
var mainPanel = document.createElement('div')
mainPanel.className = "tab"
mainPanel.style.backgroundColor = "rgba(" + plyInfo.bgColor.r + ", " + plyInfo.bgColor.g + ", " + plyInfo.bgColor.b + ", 0.50)"
document.getElementsByClassName("main-scoreboard")[0].appendChild(mainPanel)
this.playerName2 = document.createElement('p')
this.playerName2.innerText = plyInfo.name
this.playerName2.className = "player-name"
mainPanel.appendChild(this.playerName2)
this.setPlayerName = function(name) {
this.playerName2.innerText = name
}
this.updatebGColor = function(bgColor){
mainPanel.style.backgroundColor = "rgba(" + bgColor.r + ", " + bgColor.g + ", " + bgColor.b + ", 0.50)"
}
this.getPlayerName = function() {
return this.playerName2.innerText
}
panels.push(this)
}
</script>
</body>
</html>

You should call your PlayerPanel with "new" when you are using "this" in it.
function updateScoreboard(plyInfo){
if (!isPlayerInScoreboard(plyInfo.name)) {
new PlayerPanel(plyInfo)
}
}

Related

It doesn't call the function but it jumps to the top of clickevent instead?

This is an excercise creating a replica of the Simon Game. The program randomly choses an increasing sequence of colors that the player must remember and replicate.
The first game works perfectly as far as I saw, but after failing the first the second game doesn't work. I thouroughly parsed the code using devtools and found that in the second game everything runs perfectly, when pressing the correct button. The nested if statements are fulfilled but when arrive to calling the function (setTimeout(nextRandomSequence,1500);) instead of executing the function (which works in the first game) it jumps back to the top of the click event replicating the button pressing. This duplicate the pressing in the variable gamePattern that then fails to pass the if test (equality between gamePattern and userClickedPattern arrays).
Why?
let userClickedPattern = []
let gamePattern = []
var randomChosenColor = []
let buttonColors = ["green", "red", "yellow", "blue"]
let level = 1
if (level === 1) {
// Press key to start and change title to level 1
$(document).keypress(function() {
$("#level-title").text("Level " + level);
// Select first color in game pattern
nextRandomSequence();
//Click event listener
$("div[type='button']")
.click(function sequence(e) {
let userChosenColor = e.target.id
console.log("user chosen color: " + userChosenColor);
pressButtonAnimation(userChosenColor);
playSound(userChosenColor);
userClickedPattern.push(userChosenColor);
console.log("compare arrays userClicked/gamePattern " + userClickedPattern + " " + gamePattern);
if (userClickedPattern[userClickedPattern.length - 1] === gamePattern[userClickedPattern.length - 1]) {
if (userClickedPattern.length === gamePattern.length) {
$("#level-title").text("Level " + level);
console.log(level);
console.log("----- continue ---------");
setTimeout(nextRandomSequence, 1500);
}
} else {
console.log("----- game over ---------");
playSound("wrong");
gameOverAnimation(userChosenColor);
$("#level-title").text("GAME OVER, your arrived to level " + level + " press any key to start");
restartGame();
console.log(level);
}
});
});
}
// select next color of game pattern. Push chosen color in gamePattern
function nextRandomSequence() {
console.log("--------- inside nextRandomSequence -------------")
userClickedPattern = []
randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber]
gamePattern.push(randomChosenColor);
level++;
$("#" + randomChosenColor).fadeIn(300).fadeOut(300).fadeIn(300);
playSound(randomChosenColor);
console.log("random chosen color " + randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function pressButtonAnimation(colorPressed) {
$("#" + colorPressed).addClass("pressed");
setTimeout(function() {
$("#" + colorPressed).removeClass("pressed");
}, 100)
}
function gameOverAnimation(colorPressed) {
$("body").addClass("game-over");
setTimeout(function() {
$("body").removeClass("game-over");
}, 200)
}
function restartGame() {
level = 1
gamePattern = []
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press a Key to Start</h1>
<div class="container">
<div lass="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="game.js" charset="utf-8"></script>
</body>
</html>

Background is not changing accordingly in html

I am remaking Wordle for a fun project to get my brain going. I have run into an issue though where squares are getting their background color changed when they are not supposed to.
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="l1" class="letterBox"></div>
<div id="l2" class="letterBox"></div>
<div id="l3" class="letterBox"></div>
<div id="l4" class="letterBox"></div>
<div id="l5" class="letterBox"></div>
<script src="script.js"></script>
</body>
</html>
js:
var letter = 0
var id
const word = ["h","e","l","l","o"]
var guess = []
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
var key = event.key
letter+=1
id = "l".concat(letter)
document.getElementById(id).innerHTML = key
guess.push(key)
event.preventDefault();
if(letter == 5){
for(i in word){
b=parseInt(i)+1-0
letter = word[i]
for(x in guess){
gulet = guess[x]
if(gulet==letter){
id = "l"+b
document.getElementById(id).style.background = "yellow"
}
}
}
}
}, true);
css:
html, body {
width: 100%;
height: 100%;
}
#element1 {display:inline-block;margin-right:10px;}
.letterBox {
display: inline-block;
text-align: center;
font-size: 40px;
height: 50px;
width: 50px;
background-color: #ffffff;
border: 2px solid black;
border-radius: 7px;
var letter = 0
var id
const word = ["h","e","l","l","o"]
var guess = []
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
var key = event.key
letter+=1
id = "l".concat(letter)
document.getElementById(id).innerHTML = key
guess.push(key)
event.preventDefault();
if(letter == 5){
for(i in word){
b=parseInt(i)+1-0
letter = word[i]
for(x in guess){
gulet = guess[x]
if(gulet==letter){
id = "l"+b
document.getElementById(id).style.background = "yellow"
}
}
}
}
}, true);
html, body {
width: 100%;
height: 100%;
}
#element1 {display:inline-block;margin-right:10px;}
.letterBox {
display: inline-block;
text-align: center;
font-size: 40px;
height: 50px;
width: 50px;
background-color: #ffffff;
border: 2px solid black;
border-radius: 7px;
<div id="l1" class="letterBox"></div>
<div id="l2" class="letterBox"></div>
<div id="l3" class="letterBox"></div>
<div id="l4" class="letterBox"></div>
<div id="l5" class="letterBox"></div>
The constant 'word' is what the letters are being compared to.
Someone removed this part so I am adding it back. An example of a word that breaks it is 'halaa' and 'haala'
I researched this problem and I have not found anyone with this same problem, so I do not know where to even start.
There are quite some mistakes in your code, I'll try to address them one by one:
Watch out ids with leading numbers
No need for the letter variable, we can use guess.length for the same result
id = "l".concat(letter) can just ben 'l' + n' (but not needed)
b=parseInt(i)+1-0 can be: parseInt(i) + 1, since the - 0 doesn't do anything
if(gulet==letter){ compares an char vs a int, won't work as expected
Fixing the above, simplifying the code, gives us something like:
const word = ["h","e","l","l","o"]
var guess = []
window.addEventListener("keydown", (event) => {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
event.preventDefault();
var key = event.key
var id = "l" + (guess.length + 1);
document.getElementById(id).innerHTML = key
guess.push(key)
if (guess.length == 5){
for (let i in guess){
if (guess[i] == word[i]){
id = 'l' + (+i + 1)
document.getElementById(id).style.background = "yellow" ;
}
}
}
}, true);
html, body { width: 100%; height: 100%; }
.letterBox { display: inline-block; text-align: center; font-size: 40px; height: 50px; width: 50px; background-color: #ffffff; border: 2px solid black; border-radius: 7px; }
#element1 {display:inline-block;margin-right:10px;}
<div id="l1" class="letterBox"></div>
<div id="l2" class="letterBox"></div>
<div id="l3" class="letterBox"></div>
<div id="l4" class="letterBox"></div>
<div id="l5" class="letterBox"></div>
I changed this code snippet for you & I hope it works
if(letter === 5){
let idx = 0;
for(let i in word){
if (word[i] === guess[i]) {
document.getElementById(`l${idx}`).style.background = "yellow";
}
idx++;
}
}

hover in css have does no effect when element is hoverd

So I made a bunch of divs stacked on each other, and I want each div to change its background color whenever its hover, but that's not what happens
When I hover an item its background color should change to green,
but it doesn't work even that I wrote div.oldiv:hover{background-color: #48FF0D;}
The problem is probably in CSS code.
Here is a snippet :
body{
background-color: #48FF0D;
}
#bigdiv {
height: 90%;
width: 100%;
}
.oldiv {
height: 0.390625%;
width: 100%;}
div.oldiv:hover{
background-color: #48FF0D;
}
#bigdiv2 {
height: 0;
width: 100%;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
cursor: pointer;
}
.uptodown {
background-color: #e7e7e7;
color: black;
}
.uptodown:hover {
background: #ddd;
}
.l{
float: right;
}
<body>
<script>
var b = "",k = "",a,q,d;
for(a = 0;a<=256;a++){
d =" <div id=\"du\" class=\"oldiv\" style=\"background-color: rgb("+a+","+a+","+a+");\"></div>";
q =" <div id=\"du\" class=\"oldiv\" style=\"background-color:rgb("+(256-a)+","+(256-a)+","+(256-a)+");\"></div>";
b = b+"\n"+d;
k = k+"\n"+q;
}
window.onload = function (){
document.getElementById("bigdiv").innerHTML = b;
document.getElementById("bigdiv2").innerHTML = k;
}
function utd(a){
var bigdiv = document.getElementById("bigdiv");
var bigdiv2 = document.getElementById("bigdiv2");
if(a == 0){
bigdiv.style.height = "0";
bigdiv2.style.height= "90%";
}else{
bigdiv.style.height = "90%";
bigdiv2.style.height= "0";
}
}
</script>
<div id="bigdiv">
</div>
<div id="bigdiv2">
</div>
<div>
<button class="btn uptodown" onclick="utd(0)">white to black</button>
<button class="btn uptodown l" onclick="utd(1)">black to white</button>
</div>
</body>
Don't word about all the Javascript, its just to generate elements and adding them to HTML
I have no idea what the purpose of this code is, but I think I have fixed it..... Whatever it is :P
Your #bigdiv and #bigdiv2 percentage height were not working because the height of the document wasn't 100%. So I just added html, body {height:100%;} to fix that.
/* code added START */
html, body {
height:100%;
}
div.oldiv:hover {
background-color: #48FF0D!important;
}
/* code added END */
body{
background-color: #48FF0D;
}
#bigdiv {
height: 90%;
width: 100%;
}
.oldiv {
height: 0.390625%;
width: 100%;
}
/* div.oldiv:hover{background-color: #48FF0D;} */
#bigdiv2 {
height: 0;
width: 100%;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
cursor: pointer;
}
.uptodown {
background-color: #e7e7e7;
color: black;
}
.uptodown:hover {
background: #ddd;
}
.l {
float: right;
}
<script>
var b = "",k = "",a,q,d;
for(a = 0;a<=256;a++){
d =" <div id=\"du\" class=\"oldiv\" style=\"background-color: rgb("+a+","+a+","+a+");\"></div>";
q =" <div id=\"du\" class=\"oldiv\" style=\"background-color:rgb("+(256-a)+","+(256-a)+","+(256-a)+");\"></div>";
b = b+"\n"+d;
k = k+"\n"+q;
}
function utd(a) {
var bigdiv = document.getElementById("bigdiv");
var bigdiv2 = document.getElementById("bigdiv2");
if(a == 0) {
bigdiv.style.height = "0";
bigdiv2.style.height= "90%";
} else {
bigdiv.style.height = "90%";
bigdiv2.style.height= "0";
}
}
</script>
<div id="bigdiv">
<script>document.write(b);</script>
</div>
<div id="bigdiv2">
<script>document.write(k);</script>
</div>
<div>
<button class="btn uptodown" onclick="utd(0)">white to black</button>
<button class="btn uptodown l" onclick="utd(1)">black to white</button>
</div>
Well, there is no use of Javascript here. I'm not able to understand what problem you're facing but refer here : https://www.w3schools.com/cssref/sel_hover.asp
CSS already has property of hover and can be used like element:hover {your properties inside like whatever event has to be happened on hover}. There is no need to use JS here. Hope this helps.
UPDATE:
I would also suggest you to follow good practice of writing JS code and CSS code in a separate file not in a HTML file.

Div's not sorting according to classes

I found this article that's supposed to be related to what I was looking for, which is sorting a list by class. However, in my code, it didn't work. So I'm trying to figure out how to solve the problem. I have two classes, "offline" and "none". I want the class "offline" to come at top and the class "none" to appear at bottom under "offline" area. I have one more class in each div's which is "indbox", therefore, I tried to use "getElementsByClassName" but it's not working.
Here's my code from codepen.
$(document).ready(function() {
$(".con-button").click(function(){
var cssObj = {};
cssObj.left = $(this).position().left;
cssObj.width = $(this).outerWidth();
$(".controls .effect").css( cssObj );
if(this.id == "c-all") {
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
});
$(".con-button").eq(0).trigger("click");
getSteams();
var elem = $('#offline').find('div').sort(sortMe);
function sortMe(a, b) {
return a.getElementsByClassName("offline") < b.getElementsByClassName("none");
}
$('#offline').append(elem);
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "OgamingSC2", "maatukka", "Vinesauce", "brunofin", "comster404", "esl_csgo"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.divider hr {
border-top: 1px solid #6441A4;
}
.effect {
position: absolute;
display: block;
left: 0;
bottom: 5px;
height: 2px;
width: 60px;
transition: 0.4s ease-in-out;
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
background: #6441A4;
}
.indbox {
width: 100%;
display: block;
margin: 5px 0px;
padding: 8px 0px;
}
.online {
background-color: #98FB98;
}
.offline {
background-color: #ff9999;
}
.none {
background-color: #D3D3D3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
<div class="effect"></div>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
The code I would like for you to focus on is:
var elem = $('#offline').find('div').sort(sortMe);
function sortMe(a, b) {
return a.getElementsByClassName("offline") < b.getElementsByClassName("none");
}
$('#offline').append(elem);
Please help me fix it.
Looking through your code, I find out that you are using thisSort Function; however, your way of doing is incorrect. In the example, they have:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
So in order to sort "offline" before "none", your function has to return 1
function sortMe(a, b){
if (a.hasClass("offline")) {
return 1; //if an element has offline, move it above.
} else {
return -1; //if an element doesn't have offline, it means it's none. Move it down.
}
}
You might want to add in the condition to check whether they both have offline class.
Your problem can be solved by using the :
appendTo();
method.
instead of the :
append();
method.
I added two additional divs in your html code and made a small change to your javascript code ant it works !!!
the html goes like this :
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline">
<div class="notconnected"></div>
<div class="nonexisting"></div>
</div>
</div>
and the javascript was changed here :
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
}
else {
game = "Offline";
status = "offline";
}
if(status==="none"){
$('<div class="indbox ' + status + '" id="'+status+'"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>').appendTo(".nonexisting");}
else{
$('<div class="indbox ' + status + '" id="'+status+'"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>').appendTo(".notconnected");
}
} );
The Documentation for the method is here : appendTo()

Jquery functions continue to apply even the CSS is changed. How do I stop this?

The fiddle first.
I have nameCards which expand and contract when clicked by adding/removing classes. Additionally, they move to different sections in the page when buttons are clicked (again by adding/removing classes). The problem: Despite them no longer having the classes needed to trigger the functions, the function still applies to them.
In the code, they move from .unmatched to .matched, so the function selector $('.matched.nameCard') should no longer work, but it does, as shown by the fact that the alert from the .click() still shows after it got moved.
I've tried event.stopProgation() basically everywhere in the functions, tried using a local variable instead of the global variable currentCard, and have double checked that the classes are changing by inspecting using .html. By my reasoning, the second they change from .unmatched to .matched the original function should stop working. Can anybody help me figure out why it's not?
Final note, the formatting got screwed up a little in the switch to fiddle, please forgive the funkyness. I tried to get rid of as much extra stuff as possible.
Edit: Changed from #matched in my question to .matched
Full code:
HTML
<div class="col-xs-3 col-sm-4 col-md-2">
<h2>Unmatched:</h2>
<div class="container-fluid matchBoxes" id="unmatched">
<div class="namesAndModals">
<div class="nameCard preClick unmatched" id="unmatchedFunctionalityShell">
<h2 class="memberName"></h2>
<div class="nameCardContents">
<button type="button" class="btn checkmark" id="yesBtn" href="#" data-toggle="modal" data-target="#pairModal">
<div class="checkmark_circle"></div>
<div class="checkmark_stem"></div>
<div class="checkmark_kick"></div>
</button>
<input type="text" placeholder="PNM ID#" class="IDnum ansField" autofocus/>
<input type="text" placeholder="Last Name" class="lastName ansField" id="lastName"/>
<input type="text" placeholder="First Name" class="firstName ansField" id="firstName"/>
</div>
</div>
<div class="nameCard preClick unmatched">
<h2 class="memberName">Jane Doe</h2>
</div>
<div class="nameCard preClick unmatched">
<h2 class="memberName">Jane Doe</h2>
</div>
<!-- Pairing Modal -->
<div id="pairModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ready to Pair?</h4>
</div>
<div class="modal-body">
<p id="pairDialog"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="pairButton" data-dismiss="modal">Pair</button>
<button type="button" class="btn btn-default" id="dismissButton" data-dismiss="modal">Never Mind</button>
</div>
</div>
</div>
</div>
</div>
</div>
<h2>Matched:</h2>
<div class="container-fluid matchBoxes" id="matched">
<div class="nameCard preClick matched">
<h2 class="memberName">Jane Doe</h2>
<div class="matchedNameCardContents">
<p class="pnmName">Jaime Doe</p>
</div>
</div>
</div>
CSS
* {
font-family: 'Gill Sans MT', 'Microsoft YaHai UI', sans-serif;
font-weight: 200;
}
#unmatched {
width: auto;
height: 300px;
background-color: rgba(211, 211, 211, .55);
border-radius: 10px;
margin: 10px 0;
overflow-y:scroll;
min-width: 270px;
}
#matched {
width: 110%;
height: 200px;
background-color: rgba(211, 211, 211, .55);
border-radius: 10px;
margin: 10px 0;
overflow-y:scroll;
min-width: 270px;
}
.nameCard {
width: 100%;
height: 70px;
background-color: rgba(255,100,171,.5);
border-radius: 10px;
display: block;
margin: 2px 1px;
overflow:auto;
}
.nameCard.preClick {
height: 30px;
}
.nameCard .nameCardContents {
display:none;
}
.nameCard h2 {
display:inline-block;
font-size: 20px;
font-weight: 500;
padding: 5px 0 3px 10px;
text-align: left;
width: 75%;
float:left;
}
.nameCard .IDnum {
display:inline-block;
margin: 5px 2px 3px 10px;
padding: 3px 0px 3px 2px;
width: 25%;
}
.nameCard .lastName {
display:inline-block;
margin: 5px 2px 3px 2px;
padding: 3px 0px 3px 2px;
width: 30%;
}
.nameCard .firstName {
display:inline-block;
margin: 5px 2px 3px 2px;
padding: 3px 0px 3px 2px;
width: 30%;
}
#unmatchedFunctionalityShell {
display:none;
}
.checkmark {
display:inline-block;
margin:auto;
margin-right:2px;
padding-right:0px;
-ms-transform: rotate(45deg); /* IE 9 */
-webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
transform: rotate(45deg);
}
.checkmark_circle {
position: absolute;
width:22px;
height:22px;
background-color: rgba(46,195,1,.8);
border-radius:11px;
left:0;
top:0;
}
.checkmark_stem {
position: absolute;
width:3px;
height:9px;
background-color:#fff;
left:11px;
top:6px;
}
.checkmark_kick {
position: absolute;
width:3px;
height:3px;
background-color:#fff;
left:8px;
top:12px;
}
#yesBtn{
display:inline-block;
background-color: rgba(46,195,1,0);
width:20px;
height:20px;
border-radius:11px;
}
/* Matched Members */
.matched.nameCard {
background-color: rgba(50, 205, 50, .5);
}
.matched p {
display: inline-block;
text-align: left;
margin-left: 10px;
padding-top: 5px;
}
.matched .btn {
display: inline-block;
background-color: rgba(255,37,37,.7);
padding: 4px;
float:right;
}
/*I had to use important here to get rid of the nameCardContents. Try and remove it later */
#matched .nameCardContents {
display:none !important;
}
#matched .preClick .matchedNameCardContents {
display:none;
}
Javascript
$(document).ready(function(){
$('.unmatched.nameCard').hover(function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
currentCard.off('click').on("click", function(event) {
// alert("hello");
//switches between "active" and "inactive (preClick)" card
$("#unmatched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.nameCardContents');
cardContents.appendTo(currentCard);
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
alert("this shouldn't happen after being moved to #matched");
} else {
cardContents.show();
alert("this shouldn't happen after being moved to #matched");
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.off('click', ".btn").on("click", ".btn", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
$("#pairDialog").text("Are you sure you want to pair " + memberName + " with " + pnmFirstName + " " + pnmLastName + "?");
});
currentCard.off('click', ".ansField").on("click", ".ansField", function(event) {
event.stopPropagation();
});
//Unmatched to Matched
$('#pairModal #pairButton').off('click').on("click", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
currentCard.removeClass('unmatched');
currentCard.addClass('matched');
currentCard.children(".nameCardContents").hide();
currentCard.append("<div class='matchedNameCardContents'><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.addClass('preClick');
currentCard.prependTo("#matched");
$("#lastName").val("");
$("#firstName").val("");
});
//Move from Unmatched to Unavailible
//Remove for one party
$('#discardModal #onePartyButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed for one party</p></div>")
newDiv.appendTo(currentCard);
});
//Remove for one round
$('#discardModal #oneRoundButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed for one round</p></div>")
newDiv.appendTo(currentCard);
});
//Remove for all recruitment
$('#discardModal #allRecruitmentButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed from recruitment</p></div>")
newDiv.appendTo(currentCard);
});
});
});
//Matched Name cards
$(document).ready(function(){
$('.matched.nameCard').off().hover(function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
var pnmName = $(this).children(".pnmName").text();
currentCard.on("click", function(event) {
//switches between "active" and "inactive (preClick)" card
//$("#matched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.matchedNameCardContents');
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
} else {
cardContents.show();
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.on("click", ".btn", function(event) {
$("#unpairButton").text("Are you sure you want to unpair " + memberName + " and " + pnmName + "?");
});
currentCard.on("click", ".ansField", function(event) {
event.stopPropagation();
});
//.unbind() is the best thing to happen to me
//Unmatched to Matched
$('#pairModal #pairButton').unbind('click').on("click", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
currentCard.removeClass('unmatched');
currentCard.addClass('matched');
currentCard.children(".nameCardContents").hide();
var addPNM = $("<div class='matchedNameCardContents'><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.append("<div><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.prependTo("#matched");
});
});
});
I figured it out! I looked into event delegation based on the comments and changed everything to take that into account. Here's a preview of what my new functions look like:
$(document).ready(function(){
$('#unmatched').off().on("mouseover", ".unmatched.nameCard", function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
currentCard.off('click').on("click", function() {
//switches between "active" and "inactive (preClick)" card
$("#unmatched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.nameCardContents');
cardContents.appendTo(currentCard);
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
} else {
cardContents.show();
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.off('click', ".btn").on("click", ".btn", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
$("#pairDialog").text("Are you sure you want to pair " + memberName + " with " + pnmFirstName + " " + pnmLastName + "?");
$("#removeMember").text("How long do you want to remove " + memberName + " from recruitment?");
});
});
});

Categories