I have a div in it with an 8x8 div. I want to use jquery for practicing. How can i get which div in which row and column i clicked on? I tried to use event.pageX and event.pageY but it specifies the coordinate of the click and I would like to get the row and the column
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="script.js"></script>
<title></title>
</head>
<body>
<div id="gameArea"></div>
</body>
</html>
I have a css file too
body{
margin: 0;
padding: 20px;
}
.tile {
position: absolute;
background-color: rgb(115, 255, 50);
cursor: pointer;
}
.tile:hover {
background-color: darkgreen;
}
.disabled {
background-color: black;
border:1px solid black;
}
.enabled{
background-color: white;
border: 1px solid white;
}
#gameArea {
background-color: black;
position: relative;
padding: 0px;
border: 2px solid black;
}
And here's my js file with my code
const max_clicks = 3;
const table_sz = 8;
const tile_sz = 88;
const border_w = 4;
const margin_w = 2;
let game_area;
function createTile(row, col){
let tile;
if ((row + col) % 2 === 0){
tile = $('<div class = "tile disabled"></div>');
}
else{
tile = $('<div class = "tile enabled"></div>');
tile.attr('clicks', 0);
}
tile.css("margin", margin_w.toString() + "px");
tile.css("border-width", border_w.toString() + "px");
tile.attr('row', row);
tile.attr('col', col);
tile.css( {
top: row * (tile_sz + 2 * (border_w + margin_w) ),
left: col * (tile_sz + 2 * (border_w + margin_w) ),
height: tile_sz,
width: tile_sz,
} );
return tile;
}
function createTable(){
for (let row = 0; row < table_sz; ++row){
for (let col = 0; col < table_sz; ++col) {
let tile = createTile(row, col);
game_area.append(tile);
}
}
}
function createGameArea(){
game_area = $('#gameArea');
game_area.css( {
height: 800,
width: 800
} );
}
function selectTileAt(position){
return $(".tile[row=" + position[0].toString() + "][col=" + position[1].toString() + "]");
}
$(document).ready(function(){
createGameArea();
createTable();
} );
If you're adding custom data attributes (row and column), it best to do so using the standard data-* syntax. This is the general and valid way to add custom attribute to elements. Like this:
tile.attr("data-row", row);
tile.attr("data-col", col);
Then, inside the loop that creates the table, you can add a click event listener for each tile using jQuery's on event handler function. Inside that listener you can get the row and column of the tile that was clicked:
tile.on("click", function (evt) {
console.log('Clicked row: ', $(evt.target).attr("data-row"));
console.log('Clicked column: ', $(evt.target).attr("data-col"));
});
const max_clicks = 3;
const table_sz = 8;
const tile_sz = 88;
const border_w = 4;
const margin_w = 2;
let game_area;
function createTile(row, col) {
let tile;
if ((row + col) % 2 === 0) {
tile = $('<div class = "tile disabled"></div>');
} else {
tile = $('<div class = "tile enabled"></div>');
tile.attr("data-clicks", 0);
}
tile.css("margin", margin_w.toString() + "px");
tile.css("border-width", border_w.toString() + "px");
tile.attr("data-row", row);
tile.attr("data-col", col);
tile.css({
top: row * (tile_sz + 2 * (border_w + margin_w)),
left: col * (tile_sz + 2 * (border_w + margin_w)),
height: tile_sz,
width: tile_sz,
});
return tile;
}
function createTable() {
for (let row = 0; row < table_sz; ++row) {
for (let col = 0; col < table_sz; ++col) {
let tile = createTile(row, col);
tile.on("click", function (evt) {
console.log("Clicked row: ", $(evt.target).attr("data-row"));
console.log("Clicked column: ", $(evt.target).attr("data-col"));
});
game_area.append(tile);
}
}
}
function createGameArea() {
game_area = $("#gameArea");
game_area.css({
height: 800,
width: 800,
});
}
$(document).ready(function () {
createGameArea();
createTable();
});
body {
margin: 0;
padding: 20px;
}
.tile {
position: absolute;
background-color: rgb(115, 255, 50);
cursor: pointer;
}
.tile:hover {
background-color: darkgreen;
}
.disabled {
background-color: black;
border: 1px solid black;
}
.enabled {
background-color: white;
border: 1px solid white;
}
#gameArea {
background-color: black;
position: relative;
padding: 0px;
border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="gameArea"></div>
Related
I have a stormTrooper characters randomly placed around my circle called deathStar. I am trying to make my stormTroopers place in the location that my mouse clicks once they have already been clicked. But instead they are placing in random locations. I'm still having problems grasping the concept of getBoundingClientRect() and offset. I thought adding them together and subtracting from mouseClick would be the solution. I'm also open to any other advice for this project. The area I'm having problems with is the mouseDown event listener.
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = window.scrollX + deathStar.getBoundingClientRect().left; // top left X
const y1 = window.scrollY + deathStar.getBoundingClientRect().top; // top left Y
const x2 = window.scrollY + deathStar.getBoundingClientRect().right; // bottom right X
const y2 = window.scrollY + deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
var xposition = (e.clientX - stormTrooperChecker.getBoundingClientRect().left + stormTrooperChecker.offsetLeft);
var yposition = (e.clientY - stormTrooperChecker.getBoundingClientRect().top + stormTrooperChecker.offsetTop);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) > pTheoremC(radius) || pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!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>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>
The translate positioning is relative to the Death Star element's center, so I updated that.
translate does not affect offsetTop/Left, so your "in Death Star" logic was failing. I fixed that.
Also, you do not need to adjust for the scroll position (comes into effect only when scrolled). I fixed that.
Lastly, I had to put in some code in the handler to calculate the new midpoint of the Death Star element, as you only calculated it on initialization (it should be recalcuated on every use).
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
var xposition = (e.clientX - midPointX);
var yposition = (e.clientY - midPointY);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(yposition, xposition) > pTheoremC(radius) || pTheoremAB(yposition, xposition) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!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>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</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
Here is a beautiful Number Ticker. the whole day I was wondering and trying to modify the code to make it as I want but no success till now!
if you work with numbers with two or more digits then the code creates separate black squares to hold each digit ( run code snippet to have a look ), but I want only a single square as the container to hold multiple digit numbers. So if we have a two-digit number like 10 the Number Ticker should be something like this:
And the next move should look like :
I don't want those parallel animations that move two digits like this (Only the single animation is required not both):
Here is the code:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = 10;
let digits = [];
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
function setValue(number) {
let s = number.toString().split('').reverse().join('');
let l = s.length;
if (l > digits.length) {
generateDigits(l - digits.length);
}
for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}
}
function setDigit(digitIndex, number) {
digits[digitIndex].style.marginTop = '-' + number + 'em';
}
function generateDigits(amount) {
for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
counter.appendChild(d);
digits.unshift(d);
}
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Ticker</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="number-ticker.css">
</head>
<body>
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
<script src="number-ticker.js"></script>
</body>
</html>
Your css has this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
You need to change it to this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
padding: 0 0.075em;
text-align: center;
}
If you remove border-right: 1px solid #555 you will have it look like 1 box.
Also I added text-align: center to center the numbers.
Hope this solves your problem :)
I think the main issue in your code is the digits variable. It creates an array of HTML elements that holds two blocks.
Also, for this line:
let s = number.toString().split('').reverse().join('');
Why do you need to convert number to a string. You can just pass it as is. Once you add to a string using + it will be converted.
I made few changes to your code and commented out the non-relevant part. Please see below:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
// let currentValue = 10;
// let digits = [];
let currentValue = counter.getAttribute("data-value");
let digit = null;
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
setTimeout(function() {
setValue(10);
}, 8000);
function setValue(number) {
// let s = number.toString().split('').reverse().join('');
// let l = s.length;
/*if (l > digits.length) {
generateDigits(l - digits.length);
}*/
/*for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}*/
digit.style.marginTop = '-' + number + 'em';
}
/*function setDigit(digitIndex, number) {
console.log(number);
digits[digitIndex].style.marginTop = '-' + number + 'em';
}*/
function generateDigits(amount) {
// console.log("generat", amount);
// for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
digit = counter.appendChild(d);
// digits.unshift(d);
// }
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
text-align: center;
}
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
Your final JS could be like this:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = counter.getAttribute("data-value");
let d = defaultDigitNode.cloneNode(true);
let digit = counter.appendChild(d);
setValue(currentValue);
function setValue(number) {
digit.style.marginTop = '-' + number + 'em';
}
});
This question already has answers here:
How to add a background image on top of a previous background image?
(1 answer)
Can I have multiple background images using CSS?
(8 answers)
Why does z-index not work?
(10 answers)
Closed 3 years ago.
I want to set a z-index to a background img.
I want the .player background to be always displayed, even when in the same box I have another class with another background.
If you click the right button you'll see that at the the .player goes to the blue box another class will be added. The .player background must be always displayed.
Why z-index is not working? is there any alternative?
Thank you
let moveCounter = 0;
let playerOne = {
currentWeapon: "w1"
}
var grid = document.getElementById("grid-box");
for (var i = 0; i <= 8; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
$("#square" + 0).addClass("player")
$("#square" + 3).addClass("w3")
function getWeapon(ele) {
let classList = $(ele).attr("class").split(' ');
for (let i = 0; i < classList.length; i += 1) {
if (classList[i][0] === "w") {
$(ele).addClass(playerOne.currentWeapon)
playerOne.currentWeapon = classList[i];
$(ele).removeClass(playerOne.currentWeapon)
return classList[i]
}
}
}
$('#right-button').on('click', function() {
$("#square" + moveCounter).removeClass("player")
moveCounter += 1;
$("#square" + moveCounter).addClass("player")
getWeapon("#square" + moveCounter);
});
#grid-box {
width: 420px;
height: 220px;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.w3 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box"></div>
<button class="d-pad-button" id="right-button">Right button</button>
Thank you very much guys.
The problem is the class order in the css file. More info can be found here
Change:
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
To:
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
Demo
let moveCounter = 0;
let playerOne = {
currentWeapon: "w1"
}
var grid = document.getElementById("grid-box");
for (var i = 0; i <= 8; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
$("#square" + 0).addClass("player")
$("#square" + 3).addClass("w3")
function getWeapon(ele) {
let classList = $(ele).attr("class").split(' ');
for (let i = 0; i < classList.length; i += 1) {
if (classList[i][0] === "w") {
$(ele).addClass(playerOne.currentWeapon)
playerOne.currentWeapon = classList[i];
$(ele).removeClass(playerOne.currentWeapon)
return classList[i]
}
}
}
$('#right-button').on('click', function() {
$("#square" + moveCounter).removeClass("player")
moveCounter += 1;
$("#square" + moveCounter).addClass("player")
getWeapon("#square" + moveCounter);
});
#grid-box {
width: 420px;
height: 220px;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w3 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box"></div>
<button class="d-pad-button" id="right-button">Right button</button>
I have just started to learn coding and I have got a problem now.
I have made this black circle witch has number inside and it goes higher every time you click it but I would want now that even numbers would be blue and odd numbers red (1=red, 2=blue, 3=red etc.)
window.onload = function(){
var laskuri = document.getElementById('laskuri');
function kasvata() {
var i =++
laskuri.innerHTML + i;
asetaTaustaVari();
}
function asetaTaustaVari() {
}
laskuri.onclick = kasvata;
}
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
<div id=laskuri>0</div>
You can simply do it by putting an if condition and setting color in it
if (val % 2 == 0) {
color = "blue";
} else {
color = "red";
}
or use ternary operator like this
function kasvata() {
var color = '';
var i = ++
document.getElementById('laskuri').innerHTML + i;
var el = document.getElementById('laskuri');
color = el.innerHTML % 2 == 0 ? "blue" : "red";
el.style.color = color;
asetaTaustaVari();
}
function asetaTaustaVari() {
}
laskuri.onclick = kasvata;
<html lang="fi">
<head>
<meta charset="utf-8">
<title>Laskuri</title>
<style>
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<main>
<div id=laskuri>0</div>
</main>
</body>
</html>
You can achieve it by few ways:
Preferred: You can use a special class-name and use it with your element. In JS code you'll just change a class-name depends on the counter:
<style>
.color_red {
color: red;
}
.color_blue{
color: red;
}
</style>
<script>
window.onload = function(){
var laskuri = document.getElementById('laskuri');
var i = 0;
function kasvata() {
i++;
laskuri.innerHTML = i;
asetaTaustaVari();
}
function asetaTaustaVari() {
var clName = i % 2 === 0 ? 'color_blue' : 'color_red';
laskuri.className = clName;
}
laskuri.onclick = kasvata;
}
</script>
Optional: You can change colors of an element with styles changing. The code is almost the same:
function asetaTaustaVari() {
var color = i % 2 === 0 ? 'blue' : 'red';
laskuri.styles.color = color;
}
P.S.: In your code, please, don't write in your own native language (Finnish / Sweden), please, use english words ALWAYS. Not Laskuri - but Counter.
<!-- Javascript -->
function kasvata() {
var i =++
document.getElementById('laskuri').innerHTML + i;
asetaTaustaVari();
}
function asetaTaustaVari() {
var x = Math.floor(Math.random() * 256);
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var thergb = "rgb(" + x + "," + y + "," + z + ")";
console.log(thergb);
document.getElementById("laskuri").style.color = thergb;
}
laskuri.onclick = kasvata;
<!-- CSS3 -->
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
<!-- HTML5 -->
<html lang="fi">
<head>
<meta charset="utf-8">
<title>Laskuri</title>
</head>
<body>
<main>
<div id=laskuri>0</div>
<main>
</body>
</html>
There is no need of any other function. I think it is required only a ternary operator. You have done almost all thing just modify your javascript code like bellow
<script>
function kasvata() {
var i =++
document.getElementById('laskuri').innerHTML + i;
var val = document.getElementById('laskuri').innerHTML;
document.getElementById('laskuri').style.color = val % 2 == 0 ? "blue" : "red";
}
laskuri.onclick = kasvata;
</script>
I hope you can change the minimum to get it done. Here is the example https://jsfiddle.net/doehxkLy/
And if you want to change the color randomly. Please change the line
document.getElementById('laskuri').style.color = val % 2 == 0 ? "blue" : "red";
To
document.getElementById('laskuri').style.color = "#"+((1<<24)*Math.random()|0).toString(16);
Thumbs up.
You could get the number from the html and use parseInt. Then increment the number and add it to the html.
Then using the remainder you can change the color.
For example:
function kasvata() {
var elm = document.getElementById('laskuri');
if (elm && elm.innerHTML !== "") {
var number = parseInt(elm.innerHTML, 10);
number = number + 1;
elm.innerHTML = elm.innerHTML = number.toString();
asetaTaustaVari(number, elm);
}
}
function asetaTaustaVari(i, elm) {
if (i % 2 === 0) {
elm.style.color = "blue";
} else {
elm.style.color = "red";
}
}
laskuri.onclick = kasvata;
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
<main>
<div id=laskuri>0</div>
</main>
made you a small codepen for it:
https://codepen.io/anon/pen/jZrELZ
you just need a if to see if innerHTML of laskuri is even or odd. I resolve the rest with adding/removing a class. you could also change the background directly with javascript.