can someone take a look at the code here is the problem screenshot
enter image description here
when clicking on sidebar user a popup appears after clicking on popup header it will go down and then if someone will click on the same user from sidebar a duplicate instance is created and click on the head will make the first one appear and 2nd one to go down.
I want to stop that duplication when someone clicks on sidebar user again then the already generated popup will toggle.
https://jsfiddle.net/hamzasgd/Lqyajokp/4/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook like chat popup layout</title>
</head>
<body>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
</body>
</html>
$(document).ready(function(){
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel") ;
$('[rel="'+chatbox+'"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel") ;
$('[rel="'+chatbox+'"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>'+
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox(){
i = 270 ; // start position
j = 260; //next position
$.each( arr, function( index, value ) {
if(index < 4){
$('[rel="'+value+'"]').css("right",i);
$('[rel="'+value+'"]').show();
i = i+j;
}
else{
$('[rel="'+value+'"]').hide();
}
});
}
});
I've added a check that will look if you already have a chatbox with that userID:
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
}
Please note that you have some invalid html. You are not allowed, to have the id on multiple element.
Demo
$(document).ready(function() {
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel");
$('[rel="' + chatbox + '"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel");
$('[rel="' + chatbox + '"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text();
if ($.inArray(userID, arr) != -1) {
arr.splice($.inArray(userID, arr), 1);
}
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
} else {
$('.msg_box[rel="' + userID + '"] .msg_wrap').slideToggle('slow');
}
});
$(document).on('keypress', 'textarea', function(e) {
if (e.keyCode == 13) {
var msg = $(this).val();
$(this).val('');
if (msg.trim().length != 0) {
var chatbox = $(this).parents().parents().parents().attr("rel");
$('<div class="msg-right">' + msg + '</div>').insertBefore('[rel="' + chatbox + '"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox() {
i = 270; // start position
j = 260; //next position
$.each(arr, function(index, value) {
if (index < 4) {
$('[rel="' + value + '"]').css("right", i);
$('[rel="' + value + '"]').show();
i = i + j;
} else {
$('[rel="' + value + '"]').hide();
}
});
}
});
/**** Chat Popup Layout******/
body {
background: #e5e5e5;
font-family: sans-serif;
}
.msg_box {
position: fixed;
bottom: -5px;
width: 250px;
background: white;
border-radius: 5px 5px 0px 0px;
}
.msg_head {
background: black;
color: white;
padding: 8px;
font-weight: bold;
cursor: pointer;
border-radius: 5px 5px 0px 0px;
}
.msg_body {
background: white;
height: 200px;
font-size: 12px;
padding: 15px;
overflow: auto;
overflow-x: hidden;
}
.msg_input {
width: 100%;
height: 55px;
border: 1px solid white;
border-top: 1px solid #DDDDDD;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.close {
float: right;
cursor: pointer;
}
.minimize {
float: right;
cursor: pointer;
padding-right: 5px;
}
.msg-left {
position: relative;
background: #e2e2e2;
padding: 5px;
min-height: 10px;
margin-bottom: 5px;
margin-right: 10px;
border-radius: 5px;
word-break: break-all;
}
.msg-right {
background: #d4e7fa;
padding: 5px;
min-height: 15px;
margin-bottom: 5px;
position: relative;
margin-left: 10px;
border-radius: 5px;
word-break: break-all;
}
/**** Slider Layout Popup *********/
#chat-sidebar {
width: 250px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #b2b2b2;
}
#sidebar-user-box {
padding: 4px;
margin-bottom: 4px;
font-size: 15px;
font-family: Calibri;
font-weight: bold;
cursor: pointer;
}
#sidebar-user-box:hover {
background-color: #999999;
}
#sidebar-user-box:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
img {
width: 35px;
height: 35px;
border-radius: 50%;
float: left;
}
#slider-username {
float: left;
line-height: 30px;
margin-left: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
Related
Im making an user generated music playlist. The user drops files / adds files with the button.
However, whenever more files are dropped / added, the previously added files are replaced.
How to modify code to append the files with the previously added files?
PS:
I have used jquery to build the app. I have used jquery, cos i want to work with audio time duration(to find total playtime of the playlist, etc) and its a bit difficult to accomplish that with vanillaJS.
var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};
var objectUrl;
// Function
$(function() {
var ooleft = dropZone.offset().left;
var ooright = dropZone.outerWidth() + ooleft;
var ootop = dropZone.offset().top;
var oobottom = dropZone.outerHeight() + ootop;
document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
dropZone.addClass(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
if (buttonId != "") {
var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left;
var oright = clickZone.outerWidth() + oleft;
var otop = clickZone.offset().top;
var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
if (!(x < oleft || x > oright || y < otop || y > obottom)) {
inputFile.offset({
top: y - 15,
left: x - 160
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
});
}
document.getElementById(dropZoneId).addEventListener("drop", function(e) {
$("#" + dropZoneId).removeClass(mouseOverClass);
}, true);
// FILE
inputFile.on('change', function(e) {
finalFiles = {};
$('#filename').html("");
var fileNum = this.files.length,
initial = 0,
counter = 0;
$.each(this.files, function(idx, elm) {
finalFiles[idx] = elm;
});
for (initial; initial < fileNum; initial++) {
counter = counter + 1;
// Object URL
var file = e.currentTarget.files[initial];
objectUrl = URL.createObjectURL(file);
$("#filename").prop("src", objectUrl);
//console.log('Object URL: ', objectUrl);
//console.log('FILE: ', file);
// Object URL End
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file-audio-o"></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + '</strong></span> ' + '<audio controls controlsList="nodownload noplaybackrate" preload="auto" id="audioFiles" >' + '<source src="' + objectUrl + '" type="audio/mpeg" />' + '</audio>' + '<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span> ' + this.files[initial].name + '</div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '">' + '<audio controls id="audioFiles" >' + '<source src="' + objectUrl + '/' + this.files[initial].name + '" type="audio/mpeg" />' + '</audio>' + '</div>');
console.log('NAME: ', this.files[initial].name);
//console.log('INITIAL: ', this.files[initial]);
// Audio Duration
var Duration;
$(audioFiles).on("canplay", function() {
console.log('THIS DURATION: ', this.duration);
Duration = this.duration;
});
// Audio Duration End
}
// Total File Count
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').css("display", "initial");
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
// End Total File Count
});
})
function removeLine(obj) {
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
//console.log(finalFiles);
URL.revokeObjectURL(objectUrl);
// Total Files
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
if (count == 0) {
$('#totalFiles').css("display", "none");
} else {}
}
// Draggable Items
$(function() {
$('.draggable, .droppable').sortable({
connectWith: '.playlists'
});
});
#import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: visible;
font-family: 'Source Code Pro', monospace;
}
.dropper {
padding: 10px;
}
#drop-zone {
width: 100%;
min-height: 150px;
border: 3px dashed rgba(0, 0, 0, .3);
border-radius: 5px;
font-family: 'Source Code Pro', monospace;
text-align: center;
position: relative;
font-size: 20px;
color: #7E7E7E;
}
#drop-zone input {
position: absolute;
cursor: pointer;
left: 0px;
top: 0px;
opacity: 0;
}
/*Important*/
#drop-zone.mouse-over {
border: 3px dashed rgba(0, 0, 0, .3);
color: #7E7E7E;
}
/*If you dont want the button*/
#clickHere {
display: inline-block;
cursor: pointer;
color: white;
font-size: 1rem;
width: 200px;
border-radius: 0px;
background-color: #000000;
padding: 10px;
}
#clickHere:hover {
background-color: #376199;
}
.uploadedFiles {
padding: 0;
margin: 10px 50px;
}
#filename {
margin-top: 10px;
margin-bottom: 10px;
padding: 10px;
font-size: 14px;
line-height: 1.5em;
border: 1px solid;
min-height: 200px;
max-height: 400px;
overflow-y: scroll;
color: #240aff;
}
#filename span {
font-size: 1.5rem;
line-height: 1.2rem;
height: 1.5rem;
width: 1.5rem;
}
/* File Info */
#totalFiles {
border: 1px solid #06a7e5;
padding: 5px;
display: none;
}
.file-preview {
background: rgb(99, 8, 8);
border: 5px solid #fff;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
display: inline-block;
width: 60px;
height: 60px;
text-align: center;
font-size: 14px;
margin-top: 5px;
}
.closeBtn {
color: black;
display: inline-block;
vertical-align: -20%!important;
}
.closeBtn:hover {
color: red;
display: inline-block;
cursor: pointer;
}
.playlist {
border: 1px solid black;
padding: 10px;
margin: 5px;
background: #e9eaf9;
}
.playlist:hover {
cursor: move;
}
/* AUDIO CONTROLS */
#audioFiles {
vertical-align: middle;
margin: 0px 10px 0px 0px;
}
audio {
/*
filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
*/
width: 25%;
height: 35px;
}
audio::-webkit-media-controls-enclosure {
border-radius: 5px;
background-color: #cfcfcf;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload & Draggable</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js" integrity="sha256-xH4q8N0pEzrZMaRmd7gQVcTZiFei+HfRTBPJ1OGXC0k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
</head>
<body>
<div class="dropper">
<div id="drop-zone">
<p>Drop files here</p>
<div id="clickHere">or click here <i class="fa fa-upload"></i>
<input type="file" name="file" id="file" multiple accept="audio/*" />
</div>
</div>
</div>
<div class="uploadedFiles">
<p>Uploaded Files are Draggable. <span id="totalFiles"></span></p>
<div id="filename" class="playlists droppable"></div>
</div>
<!--
<audio id="audio2"></audio>
<p>
<label>File Size:</label>
<span id="filesize"></span>
<input type="hidden" id="size" name="size" value="" />
</p>
<p>
<label>Total Duration:</label>
<span id="duration"></span>
<input type="hidden" id="timelength" name="time" value="" />
</p>
-->
<script src="./script.js" async defer></script>
</body>
</html>
It worked well when i removed the following line of jquery code:
$('#filename').html("");
I am creating an HTML table dynamically from JSON objects. I am trying to create a filter for one of the table columns. It works fine but I cannot make it work with a multiselect function.
I tried adding this line:
$('.One1').multiselect();
in my script, in different places and it did not work.
var data = {"headers":["One","Two","Three","Four","Five","Six","Seven","Number1","Number2"],"rows":[["One1","Two1","Three1","Four1","Five1","Six1","Seven1",11,1000],["One1","Two1","Three2","Four1","Five1","Six1","Seven1", 22, 2000],["One2","Two1","Three1","Four2","Five1","Six1","Seven1", 77, 99]]};
//////First table - Three1 for Views
var table1 = '<div class = "filter_box"></div><div class="row"><div class="col-lg-6" style="background-color: #e90649; width: 117px;"> </div><div class="col-lg-6" style="max-width: 100px; padding-left: 10px; font-size: 2vw;">Table<br/><br/><span style="font-size: 1vw;">One1, Three1, Five1</span></div><div class="col-lg-6"><div class="container"><table><thead><tr></tr><tr><th>One</th><th>Two</th><th>Three</th><th>Four</th><th>Five</th><th>Six</th><th>Seven</th><th>Number1</th><th>Number2</th></tr></thead><tbody>';
var One = '<div class = "filter"><select class="One1" data-col="0"><option value="a">' + "One" + '</option>';
for (i = 0; i < data.rows.length; i++)
{
table1 +="<tr><td>" + data.rows[i][0] + "</td><td>" + data.rows[i][1] + "</td><td>" + data.rows[i][2] + "</td><td>" + data.rows[i][3] + "</td><td>" + data.rows[i][4] + "</td><td>" + data.rows[i][5] + "</td><td>" + data.rows[i][6] + "</td><td>" + data.rows[i][7].toLocaleString() + "</td><td>" + data.rows[i][8].toLocaleString() + "</td><td>" + "</td></tr>";
// Interactive filters
One +='<option value="' + i + '">' + data.rows[i][0] + '</option>';
}
table1 += '</tbody></table></div></div></div>';
One +='</select></div>';
$("#one").html(table1);
$(".filter_box").html(One);
////First table - Filter
$('.One1').change(function () {
var values = [];
$('.One1').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push({
text: $(this).text(),
colId: colIdx
});
});
});
One1('#one table > tbody > tr', values);
});
function One1(selector, values) {
$(selector).each(function () {
var sel = $(this);
var txt = sel.find('td:eq(0)').text().trim();
var hwMatches = values.filter(function(ele, idx) {
return ele.text == txt;
}).length;
sel.toggle(hwMatches > 0 || values.length == 0);
});
};
//$('.One1').multiselect();
#import url('https://fonts.googleapis.com/css?family=Roboto');
body, * {
margin: 0;
color:#fff;
font-family: Roboto;
text-transform:capitalize;
}
.row {
display: table;
width: 100%;
height: 241px;
background-color:#454545;
}
.row > .col-lg-6 {
display: table-cell;
vertical-align: middle;
}
.container {
/*display: flex;*/
flex-wrap: wrap;
}
.container > div {
padding: 15px;
margin: 5px;
flex: 0 0 calc(100% - 20px);
text-align: left;
}
/*img {
padding-left: 7%;
max-height:55px;
width:auto;
}*/
td{
padding: 2px 2px;
text-align: center;
margin: 6px 0;
border: none;
}
table{
width: 100%;
background-color:#454545;
font-weight:500;
border-collapse: separate;
border-spacing:0.3em 1.1em;
color: #fff;
border: 0;
}
tr{
font-size: 1.1em;
}
th {
color: #CCC;
font-size: 0.7em;
}
#one,#two,#three,#four{
padding-top:2%;
}
.filter
{
margin:1px;
width:20%;
text-align:center;
display:inline-block;
}
.filter_box
{
text-align:center;
display:inline-block;
width:100%;
}
.filter select, .multiselect dropdown-toggle btn btn-default {
min-width:120px;
-webkit-appearance: button;
-webkit-border-radius: 2px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
-webkit-padding-end: 20px;
-webkit-padding-start: 2px;
-webkit-user-select: none;
background-image: url(http://i62.tinypic.com/15xvbd5.png), -webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
background-position: 97% center;
background-repeat: no-repeat;
border: 1px solid #AAA;
color: #000;
font-size: inherit;
margin: 3px;
overflow: hidden;
padding: 1px 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
/*
tr th:nth-child(5) {
background: red;
display:none;
}
tr td:nth-child(5) {
background: red;
display:none;
}
*/
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<div id="one"></div>
When you declare your select, you can specify it is multiple:
var One = '<div class = "filter"><select class="One1" data-col="0"><option value="a">' + "One" + '</option>';
Change it to:
var One = '<div class = "filter"><select multiselect class="One1" data-col="0"><option value="a">' + "One" + '</option>';
Result:
var data = {"headers":["One","Two","Three","Four","Five","Six","Seven","Number1","Number2"],"rows":[["One1","Two1","Three1","Four1","Five1","Six1","Seven1",11,1000],["One1","Two1","Three2","Four1","Five1","Six1","Seven1", 22, 2000],["One2","Two1","Three1","Four2","Five1","Six1","Seven1", 77, 99]]};
//////First table - Three1 for Views
var table1 = '<div class = "filter_box"></div><div class="row"><div class="col-lg-6" style="background-color: #e90649; width: 117px;"> </div><div class="col-lg-6" style="max-width: 100px; padding-left: 10px; font-size: 2vw;">Table<br/><br/><span style="font-size: 1vw;">One1, Three1, Five1</span></div><div class="col-lg-6"><div class="container"><table><thead><tr></tr><tr><th>One</th><th>Two</th><th>Three</th><th>Four</th><th>Five</th><th>Six</th><th>Seven</th><th>Number1</th><th>Number2</th></tr></thead><tbody>';
var One = '<div class = "filter"><select multiple class="One1" data-col="0"><option value="a">' + "One" + '</option>';
for (i = 0; i < data.rows.length; i++)
{
table1 +="<tr><td>" + data.rows[i][0] + "</td><td>" + data.rows[i][1] + "</td><td>" + data.rows[i][2] + "</td><td>" + data.rows[i][3] + "</td><td>" + data.rows[i][4] + "</td><td>" + data.rows[i][5] + "</td><td>" + data.rows[i][6] + "</td><td>" + data.rows[i][7].toLocaleString() + "</td><td>" + data.rows[i][8].toLocaleString() + "</td><td>" + "</td></tr>";
// Interactive filters
One +='<option value="' + i + '">' + data.rows[i][0] + '</option>';
}
table1 += '</tbody></table></div></div></div>';
One +='</select></div>';
$("#one").html(table1);
$(".filter_box").html(One);
////First table - Filter
$('.One1').change(function () {
var values = [];
$('.One1').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push({
text: $(this).text(),
colId: colIdx
});
});
});
One1('#one table > tbody > tr', values);
});
function One1(selector, values) {
$(selector).each(function () {
var sel = $(this);
var txt = sel.find('td:eq(0)').text().trim();
var hwMatches = values.filter(function(ele, idx) {
return ele.text == txt;
}).length;
sel.toggle(hwMatches > 0 || values.length == 0);
});
};
//$('.One1').multiselect();
#import url('https://fonts.googleapis.com/css?family=Roboto');
body, * {
margin: 0;
color:#fff;
font-family: Roboto;
text-transform:capitalize;
}
.row {
display: table;
width: 100%;
height: 241px;
background-color:#454545;
}
.row > .col-lg-6 {
display: table-cell;
vertical-align: middle;
}
.container {
/*display: flex;*/
flex-wrap: wrap;
}
.container > div {
padding: 15px;
margin: 5px;
flex: 0 0 calc(100% - 20px);
text-align: left;
}
/*img {
padding-left: 7%;
max-height:55px;
width:auto;
}*/
td{
padding: 2px 2px;
text-align: center;
margin: 6px 0;
border: none;
}
table{
width: 100%;
background-color:#454545;
font-weight:500;
border-collapse: separate;
border-spacing:0.3em 1.1em;
color: #fff;
border: 0;
}
tr{
font-size: 1.1em;
}
th {
color: #CCC;
font-size: 0.7em;
}
#one,#two,#three,#four{
padding-top:2%;
}
.filter
{
margin:1px;
width:20%;
text-align:center;
display:inline-block;
}
.filter_box
{
text-align:center;
display:inline-block;
width:100%;
}
.filter select, .multiselect dropdown-toggle btn btn-default {
min-width:120px;
-webkit-appearance: button;
-webkit-border-radius: 2px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
-webkit-padding-end: 20px;
-webkit-padding-start: 2px;
-webkit-user-select: none;
background-image: url(http://i62.tinypic.com/15xvbd5.png), -webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
background-position: 97% center;
background-repeat: no-repeat;
border: 1px solid #AAA;
color: #000;
font-size: inherit;
margin: 3px;
overflow: hidden;
padding: 1px 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
/*
tr th:nth-child(5) {
background: red;
display:none;
}
tr td:nth-child(5) {
background: red;
display:none;
}
*/
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<div id="one"></div>
For example if you want to filter "One1" in a table, you can simply use something like: $('td:contains("One1")').parent().hide(); and $('td:contains("One1")').parent().show(); as a filter.
If you want to filter specific column, combine something like this with your selector: $('table tr > td:nth-child(yourColumnNumberShouldBeFiltered), table tr > th:nth-child(yourColumnNumberShouldBeFiltered)'). These expressions may be used in a function binded to 'change' event of your multiselect.
UPDATE: Above method, because of using :contains(), filter all of "One1", "One12", and so on! For exact match filteration you can use something like this:
$('table tr > td:nth-child(yourColumnNumberShouldBeFiltered)').filter(function() {
return $(this).text() == "yourExactTextToFilter";
}).parent().hide();
$('table tr > td:nth-child(yourColumnNumberShouldBeFiltered)').filter(function() {
return $(this).text() == "yourExactTextToFilter";
}).parent().show();
or for better performance of getting exact matches, see this link: Select element by exact match of its content
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " °C";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " °F";
}
I am trying to use a button on click event to change the temp display, but it doesn't seem to work like this. The function keeps seeing Celsius no matter what. I tried $(this).html too. The text of the button is actually changing, just the function isn't updating. I tried running the change units function inside the the button click even as well and it still doesn't update.
What am I not understanding about this onclick event and how can I get it to work.
JS Code:
var apiKey = "get your own key from http://openweathermap.org";
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " °C";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " °F";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
var currentTemp = changeUnits(weather.main.temp);
var high = changeUnits(weather.main.temp_max);
var low = changeUnits(weather.main.temp_min);
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
$('#currentTemp').html(currentTemp);
$('#high-low').html('<span id="high">High: ' + high + '</span><br>'
+ '<span id="low">Low: ' + low + '</span>');
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"><h1 id="currentLocation">Your Current Location is </h1></div>
<div class="navbar"></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<h2 class="text-center content-title" id="currentTemp"></h2>
<div class="content-body text-center">
<p id="high-low"></p>
<button data-text-swap="Fahrenheit" id="unitButton" type="button" class="btn btn-success">Celsius</button>
<p id="currentConditions"></p>
</div>
</div>
</body>
</html>
I have done every change I can think of. console.log(el.text()) in the onclick clearly shows the text changing; but the function for changeUnits never seems to pick it up in the if statement when I run the function again during the onclick.
Looks like you're using html() instead of text(). I assume you're looking for button text instead of html, so try this:
$('.btn').on("click", function() {
$(this).text(function(f, c) {
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
});
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius'){
return Math.round(Temp - 273.15) + " °C";
}else{
return Math.round((Temp* (9/5)) - 459.67) + " °F";
}
}
you are not calling the function, read comments in code
Also you are not passing any information to the '.btn' in the function passed to the text method.
$('.btn').on("click", function() {
var text = function(f, c) { // where are you getting your f and c parameters?
console.log(f); // should be undefined
console.log(c); // should be undefined
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
}();
console.log(text); // should be 'Celsius'
$(this).text(text); // changed from }) to }())
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius') // change html() to text() as well
return Math.round(Temp - 273.15) + " °C";
else
return Math.round((Temp* (9/5)) - 459.67) + " °F";
}
Additionaly you should use a ID to associate your button to do this
<input id='thisID'>
// then call it in javascript
$("#thisID")
Toggleing the button
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
});
Here is what I think is your problem. I didn't get to test it because I need to get the weather API and stuff. By looking at your code, here is what I get.
When the page loads, you are getting weather data from OpenWeatherMap. However, you are not cashing this info in some sort of global variable in order for you to access it later. You have declared all your variables inside the ajax callback and you have no way of accessing them later.
Try to do this:
var currentTemp;
var high;
var low;
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
currentTemp = weather.main.temp;
high = weather.main.temp_max;
low = weather.main.temp_min;
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
updateDisplay();
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
function changeUnits(Temp) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " °C";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " °F";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
updateDisplay();
});
function updateDisplay(){
$('#currentTemp').html(changeUnits(currentTemp));
$('#high-low').html('<span id="high">High: ' + changeUnits(high) + '</span><br>'
+ '<span id="low">Low: ' + changeUnits(low) + '</span>');
}
I have introduced another function updateDisplay() to actually handle the changing of the displayed temps. As I said, I didn't get to test it. But I am pretty sure it will work.
JS:
var apiKey="get an openweathermap APIKey";
var loc;
var lat;
var long;
var temp;
var high;
var low;
var icon;
//var wind;
//var windDir;
//var windSpd;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
lat = parseFloat(loc[0]);
long = parseFloat(loc[1]);
getWeather(lat, long);
initGmaps(lat, long);
});
//api call to use lat and long to generate a map
window.addEventListener('load', function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '?key=AIzaSyDKgEmSnYmFmbhQVGY8K6NXxV5ym2yZXdc&callback=initMap';
document.body.appendChild(script);
});
function initGmaps(lat, long) {
var map = new GMaps({
div: '#map',
lat: lat,
lng: long,
zoom: 14,
disableDefaultUI: true,
mapTypeId: "satellite",
});
map.addMarker({
lat: lat,
lng: long
});
}
//using weather to get data and plug it into our page
function getWeather(lat, long) {
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
lat + '&lon=' + long + '&appid=' + apiKey;
$.ajax({
url: api,
dataType: 'json',
success: function(data) {
temp = {
f: Math.round(((data.main.temp * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp - 273.15)) * 100) / 100 + " °C"
};
high = {
f: Math.round(((data.main.temp_max * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
low = {
f: Math.round(((data.main.temp_min * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
windSpd = {
f: Math.round((data.wind.speed * 2.23694)*10)/10 + " MPH",
c: Math.round((data.wind.speed)*10)/10 + " M/S"
};
var windArr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
var windDir = windArr[Math.floor(((data.wind.deg/22.5)+.5))];
$('#currentLocation').append(data.name);
$('#high').append(" " + high.f);
$('#low').append(" " + low.f);
$('#currentTemp').html(temp.f);
$('#weatherDesc').html(data.weather[0].description);
$('#windDir').html(windDir);
$('#windDir').append('<span id="windSpd">' + windSpd.f + '</span>');
icon = data.weather[0].icon;
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').html('<img id="weatherImg" src="' + iconSrc + '"><br>');
}
});
}
$('#currentTemp').on('click', function() {
var current = $(this).data('nexttemp');
$('#currentTemp').text(temp[current]);
$('#high').html(high[current]);
$('#low').html(low[current]);
$('#windSpd').html(windSpd[current]);
if (current == 'c') {
$(this).data('nexttemp', 'f');
return;
}
$(this).data('nexttemp', 'c');
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"></div>
<div class="navbar"><h4>Free Code Camp Weather App</h4></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<div class="col-lg-4" id="map"></div>
<div class="col-lg-4">
<h1 id="currentLocation">Your Current Location is </h1>
</div>
<h2 class="center-text content-title" id="currentTemp"></h2>
<h3 id="caption">Click temperature to change Units</h3>
<div class="center-text">
<p class="oneLine" id="labels">High: <span id="high"></span></p>
<p class="oneLine" id="labels">Low: <span id="low"></span></p>
</div>
<p class="center-text" id="currentConditions"></p>
<p class="center-text" id="weatherDesc"></p>
<div class="windCompass col-lg-4">
<div class="compass">
<div class="direction">
<p id="windDir"></p>
</div>
<div class="arrow ne"></div>
</div>
</div>
</div>
</body>
</html>
CSS:
#import url(http://fonts.googleapis.com/css?family=Dosis:200,400,500,600);
body {
background: url(http://eskipaper.com/images/pixel-backgrounds-1.jpg);
background-size: auto;
background-repeat: no-repeat;
font-family: Ranga, cursive;
}
h4 {
margin-top: 7px;
}
h1 {
margin-left: -7px;
font-size: 1.05em;
color: white;
}
#header {
background: #2980b9;
color: white;
padding: 0 5px;
display: inline-block;
width: 100%;
margin: 0;
box-shadow: 0 2px 5px #555555;
}
#header .left {
display: inline-block;
width: auto;
float: left;
margin-top: 7px;
margin-left: 7px;
}
#header .navbar {
display: inline-block;
width: 60%;
}
#header .right {
display: inline-block;
width: auto;
text-align: right;
float: right;
margin-top: 2px;
margin-right: 7px;
vertical-align: bottom;
}
.bigger_icon {
margin-top: 10px;
font-size: 2em;
color: white;
}
#map {
height: 200px;
width: 200px;
border-radius: 5%;
margin-top: 20px;
}
#container {
background: rgba(66, 66, 66, 0.6);
display: block;
position: relative;
width: 40%;
margin: 24px auto;
min-height: 300px;
padding: 16px;
border-radius: 4px;
}
#container .center-text {
text-align: center;
}
h2 {
color: white;
font-family: Ranga, cursive;
font-size: 2.5em;
font-weight: bold;
margin-top: -230px;
}
#caption {
font-size: 17px;
text-align: center;
color: pink;
}
#labels {
color: darkGrey;
font-size: 1.5em;
}
.oneLine {
color: darkGrey;
font-size: 1.5em;
text-align: center;
display: inline;
padding: 5px;
}
#high {
text-align: center;
color: orange;
}
#low {
text-align: center;
color: blue;
}
#currentConditions {
text-align: center;
color: black;
}
#weatherDesc {
margin-top: -25px;
color: white;
}
.windCompass {
margin-left: 75%;
margin-top: -20%;
}
.compass {
display: block;
width: 120px;
height: 120px;
border-radius: 100%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.85);
position: relative;
font-family: 'Dosis';
color: #555;
text-shadow: 1px 1px 1px white;
}
.compass:before {
font-weight: bold;
position: absolute;
text-align: center;
width: 100%;
content: "N";
font-size: 14px;
top: -2px;
}
.compass .direction {
height: 100%;
width: 100%;
display: block;
background: #f2f6f5;
background: -moz-linear-gradient(top, #f2f6f5 30%, #cbd5d6 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f5), color-stop(100%, #cbd5d6));
background: -webkit-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
background: o-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
border-radius: 100%;
}
.compass .direction p {
text-align: center;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 100%;
line-height: 80px;
display: block;
margin-top: -35%;
font-size: 28px;
font-weight: bold;
}
.compass .direction p span {
display: block;
line-height: normal;
margin-top: -10%;
font-size: 17px;
text-transform: uppercase;
font-weight: normal;
font-family: Ranga, cursive;
}
.compass .arrow {
width: 100%;
height: 100%;
display: block;
position: absolute;
top: 0;
}
.compass .arrow:after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid red;
position: absolute;
top: -6px;
left: 50%;
margin-left: -5px;
z-index: 99;
}
.compass .arrow.nne {
transform: rotate(22.5deg);
}
.compass .arrow.ne {
transform: rotate(45deg);
}
.compass .arrow.ene {
transform: rotate(67.5deg);
}
.compass .arrow.e {
transform: rotate(90deg);
}
.compass .arrow.ese {
transform: rotate(112.5deg);
}
.compass .arrow.se {
transform: rotate(135deg);
}
.compass .arrow.sse {
transform: rotate(157.5deg);
}
.compass .arrow.s {
transform: rotate(180deg);
}
.compass .arrow.ssw {
transform: rotate(202.5deg);
}
.compass .arrow.sw {
transform: rotate(-135deg);
}
.compass .arrow.wsw {
transform: rotate(-114.5deg);
}
.compass .arrow.w {
transform: rotate(-90deg);
}
.compass .arrow.wnw {
transform: rotate(-69.5deg);
}
.compass .arrow.nw {
transform: rotate(-45deg);
}
.compass .arrow.nnw {
transform: rotate(-24.5deg);
}
I ended up finding some Ajax and working with it to do what I expected the button to do. While not a button, it does what is intended. I also worked in changing the high, low, and wind speed to also change with the unit change.
I appreciate the help that everyone offered.
feel free to offer suggestions on the code as well for fixing the css for the compass gradient and making the stupid thing more responsive if you'd like. (The Map is not doing the responsive thing.
Your script probably gets loaded before the DOM is ready.
What you want to do here is one of a few options:
1. Load the JS script tag at the end of the body.
2. Wrap your $('.btn').on(...) function with document.on('ready') event, so this code will only be triggered when the DOM is ready.
Hello I'm stuck on how to add category for my to do list. When you click on Button of category need change class name. I don't understand how to correctly write if/else statement when button is clicked.
plan how it need to work
Write task name
Choose Category
Add new task
May be somebody can help me out ore give some advice how to solve this problem!
Sorry for my english and if my question is to badly explained!
var toDoList = function() {
var addNewTask = function() {
var input = document.getElementById("taks-input").value,
itemTexts = input,
colA = document.getElementById('task-col-a').children.length,
colB = document.getElementById('task-col-b').children.length,
taskBoks = document.createElement("div"),
work = document.getElementById("work"),
Category = "color-2",
taskCount = 1;
if (work.onclick === true) {
var Category = "color";
}
taskBoks.className = "min-box";
taskBoks.innerHTML = '<div class="col-3 chack" id="task_' + (taskCount++) + '"><i class="fa fa-star"></i></div><div class="col-8 task-text" id="taskContent"><p>' + itemTexts + '</p><span id="time-now"></span></div><div class="col-1 ' + (Category) + '"></div>'
if (colB < colA) {
var todolist = document.getElementById("task-col-b");
} else {
var todolist = document.getElementById("task-col-a");
}
//todolist.appendChild(taskBoks);
todolist.insertBefore(taskBoks, todolist.childNodes[0]);
},
addButton = function() {
var btn2 = document.getElementById("add-task-box");
btn2.onclick = addNewTask;
};
addButton()
}
toDoList();
p {
padding: 20px 20px 20px 45px;
}
.chack {
background-color: #4c4b62;
height: 100%;
width: 40px;
}
.task-text {
background-color: #55566e;
height: 100%;
width: 255px;
}
.color {
width: 5px;
height: 100%;
background-color: #fdcd63;
float: right;
}
.color-2 {
width: 5px;
height: 100%;
background-color: red;
float: right;
}
.color-3 {
width: 5px;
height: 100%;
background-color: purple;
float: right;
}
.task {
height: 100px;
width: 300px;
border: 1px solid #fff;
float: left;
}
.chack,
.task-text {
float: left;
}
.add-new-task {
margin-bottom: 50px;
height: 80px;
width: 588px;
background-color: rgb(85, 86, 110);
padding-top: 30px;
padding-left: 15px;
}
.min-box {
height: 100px;
border-bottom: 1px solid #fff;
}
.center {
padding-top: 20px;
padding-left: 50px;
}
.fa-star {
padding-left: 14px;
padding-top: 100%;
}
#add-task-box {
float: right;
margin-right: 10px;
margin-top: -7px;
border: none;
background-color: rgb(255, 198, 94);
padding: 10px;
}
#taks-input {
height: 30px;
width: 350px;
margin-top: -7px;
}
.category {
margin-top: 10px;
}
<div class="container">
<div class="add-new-task">
<input type="text" id="taks-input">
<button id="add-task-box">Add New Task box</button>
<div class="category">
<button class="catBtn" id="work">Work</button>
<button class="catBtn" id="home">Home</button>
<button class="catBtn" id="other">Other</button>
</div>
</div>
<div class="lg-task" id="bigTask"></div>
<div class="task" id="task-col-a"></div>
<div class="task" id="task-col-b"></div>
</div>
you need to bind click event to your buttons and store that value in Category, so in you js add this
var toDoList = function() {
// set to default
var Category = "color-3";
// attach event to buttons
var catButtons = document.getElementsByClassName("catBtn");
// assign value based on event
var myCatEventFunc = function() {
var attribute = this.getAttribute("id");
if (attribute === 'work') {
Category = 'color';
} else if (attribute === 'home') {
Category = 'color-2';
}
};
for (var i = 0; i < catButtons.length; i++) {
catButtons[i].addEventListener('click', myCatEventFunc, false);
}
Demo: Fiddle
and remove this code from addNewTask function
if (work.onclick === true) {
var Category = "color";
}
It is a bit hard to understand what you are doing, what you are going for (a module of some kind?). You were not that far away from a working state.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Task</title>
<style>
p {
padding: 20px 20px 20px 45px;
}
.chack {
background-color: #4c4b62;
height: 100%;
width: 40px;
}
.task-text {
background-color: #55566e;
height: 100%;
width: 255px;
}
.color {
width: 5px;
height: 100%;
background-color: #fdcd63;
float: right;
}
.color-2 {
width: 5px;
height: 100%;
background-color: red;
float: right;
}
.color-3 {
width: 5px;
height: 100%;
background-color: purple;
float: right;
}
.task {
height: 100px;
width: 300px;
border: 1px solid #fff;
float: left;
}
.chack,
.task-text {
float: left;
}
.add-new-task {
margin-bottom: 50px;
height: 80px;
width: 588px;
background-color: rgb(85, 86, 110);
padding-top: 30px;
padding-left: 15px;
}
.min-box {
height: 100px;
border-bottom: 1px solid #fff;
}
.center {
padding-top: 20px;
padding-left: 50px;
}
.fa-star {
padding-left: 14px;
padding-top: 100%;
}
#add-task-box {
float: right;
margin-right: 10px;
margin-top: -7px;
border: none;
background-color: rgb(255, 198, 94);
padding: 10px;
}
#taks-input {
height: 30px;
width: 350px;
margin-top: -7px;
}
.category {
margin-top: 10px;
}
</style>
<script>
var toDoList = function() {
var addNewTask = function() {
var input = document.getElementById("taks-input").value,
itemTexts = input,
colA = document.getElementById('task-col-a').children.length,
colB = document.getElementById('task-col-b').children.length,
taskBoks = document.createElement("div"),
work = document.getElementById("work"),
Category = "color-2",
taskCount = 1;
if (work.onclick === true) {
Category = "color";
}
taskBoks.className = "min-box";
taskBoks.innerHTML = '<div class="col-3 chack" id="task_'
+ (taskCount++) +
'"><i class="fa fa-star"></i></div><div class="col-8 task-text" id="taskContent"><p>'
+ itemTexts +
'</p><span id="time-now"></span></div><div class="col-1 '
+ (Category) + '"></div>'
if (colB < colA) {
var todolist = document.getElementById("task-col-b");
} else {
var todolist = document.getElementById("task-col-a");
}
//todolist.appendChild(taskBoks);
todolist.insertBefore(taskBoks, todolist.childNodes[0]);
},
// I don't know what to do with that?
addButton = function() {
var btn2 = document.getElementById("add-task-box");
btn2.onclick = addNewTask();
};
// return the stuff you want to have public
return {
addNewTask:addNewTask
};
}
var f;
// wait until all HTML is loaded and put the stuff from above into the variable `f`
// you can call it with f.someFunction() in your case f.addNewTask()
window.onload = function(){
f = toDoList();
}
</script>
</head>
<body>
<div class="container">
<div class="add-new-task">
<input type="text" id="taks-input">
<button id="add-task-box" onclick="f.addNewTask()">Add New Task box</button>
<div class="category">
<button class="catBtn" id="work" >Work</button>
<button class="catBtn" id="home">Home</button>
<button class="catBtn" id="other">Other</button>
</div>
</div>
<div class="lg-task" id="bigTask"></div>
<div class="task" id="task-col-a"></div>
<div class="task" id="task-col-b"></div>
</div>
</body>
</html
I hope you understood what I did?
I am making a game so I stared at it for awhile (and yes, I did look at the developer log console for errors), and found no errors (within my reasoning) of why it wouldn't open a battle function.
It is saying that for whatever reason that Giant is not defined when clicked, Zombie is not defined when clicked, and for Giant Spider it says something along the lines of missing parameter. I am quite sure it falls down to the code below -->
for(var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
}
If you wish to look at all the code look below. And if you're wondering why everything is so small it's because I'm making it on my phone, and transferred it to ask via GitHub.
var monsters = []; //All monsters are stored here
//All types of monsters are listed below
monsters.push(new monster_prototype("Giant", 50, 30, 1, 20, 20));
monsters.push(new monster_prototype("Giant spider", 20, 50, 1, 15, 30));
monsters.push(new monster_prototype("Zombie", 50, 50, 2, 40, 70));
for (var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
} //Where I believe the error occurs, it basically loads all monster stats into a div
function Gid(id) {
return document.getElementById(id);
} //So I don't have to write the whole document.getElementById
function monster_prototype(name, hp, dmg, lvl, xp, money) {
this.name = name;
this.hp = hp;
this.dmg = dmg;
this.lvl = lvl;
this.xp = xp,
this.money = money;
} //How I store the monsters info
function save() {
localStorage.player = JSON.stringify(playerStats);
}
var playerStats = {
lvl: 1,
xp: 0,
xpToLvl: 100,
name: null,
dmg: null,
hp: null,
money: 100
};
if (localStorage.player === undefined) {
save();
playerSetup();
} else {
playerStats = JSON.parse(localStorage.player);
alert("Welcome back " + playerStats.name);
refreshStats();
} //Checks if the player is new, and if so starts the main player setup. If not it loads it
function refreshStats() {
Gid("maxDmg").innerHTML = "Max damage: " + playerStats.dmg;
Gid("hp").innerHTML = "Health: " + playerStats.hp;
} //Refreshes some stats
function playerSetup() {
document.getElementById("mainContainer").style.display = "none";
$("#class_container").show();
}
function classChosen(pClass) {
if (pClass === "Juggernaut") {
playerStats.hp = 100;
playerStats.dmg = 10;
} else if (pClass === "Average Joe") {
playerStats.hp = 60;
playerStats.dmg = 30;
} else {
playerStats.hp = 40;
playerStats.dmg = 70;
}
refreshStats();
document.getElementById("class_container").style.display = "none";
var getName = prompt("What is your name?");
playerStats.name = getName;
document.getElementById("mainContainer").style.display = "block";
save();
} //Starts the class choosing feature
function toggle(id) {
$("#" + id).toggle();
} //Toggles display (Hidden or block)
function restartGame() {
localStorage.removeItem('player');
location.reload();
}
function battle(enemy, enemyLoc) {
console.log(enemy + " and " + enemyLoc);
enemy = enemy.toLowerCase();
Gid("attackInfo").innerHTML = "";
var battleWords = ['slashed', 'bashed', 'stabbed', 'punched'];
var enemyHp = monsters[enemyLoc].hp;
var enemyDmg = monsters[enemyLoc].dmg;
var playerHp = playerStats.hp;
var playerDmg = playerStats.dmg;
var battleLoop = setInterval(function() {
var atkName1 = Math.floor(Math.random() * battleWords.length);
var atkName2 = Math.floor(Math.random() * battleWords.length);
var enemyDealt = Math.round(Math.random() * enemyDmg);
var playerDealt = Math.round(Math.random() * enemyDmg);
playerHp -= enemyDealt;
enemyHp -= playerDealt;
Gid("attackInfo").innerHTML += ("<strong>•</strong>" + enemy + " " + battleWords[atkName1] + " you and dealt " + enemyDealt + " damage to you and you now have " + playerHp + " health remaining.<br>You " + battleWords[atkName2] + " the " + enemy + " and dealt " + playerDealt + " damage. The " + enemy + " has " + enemyHp + " health remaining.<br><br>");
if (enemyHp <= 0 && playerHp <= 0) {
clearInterval(battleLoop);
alert("You both died at the same time! A win... but mainly a loss. Game over");
restartGame();
} else if (enemyHp <= 0) {
clearInterval(battleLoop);
alert("You won!");
playerStats.money += monsters[enemyLoc].money;
playerStats.xp += monsters[enemyLoc].xp;
if (playerStats.xp >= playerStats.xpToLvl) levelUp();
} else if (playerHp <= 0) {
alert("Game over");
clearInterval(battleLoop);
restartGame();
}
}, 1000);
} //Main battle, this is the function that won't load
function levelUp() {
} //TBA
#container {
background-color: gray;
width: 300px;
height: 350px;
margin: auto;
}
#atkOpt_container {
display: none;
}
#attackBtn {
background-color: black;
width: 96px;
color: yellow;
border: 4px groove red;
float: left;
font-size: 30px;
text-align: center;
display: block;
margin-top: 5px;
margin-left: 5px;
}
#attackInfo {
float: left;
background-color: #eee;
width: 200px;
font-size: 10px;
height: 250px;
clear: left;
display: block;
margin-top: 5px;
margin-left: 5px;
border: 2px solid red;
}
#class_container {
z-index: 10;
display: none;
width: 300px;
height: 150px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: orange;
overflow: auto;
border: 5px groove black;
}
.playerClass {
margin: auto;
width: 200px;
border: 5px groove red;
color: #00FF00;
font-size: 35px;
text-align: center;
margin-bottom: 5px;
display: block;
background-color: black;
}
#title {
width: 95%;
background-color: black;
color: #00FF00;
border: 1px solid orange;
font-size: 25px;
font-weight: bolder;
text-align: center;
margin: auto;
}
#atkOpt_container {
z-index: 11;
width: 275px;
height: 300px;
overflow: auto;
background-color: black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border: 2px solid orange;
}
.monsterContainer {
width: 200px;
margin: auto;
text-align: center;
background-color: orange;
border: 5px groove red;
margin-bottom: 5px;
}
.monsterT {
width: 100%;
background-color: black;
color: #eee;
font-size: 30px;
text-align: center;
}
td {
background-color: Cyan;
font-size: 15px;
width: 49%;
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="class_container">
<div id="title">Choose a class</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Juggernaut</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Masculine Mat</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Average Joe</div>
</div>
<div id="mainContainer">
<div id="container">
<div id="attackBtn" onclick="toggle('atkOpt_container'); toggle('mainContainer');">Attack</div>
<div id="attackInfo"></div>
<div id="maxDmg">Max damage: 0</div>
<div id="hp">Health: 0</div>
</div>
<button onclick="restartGame();">Delete stats</button>
</div>
<div id="atkOpt_container"></div>
</body>
</html>
Because
"<div onclick='battle(" + monsters[z].name + "," + this.value + ")'
produces
<div onclick='battle(whatever, whatever)'
Which is wrong, because you do not have quotes around the strings. You need to quote them. So add in the "
"<div onclick='battle(\"" + monsters[z].name + "\",\"" + this.value + "\")'
Ideally you would use DOM methods such as createElement and addEventListener so you would not have to deal with this.