Adding incremental relative position to dynamically created divs - javascript

I am trying to create this shape using dynamically created divs. I have this code already in place:
var bgImg = ['ScreenShot.png', 'stars.jpg', 'ScreenShot.png', 'stars_1230_600x450.jpg'];
for (var i = 0, n = 12; i < n; i++) {
var port = document.createElement('div');
document.body.appendChild(port);
port.style.backgroundImage = "url('" + bgImg[3] + "')";
I would like to create this image: https://flic.kr/p/mSJm6G
which will eventually hold images from the array. (one image per slot on the grid.)
I have tried below, which only does not work, it doesn't do what i want, which is to add that amount each time a new div is created. I want a new object to raise by 40px each time it is created.
$(port).css('top','+=40n');
I think that i will have to create three divs/scripts,, one for each row, so that i can get the divs to align properly. the master css will set the divs with a negative margin-top so they can cascade properly.
for reference, my css looks like this:
div {
height: 190px;
width:230px;
background: red;
position: relative;
background: #ef4c4d;
background-position: center;
float: left;
margin: 8px;
top: 30px;
left: 10px;
}
div:before {
content: '';
position: absolute;
bottom: 0; right: 0;
border-bottom: 60px solid #0d1036;
border-left: 60px solid transparent;
width: 0;
}
div:after {
content: '';
position: absolute;
top: 0; left: 0;
border-top: 60px solid #0d1036;
border-right:60px solid transparent;
width: 0;
}
I think that i need to pull the integer from an array, but really not sure.

Some things I notice in your code:
for (var i = 0, n = 12; i < n; i++) {
var port = document.createElement('div');
document.body.appendChild(port);
// <- end "}" of for loop is missing here
port.style.backgroundImage = "url('" + bgImg[3] + "')"; // <- will just be applied on the last created div
I guess you want something like this:
for (var i = 0, n = 12; i < n; i++) {
var port = document.createElement('div');
port.style.backgroundImage = "url('" + bgImg[3] + "')";
document.body.appendChild(port);
}
To update the "top" property, you can use this code with jQuery:
for (var i = 0, n = 12; i < n; i++) {
var port = $('<div></div>');
port.css("background-image", "url('" + bgImg[3] + "')");
port.css("top": 40 * i + "px"); // <- set "top" +40px for each div
$("body").append(port);
}

Related

Centering multiple images in a <tr> element

So I'm building this app which is an implementation of the game "Mancala". In a position of the board there can be "seeds" (game's piece) which I chose to represent as images.
In the initial setup of the game, there are N seeds in each position of the board. I represent this as N equal images ("seed.png") printed randomly in the respective position.
I want images to overlap, so even when N is a big number, they will all fit in the position ("see image nrº1"). What I accomplished so far is a random distribution with little to none overlapping and some "seeds" are getting out of the circle.
This is the code I have, built in JavaScript:
function init_board() {
const board = document.getElementById("board");
for(let i = 0; i < 2; i++) {
const tr = board.insertRow();
if(i == 0) {
tr.insertCell().setAttribute("rowSpan", "2");
}
for(let j = 0; j < 6; j++) {
var x = tr.insertCell();
for(let k = 0; k < 20; k++) {
var img = document.createElement("img");
img.src = "images/seed.png";
img.height = "10";
img.width = "10";
img.style.position = "relative";
img.style.left = Math.floor(Math.random() * 7) + "px";
img.style.top = -7 + Math.floor(Math.random() * 14) + "px";
x.appendChild(img);
}
}
if(i == 0) {
tr.insertCell().setAttribute("rowSpan", "2");
}
}
With the following formatting:
#board {
margin-left: auto;
margin-right: auto;
position: relative;
top: 30%;
}
td {
width: 75px;
height: 75px;
border: 3px solid darkred;
border-radius: 40px;
background: antiquewhite;
}
table {
border: 5px solid darkred;
border-radius: 20px;
background: burlywood;
}
Image Nrº1 N=20: https://imgur.com/a/7aNVsUb,
Image Nrº2 where N=30 and the seeds change the size of the circle: https://imgur.com/a/2iHXwyd
Thank you in advance!
To apply width and height correctly to td tag, you need to make it an inline-block element.
td:not([rowspan="2"]) {
display: inline-block;
}
Your pen updated (with seeds=30): CodePen

DOM assign an id to child Javascript

I have created a grid with div, class and id. I want to randomly create a yellow square and I want to assign an id= 'yellowSquare' how do I do it?
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 100; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
}
}
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#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;
}
<div id="grid-box"></div>
I am new to Javascript / jQuery. Any help will be much appreciated ! Thank you
There are two options to your question. You can either change the id of the yellow square which is already created from your code, or create a child element within the square, which looks the same as your current solution. Creating a new child element will let you keep the numeric id pattern for the grid:
Changing the ID :
var element = document.getElementById('square' + randomIndex)
element.id = "yellowSquare";
Adding new element inside:
var node = document.createElement("DIV");
node.id = "yellowSquare";
node.style = "background-color:yellow;height:100%;width:100%;";
var element = document.getElementById('square' + randomIndex)
element.appendChild(node);
I set the styling of the div child to 100% width and height, as it has no content, and would get 0 values if nothing was specified. This should make it fill the parent container.
There are also multiple other ways to achieve the same result, for instance with JQuery.
Use the HTMLElement method setAttribute (source);
...
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
drawPone.setAttribute('id', 'yellowSquare');
...
As you requested in your comment how to move the square i made an example how you can move it left and right using jQuery next() and prev() functions. However because your html elements are 1 dimensional it's not easy to move them up/down and check the sides for collisions. Better would be to create your html table like with rows and columns and this way create a 2 dimensional play field.
Also added a yellowSquery class for selection with $drawPone.addClass('yellowSquare');.
Also since you like to use jQuery I changed your existing code to jQuery function. Might help you learn the framework.
var $grid = $("#grid-box");
for (var i = 1; i <= 100; i++) {
var $square = $("<div>");
$square.addClass('square');
$square.attr('id','square' + i);
$grid.append($square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var $drawPone = $('#square' + randomIndex);
$drawPone.addClass('yellowSquare');
}
}
$('#button_right').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquareNext = $yellowSquare.next();
$yellowSquare.removeClass('yellowSquare');
$yellowSquareNext.addClass('yellowSquare');
});
$('#button_left').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquarePrev = $yellowSquare.prev();
$yellowSquare.removeClass('yellowSquare');
$yellowSquarePrev.addClass('yellowSquare');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#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;
}
.yellowSquare {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid-box"></div>
<button id="button_left">left</button>
<button id="button_right">right</button><br>

setAttribute background-image can't be changed. Stuck at default value

function showHome() {
removeSlideShow();
var homeHeader = document.createElement("div");
homeHeader.setAttribute("id", "homeHeader");
document.getElementById("window").insertBefore(homeHeader, document.getElementById("content"));
var slideShowDiv = document.createElement("div");
var images = ["slideShow/slideShow-1.jpg", "slideShow/slideShow-2.jpg", "slideShow/slideShow-3.jpg", "slideShow/slideShow-4.jpg", "slideShow/slideShow-5.jpg", "slideShow/slideShow-6.jpg", "slideShow/slideShow-7.jpg"];
homeHeader.appendChild(slideShowDiv);
startSlideShow(slideShowDiv, images);
content.innerHTML = "";
}
function startSlideShow(element, images) {
var iterator = 0;
element.setAttribute("id", "slideShowDiv");
element.setAttribute("style", "background-image: url(" + images[0] + ")");
var startInterval = setInterval(function() {
iterator++;
if (iterator == images.length) iterator = 0;
element.setAttribute("style", "background-image: url(" + images[iterator] + ")");
element.style = "background-image: url(" + images[iterator] + ")";
transition(element);
}, 3000);
}
function removeSlideShow() {
if (document.getElementById("homeHeader")) {
document.getElementById("window").removeChild(document.getElementById("homeHeader"));
}
}
function transition(element) {
element.setAttribute("style", "opacity:0.01;");
var i = 0;
var set = setInterval(function() {
i += 0.01;
element.setAttribute("style", "opacity:" + i + ";");
}, 4);
setTimeout(function() {
clearInterval(set);
element.setAttribute("style", "opacity:1;");
}, 500);
}
div#homeHeader {
background-color: #FFF;
width: 900px;
height: 280px;
border: solid 2px #F00;
border-radius: 20px;
}
div#slideShowDiv {
background-image: url(slideShow/slideShow-1.jpg);
background-color: #FFF;
width: 898px;
height: 278px;
border: solid 1px #FFF;
border-radius: 20px;
background-size: 100% 100%;
}
What i want to do is change the background image every 3 seconds. The code work but it's not changing the image, stays at 'slideShow-1.jpg'. If i remove the transition(element); part, the image rotate just fine. What should i do to get it work? Im still beginner in Javascript, will learn jquery when i got better. Sorry for my grammar.
If i remove the transition(element); part, the image rotate just fine.
The transition part sets a new value for the style attribute.
Setting a new value for the attribute replaces the old value.
You are removing the style for the background image. (So the one from the stylesheet is applied again instead).
What should i do to get it work?
Don't use setAttribute(..., ...) to modify styles.
Use .style.cssPropertyName = ... instead.

Image overlapping a span in another li element

EDIT: I have created a JS-Fiddle that shows you the code in action and you can see how the caption's text is being overlapped. https://jsfiddle.net/wj76sv1h/
So I have a list of divs that display images obtained from a Database. This list is created by PHP, but when I have attempted to add a caption, as you can see from the image (sorry I can't include the image directly in the post), it is being overlapped by another Li element's image. The caption is a span tag.
I have attempted to change the z-index of the images and the divs, however it seems like it has no effect. I am also using this code in order to create the grid system using the lis.
function createListStyles(rulePattern, rows, cols) {
var rules = [], index = 0;
for (var rowIndex = 0; rowIndex < rows; rowIndex++) {
for (var colIndex = 0; colIndex < cols; colIndex++) {
var x = (colIndex * 100) + "%",
y = (rowIndex * 100) + "%",
transforms = "{ -webkit-transform: translate3d(" + x + ", " + y + ", 0); transform: translate3d(" + x + ", " + y + ", 0); }";
rules.push(rulePattern.replace("{0}", ++index) + transforms);
}
}
var headElem = document.getElementsByTagName("head")[0],
styleElem = $("<style>").attr("type", "text/css").appendTo(headElem)[0];
if (styleElem.styleSheet) {
styleElem.styleSheet.cssText = rules.join("\n");
} else {
styleElem.textContent = rules.join("\n");
}
}
If anyone could help me, that would be great. Thanks. This is the html used for the item/caption.
<div class="item" id="item-covert"><span>Caption</span> <div id="item-price"> $54.36</div><img class="item-image" src="image.url"></div>
Css:
.item {
position: relative
}
.item span {
display: none;
position: absolute;
bottom: 0;
padding: 10px;
background: rgba(255,255,255,0.99);
/*top: 20px;
width: 300px;
height: 50px;*/
font-family: Open Sans;
/*margin-left: 110px;*/
left: 110px;
}
.item:hover span {
display: block
}
Your positioning of the span moves it onto the image. Move it ten pixels farther to the right, and it looks fine. https://jsfiddle.net/yak613/5p3uuzfg/
I've taken some liberties with the caption text :)
And some suggestions for cool caption colors :)
Live Example

jQuery offset issues with div overflow: scroll

I am writing an HTML5 board game and I am having issues with jQuery's offset(). The grid of DIVs that make up the game board reside within a wrapper DIV that has CSS that sets overflow:scroll/width and height:100%. The game board itself is quite larger, so the scroll can be quite a bit horizontally and vertically.
The problem is that when I click on a DIV and try to move the player to that board piece, the player shifts around and is never in a consistent place relative to the board piece clicked.
Code:
$(".boardGridPiece").click(function(){
if(!$(this).hasClass("room") && $(this).hasClass("eligibleMove")){
playerStartX = $(this).offset().left;
playerStartY = ($(this).offset().top;
player.css("left", playerStartX);
player.css("top", playerStartY);
determineEligibleMoves($(this).attr("id"));
}
});
You can see that when a board piece is clicked, the offset of the board piece is grabbed and set to the player's X and Y.
CSS:
#boardWrapper {
position:relative;
width:100%;
height:80%;
overflow: scroll;
}
#theGame {
background-color: #fff;
height: 1080px;
width: 1920px;
}
Depending on where the player is relative to the current scroll view, when I click on a board piece he shifts around in a very inconsistent manner. Sometimes he's far left of where I click, or far up, etc.
What am I doing wrong? How do I take into account relative scroll position to get consistent positioning?
Here's a board for you to play with as an example. Also, my stab at the jquery is included as well. Basically, it finds where you clicked, calculated the px distance in float form, and animates the soldier to slide to his new position:
var black = '<td style="background-color:black"><div class="boardGridPiece"></div></td>';
var white = '<td style="background-color:white"><div class="boardGridPiece"></div></td>';
var squares = [black, white];
var grid = "";
for (var i = 0; i < 9; i++) {
grid += "<tr>";
for (var j = 0; j < 16; j++) {
grid += squares[(i + j) % 2];
}
grid += "<\tr>";
}
$('#gameboard').append(grid);
var gridSelected = $('#gameboard').find('tr:nth-child(2)').find('td:first').find('div');
gridSelected.toggleClass('position');
$('.boardGridPiece').click(function () {
$('.position').removeClass('position');
var gridSelected = $(this);
gridSelected.toggleClass('position');
var thisBox = $('.position');
var finalX = 0;
var finalY = 0;
for (var i = 0; i < 9.00; i++) {
for (var j = 0; j < 16.00; j++) {
var aBox = $('#gameboard').find('tr:nth-child(' + (i + 1) + ')').find('td:nth-child(' + (j + 1) + ')').find('div');
if (thisBox.get(0) == aBox.get(0)) {
finalX = j + 1;
finalY = i;
i = j = 16; // soft break
}
}
}
var overX = (finalX * parseFloat(1920))/16.00;
var downY = (finalY * parseFloat(1080))/9.00;
$('#player').animate({ left: overX, top: downY });});
html {
background-color:gray;
}
#gameboard {
margin: 100px;
height:1080px;
width:1920px;
border:1px solid black;
}
.boardGridPiece {
height: 110px;
width: 110px;
}
.position {
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
border: 1px solid red;
}
#player {
position: absolute;
top: 120px;
left: 125px;
height: 200px;
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="gameboard" style=""></table>
<img id="player" src="http://img2.wikia.nocookie.net/__cb20110819034426/halo/images/7/74/ODST_Helljumper.png" />

Categories