I want to perform "Flip card" effect on div elemenets (card). To to that I am using code below (i applied onclick event but I didn't iclude it here). Does someone knows where is the problem ? I want to flip "Card" Div element. To to that I am using "OpenCard()" JavaScript function that I included below.
EDIT 1: Added jsFiddle
http://jsfiddle.net/9CvYd/1/
JavaScript:
function OpenCard() {
var id = $(this).attr("id");
if ($("#" + id + " img").is(":hidden")) {
var img = document.querySelector("#" + id + " img");
img.classList.toggle("flip");
if (ImgOpened == "") {
BoxOpened = id;
ImgOpened = $("#" + id + " img").attr("src");
setTimeout(function() {
$(Source + " div").bind("click", OpenCard)
}, 300);
} else {
CurrentOpened = $("#" + id + " img").attr("src");
if (ImgOpened != CurrentOpened) {
setTimeout(function() {
document.querySelector("#" + id + " img").classList.toggle("flip");
document.querySelector("#" + BoxOpened + " img").classList.toggle("flip");
BoxOpened = "";
ImgOpened = "";
}, 400);
Counter-=10;
wrong.play();
} else {
$("#" + id + " img").parent().css("disabled", "disabled");
$("#" + BoxOpened + " img").parent().css("disabled", "disabled");
ImgFound++;
BoxOpened = "";
ImgOpened = "";
Counter+=100;
correct.play();
}
setTimeout(function() {
$(Source + " div").bind("click", OpenCard)
}, 400);
}
$("#counter").html("" + Counter);
if (ImgFound == ImgSource.length) {
clearInterval(timer);
alert ("Game over! You result is: "+Counter);
}
}
}
CSS:
#picbox {
margin: 0px auto;
width: auto;
}
#boxcard {
z-index: 1;
display: table;
margin: 0px auto;
width: auto;
}
#boxcard div{
float: left;
width: 100;
height: 120;
margin: 5px;
padding: 5px;
border: 4px solid #EE872A;
cursor: pointer;
border-radius: 10px;
box-shadow: 0 1px 5px rgba(0,0,0,.5);
background: #B1B1B1;
z-index: 2;
}
#boxcard > div:nth-child(6n+1) {
clear: both;
}
#boxcard div img {
/*display: none;*/
border-radius: 10px;
z-index: 3;
}
#boxcard div img.flip{
transform: rotateY(180deg);
display:inline-block;
}
HTML:
<div id="boxcard" align="center">
<div id="card10" style="visibility: visible;"><img src="http://img6.uploadhouse.com/fileuploads/17699/17699263b01721074bf094aa3bc695aa19c8d573.png" class=""></div>
<div id="card11" style="visibility: visible;"><img src="http://img9.uploadhouse.com/fileuploads/17699/176992615db99bb0fd652a2e6041388b2839a634.png" class=""></div>
<div id="card12" style="visibility: visible;"><img src="http://icons.iconarchive.com/icons/reclusekc/kulo/96/Skull-1-icon.png"></div>
The problem is your if statement condition is not matching.
Click a card here: http://jsfiddle.net/YffE5/1/
if ($("#" + id + " img").is(":hidden")) // Image is visible, thus code inside this will not execute.
Related
I am trying to implement CSGO like case opener code on my website.
Code can be found here:
https://codepen.io/killerek/pen/ObBOJE
I am trying to make it responsive on all screens (full width and centered), but when I resize the window or open it on a mobile device, the red arrow is not in the center. After changing the CSS of the arrow-down class to margin-left:50%; and after centering the cardList class with full screen width: "width: 100%; margin: auto;" 2 problems arise:
After resizing the window, the red arrow is always centered (correct behaviour) but the items in the cardList are not moving (even if the arrow would be pointing at the won item, the arrow is moving, but not the item)
Now the arrow is not pointing at the right item, it has something to do with this code:
$('.card').first().animate({ marginLeft: -rand }, 5000, timing,
function(){ ... }
The spin is animated based on the generated random reward, but I dont know what value to put there in order for it to work.. I am guessing the marginLeft should be changed in % values instead.
I would like to ask for help in this matter.
Relevant CSS code:
#cardList {
height: 100px;
width: 800px;
position: relative;
overflow: hidden;
white-space: nowrap;
}
.card {
display: inline-block;
text-align: center;
width: 100px;
height: 100px;
}
.arrow-down {
margin-left: 380px;
width: 0;
height: 0;
}
Relevant JS code:
var rand = random(1000,20000);
var childNumber = Math.floor(rand/100)+4;
var timings = ["easeInOutBack","easeOutExpo","easeInOutBounce","easeOutQuad","swing","easeOutElastic","easeInOutElastic"];
var timing = timings[random(0,timings.length)];
var reward = $('#itemNumber'+childNumber).attr('data-rarity');
$('.card').first().animate({
marginLeft: -rand
}, 5000, timing, function(){ ... }
EDIT:
I think I´ve gotten closer with the following change in the JavaScript, the cards are now more responsive, but the won item still leaves the arrow.
var mywidth = (rand*100) / screen.width;
$('.card').first().animate({
marginLeft: -mywidth+"%"
}, 5000, timing, function(){ ... }
EDIT 2:
Current state of the codepen code
https://codepen.io/chris-fodor/pen/GRxjpYO
I've restructured the styling little bit, try this one.
var img = {
blue: '<img src="https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopujwezhhwszYI2gS09-5mpSEguXLPr7Vn35c18lwmO7Eu9TwjVbs8xVqZm_3J4TGcVU3YFCE-Ae5weq81JXovJXLyiRjvyFw4nfD30vgN-NX6nY/360fx360f"/>',
purple: '<img src="http://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLZTjlH7du6kb-FlvD1DLfYkWNF18lwmO7Eu46h2QS1r0tvZjvyLI-RIwI6aV7X_ADrwevmhZO0up_AwSM1uHNw5nzD30vgQ0tV-jw/360fx360f"/>',
pink: '<img src="https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLZTjlH_9mkgIWKkPvxDLDEm2JS4Mp1mOjG-oLKhF2zowcDPzixc9OLcw82ZlyF8wC8wb251MW4tcifmydi7CEn4HiPlhyy1BxJbeNshqPIHELeWfJvK5CfiA/360fx360f"/>',
red: '<img src="https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5gZKKkPLLMrfFqWZU7Mxkh9bN9J7yjRrhrUFuazjzJteVJlQ6NVHTrFe3wObs15G06picwHFnvid25C3bnhSzn1gSOQz0szG-/360fx360f"/>',
yellow: '<img src="http://vignette4.wikia.nocookie.net/cswikia/images/a/ad/Csgo-default_rare_item.png/revision/latest?cb=20150227163025"/>'
}
function reset() {
$('.card').remove();
for (var i = 0; i < 210; i++) {
var element = '<div class="card" style="background-color: lightblue;" data-rarity="blue" id=itemNumber' + i + '>' + img.blue + '</div>';
var rand = random(1, 10000) / 100;
if (rand < 20) {
element = '<div class="card" style="background-color: purple;" data-rarity="purple" id=itemNumber' + i + '>' + img.purple + '</div>';
}
if (rand < 5) {
element = '<div class="card" style="background-color: hotpink;" data-rarity="pink" id=itemNumber' + i + '>' + img.pink + '</div>';
}
if (rand < 2) {
element = '<div class="card" style="background-color: red;" data-rarity="red" id=itemNumber' + i + '>' + img.red + '</div>';
}
if (rand < 0.5) {
element = '<div class="card" style="background-color: yellow;" data-rarity="yellow" id=itemNumber' + i + '>' + img.yellow + '</div>';
}
$('#cardList').append(element);
}
$('.card').first().css('margin-left', -1000);
}
function openCase() {
reset();
var rand = random(1000, 20000);
var childNumber = Math.floor(rand / 100) + 4;
var timings = ["easeInOutBack", "easeOutExpo", "easeInOutBounce", "easeOutQuad", "swing", "easeOutElastic", "easeInOutElastic"];
var timing = timings[random(0, timings.length)];
var reward = $('#itemNumber' + childNumber).attr('data-rarity');
var mywidth = (rand * 100) / screen.width;
$('.card').first().animate({
marginLeft: -mywidth + "%"
}, 5000, timing, function() {
var src = $('#itemNumber' + childNumber + ' img').attr('src');
$('#itemNumber' + childNumber).css({
background: "linear-gradient(#00bf09, #246b27)"
});
$('#dialog-msg').html("You have received " + reward + " item!" + "<br><img src=" + src + ">");
$('#dialog').dialog({
modal: true,
title: "New item!",
resizeable: false,
draggable: false,
width: 400,
buttons: {
"Receive item": function() {
$(this).dialog("close");
// add resources
}
}
});
});
//$('.card').css({backgroundColor: 'red'})
//$('.card:nth-child('+(childNumber+1)+')').css({backgroundColor: 'green'})
}
function random(min, max) {
return Math.floor((Math.random() * (max - min)) + min);
}
* {
box-sizing: border-box;
}
#cardList {
height: 100px;
width: 800px;
position: relative;
border: 2px solid black;
overflow: hidden;
white-space: nowrap;
}
.card {
display: inline-block;
background-color: red;
text-align: center;
border-left: 1px solid black;
border-right: 1px solid black;
width: 100px;
height: 100px;
}
.card>img {
width: 100px;
height: 100px;
}
.arrow-down {
margin-left: 380px;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #f00;
}
#dialog-msg>img {
width: 150px;
height: 150px;
}
#dialog-msg {
text-align: center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div id=unbox-area>
<div class="arrow-down"></div>
<div id=cardList></div>
</div>
<button onclick="openCase();">Open</button>
<div id=dialog>
<div id=dialog-msg></div>
</div>
</body>
</html>
this is my code:
jQuery(document).on('change', 'input[type=color]', function(picker) {
var color_chng = jQuery(this).closest('.input-group').attr('id');
jQuery('.card-txt[id=p' + color_chng + ']').css('color', picker.currentTarget.value);
});
jQuery(document).ready(function() {
var img_url = jQuery("#pro-image").attr('src');
jQuery(".edit-image").css('background', 'url(' + img_url + ')');
jQuery(".hide-img").attr('src', img_url);
jQuery(".edit-btn").find(".elementor-button-link").click(function() {
jQuery(".edit-box").show();
});
//input keyup
jQuery(document).on('keydown, keyup', '.input-group input[type="text"]', function() {
var texInputValue = jQuery(this).val();
var input_id = jQuery(this).parent().attr('id');
jQuery('.edit-image span[id=p' + input_id + ']').html(texInputValue);
});
// Draggable
(function(jQuery) {
jQuery.fn.drags = function(opt) {
opt = jQuery.extend({
handle: "",
cursor: "move"
}, opt);
if (opt.handle === "") {
var jQueryel = this;
} else {
var jQueryel = this.find(opt.handle);
}
return jQueryel.css('cursor', opt.cursor).on("mousedown", function(e) {
if (opt.handle === "") {
var jQuerydrag = jQuery(this).addClass('draggable');
} else {
var jQuerydrag = jQuery(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = jQuerydrag.css('z-index'),
drg_h = jQuerydrag.outerHeight(),
drg_w = jQuerydrag.outerWidth(),
pos_y = jQuerydrag.offset().top + drg_h - e.pageY,
pos_x = jQuerydrag.offset().left + drg_w - e.pageX;
jQuerydrag.css('z-index', 1000).parents().on("mousemove", function(e) {
jQuery('.draggable').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup", function() {
jQuery(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup", function() {
if (opt.handle === "") {
jQuery(this).removeClass('draggable');
} else {
jQuery(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
jQuery('.draggble').drags();
// Duplicate
var buttonAdd = jQuery(".addtxt");
var buttonRemove = jQuery(".removetxt");
var className = ".input-group";
var className2 = ".card-txt";
var count = 0;
var field = "";
var field2 = "";
var maxFields = 5;
function totalFields() {
return jQuery(className).length;
}
function addNewField() {
count = totalFields() + 1;
field2 = jQuery("#ptxtgrp1").clone();
field2.attr("id", "ptxtgrp" + count);
field2.html("");
field2.attr('style', '');
jQuery(field2).drags();
field = jQuery("#txtgrp1").clone();
field.attr("id", "txtgrp" + count);
field.find("input").val("");
jQuery(className + ":last").after(jQuery(field));
jQuery(className2 + ":last").after(jQuery(field2));
count++;
}
function removeLastField() {
if (totalFields() > 1) {
jQuery(className + ":last").remove();
jQuery(className2 + ":last").remove();
}
}
function enableButtonRemove() {
if (totalFields() === 2) {
buttonRemove.removeAttr("disabled");
buttonRemove.addClass("shadow-sm");
}
}
function disableButtonRemove() {
if (totalFields() === 1) {
buttonRemove.attr("disabled", "disabled");
buttonRemove.removeClass("shadow-sm");
}
}
function disableButtonAdd() {
if (totalFields() === maxFields) {
buttonAdd.attr("disabled", "disabled");
buttonAdd.removeClass("shadow-sm");
}
}
function enableButtonAdd() {
if (totalFields() === (maxFields - 1)) {
buttonAdd.removeAttr("disabled");
buttonAdd.addClass("shadow-sm");
}
}
buttonAdd.on("click", function() {
addNewField();
enableButtonRemove();
disableButtonAdd();
});
buttonRemove.on("click", function() {
removeLastField();
disableButtonRemove();
enableButtonAdd();
});
// Hide Show Texts
jQuery(document).on('click', '.show', function() {
var txt_id = jQuery(this).parent().attr('id');
jQuery(".card-txt[id=p" + txt_id + "]").toggle();
jQuery(this).toggleClass("hide");
});
// Font Size Change
jQuery(".input-group").each(function() {
jQuery(document).on('click', '.font-up', function() {
var ftxt_id = jQuery(this).parent().attr('id');
var size = jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size");
size = parseInt(size, 10);
if ((size + 2) <= 70) {
jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size", "+=2");
}
});
jQuery(document).on('click', '.font-down', function() {
var ftxt_id = jQuery(this).parent().attr('id');
var size = jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size");
size = parseInt(size, 10);
if ((size - 2) >= 12) {
jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size", "-=2");
}
});
});
});
.edit-box {
width: 600px;height:300px;
margin: 0 auto;
display: block;
border: 2px solid #dddddd;
border-radius: 10px;
background: #eee;
}
body {
height: 3000px;
}
/***************************/
.edit-image {
background-size: cover;
width: max-content;
display: block;
background: red;
margin: 40px auto;
position: relative;width:200px;height:200px;backgrounf:red;
}
.edit-contents {
width: 80%;
display: block;
margin: 20px auto;
background: #fff;
padding: 20px;
}
.card-txt {
position: absolute;
top: 50%;
left: 50%;
}
.show,
.font-up,
.font-down {
background: green;
width: 20px;
height: 20px;
display: inline-block;
color: #fff;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
}
.addtxt,
.removetxt {
margin: 10px;
display: inline;
}
.show.hide {
background: red;
}
[type='color'] {
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
padding: 0;
width: 15px;
height: 15px;
border: none;
}
[type='color']::-webkit-color-swatch-wrapper {
padding: 0;
}
[type='color']::-webkit-color-swatch {
border: none;
}
.color-picker {
padding: 10px 15px;
border-radius: 10px;
border: 1px solid #ccc;
background-color: #f8f9f9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="edit-box">
<div class="edit-image">
<img class="hide-img" src="" style="visibility: hidden;" />
<span class="card-txt draggble" id="ptxtgrp1"></span>
</div>
<div class="edit-contents">
<button type="button" class="addtxt">Add</button>
<button type="button" class="removetxt">remove</button>
<div class="input-group" id="txtgrp1">
<input class="inptxt" type="text">
<i class="show"></i>
<i class="font-up">+</i>
<i class="font-down">-</i>
<span class="color-picker">
<label for="colorPicker">
<input type="color" value="#1DB8CE" class="colorPicker" >
</label>
</span>
</div>
</div>
</div>
as you can see I need to add new texts dynamically to the "edit-image" box and I need users to change the size and color of added texts.
the first input box that already exists in DOM change color works fine
but when I add another input box by jquery codes the change color function doesn't work for it
I would be thankful if you can help me to find out the reason and resolve the issue
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.
In the below code, why aren't the values in the array appending to the div element but I am able to append it to the heading? I am storing semicolon separated values in a local storage, then splitting each item and appending it to the div.
<!DOCTYPE html>
<html>
<head>
<title>To do</title>
<style type="text/css">
html {
overflow-y: scroll;
}
body {
padding: 0px;
margin: 0px;
font-family: Verdana, Geneva, sans-serif
}
h2 {
color: black;
text-align: center
}
#omnibox {
margin-left: 400px;
height: 30px;
width: 500px;
font-size: 14px;
padding: 10px;
position: center;
}
#searchWrapper {
margin-left: 500px
}
/*#omnibox,#listWrapper{margin:20px;position:center}*/
.searchable {
color: white;
display: block;
padding: 10px;
font-size: 16px;
background: #4298E8;
width: 300px;
margin-bottom: 10px
}
.searchable:hover {
background-color: #E8C420;
}
.delete {
display: block;
float: right;
height: 20px;
width: 20px;
line-height: 20px;
border-radius: 10px;
background-color: black;
color: white;
text-align: center;
font-size: 1em;
transform: rotate(-45deg);
}
.delete:hover {
background-color: #D8FFF1;
color: red;
cursor: pointer;
}
.comments {
margin-left: -10px;
margin-top: 10px;
width: 310px;
display: inline-block
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
console.log('ready');
$(function() {
// body...
$('#omnibox').focus();
if (window.localStorage) {
localStorage.setItem(1,"how do;you do");
localStorage.setItem(2,"ok;got it");
myList();
function myList() {
var list = "";
console.log('Items in Local Storage = ' + localStorage.length);
document.querySelector('h2').innerHTML = "To do - " + localStorage.length;
for (var i = localStorage.length - 1; i >= 0; i--) {
var itemKey = localStorage.key(i);
var values = new Array();
values = localStorage.getItem(itemKey);
values = values.split(";");
console.log("Array - " + values + " Items - " + values.length);
list += "<div class='searchable' id='" + itemKey + "'><span class='note'>" + itemKey + " " + values[0] + " </span><input type='text' class='comments' placeholder='Comments.'><br/></div>";
var myComments = ""
for (var j = values.length - 1; j >= 0; j--) {
console.log("Element - " + values[j] + " parentNode is " + itemKey);
myComments += '<span>' + ' ' + values[j] + ' ' + '</span>';
};
//Why doesn't this work?
$("#itemKey").append(myComments);
//This works though.
$("h2").append(myComments);
}
$("#listWrapper").html(list);
}
var todo = document.querySelector('#omnibox');
$('#omnibox').keyup(function(e) {
document.querySelector('.errorMessage').innerHTML = "";
if (e.keyCode == 13) {
var todoVal = document.querySelector('#omnibox').value;
if (!todoVal.match(/\S/)) {
console.log('Empty value entered.');
document.querySelector('.errorMessage').innerHTML = "Enter something!";
return false;
} else {
console.log("Some value entered.");
$(this).trigger("enterKey");
var remember = new Array();
myNote = document.querySelector('#omnibox').value;
$('#omnibox').val("");
document.location.reload(true);
return true;
}
}
});
}
});
</script>
</head>
<body>
<h2></h2>
<div id='searchWrapper'>
<div id="listAddWrapper">
<div id="empty"></div>
</div>
<div id="listWrapper">
</div>
</div>
</body>
</html>
You can't use a selector to find an element before you've added it to the DOM. Even if you could, your selector is wrong — it should be "#" + itemKey. But that doesn't matter because it won't work anyway; the element it would match is still just part of that list string you're building.
Looking at your code, I think the best thing to do is to add the comments to the text while you're building it.
list += "<div class='searchable' id='" + itemKey + "'><span class='note'>" + itemKey + " " + values[0] + " </span><input type='text' class='comments' placeholder='Comments.'><br/>";
var myComments = ""
for (var j = values.length - 1; j >= 0; j--) {
console.log("Element - " + values[j] + " parentNode is " + itemKey);
myComments += '<span>' + ' ' + values[j] + ' ' + '</span>';
};
list += myComments + "</div>";
I am trying to make sticky table headers. Here is what I have so far as an example of what I need.
Here is the code I found from someone else.
function makeTableHeadersSticky(tableId) {
var thArr = $(tableId + " th");
var thWidthsArr = [];
$(tableId + " th").each(function(){
thWidthsArr.push($(this).css("width"));
});
var pos = $(tableId).offset();
var thTop = pos.top + "px";
var count = 0;
$(tableId + " tr:first-child > th").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
count = 0;
$(tableId + " tr:last-child > td").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
$(window).scroll(function(){
if($(window).scrollTop() > pos.top) {
$(tableId + " tr:first-child").css("position", "fixed");
$(tableId + " tr:first-child").css("top", "0px");
} else {
$(tableId + " tr:first-child").css("position", "relative");
$(tableId + " tr:first-child").css("top", thTop);
}
});
console.log(thTop);
}
makeTableHeadersSticky("#myTable");
Here you can see a DEMO of what I want to achieve JSFiddle
You could use CSS to fix the headline to the top and then give the container a margin at the top to stop it from overflowing:
http://jsfiddle.net/n9wac1x6/5/
header {
width: 100%;
background-color: #fff;
height: 50px;
position: fixed;
top:0;
left: 0;
}
h1 {
position: absolute;
left: 5px;
top 2px;
padding: 0;
margin: 0;
}
.container {
margin-top: 50px;
}