I have two action functions here, the first one, firstStartSlide(), creates a div of #2-slide id and appends it to the document, the second one however secondStartSlide() just simply wants to refer to #2-slide and console.log it, but I have no idea why either 'null' or an empty object is returned when I attempt to refer to it inside another function!
I know I can refer to #2-slide inside the firstStartSlide() but I need to refer to that inside secondStartSlide(), but secondStartSlide() or any other function just doesn't recognize it,
anybody knows why this error is happening and how I can fix this?
const eachImageWidth = 700;
const eachImageHeight = 360;
let index = 1;
//----------------------------- DOM elements creator -------------------------------
function domElementsCreator(nth) {
let slideWrapperContainer = document.querySelector('.main');
let slide = document.querySelectorAll('.img-wrapper');
let imgWrapper = document.createElement('div');
imgWrapper.classList.add('img-wrapper');
imgWrapper.id = `${nth}-slide`;
$('.main').append(imgWrapper);
}
// ------------------- image creator function ---------------------
function createImages(nth) {
$(slideWrapperContainer).css('width', '700px').css('height', eachImageHeight);
$(`#${nth}-slide`).css('width', '1400px');
for (let i = 1; i <= 2; i++) {
let img = document.createElement('img');
$(img).attr('src', `https://via.placeholder.com/700x360`);
$(`#${nth}-slide`).append(img);
}
}
domElementsCreator(1)
slideWrapperContainer = document.querySelector('.main');
slides = document.querySelectorAll('.img-wrapper img');
slide = document.querySelectorAll('.img-wrapper');
createImages(1)
//---------------------- first sliding round ------------------------
function firstStartSlide(){
index++;
slide[0].style.transform = `translateX(${-eachImageWidth * (index - 1)}px)`;
slide[0].style.transition = '1000ms';
setTimeout(firstStartSlide, 1500);
if (index === 4){
domElementsCreator(2)
createImages(2)
$('#2-slide').css('left', '0').css('zIndex', '-1')
}
}
firstStartSlide();
//--------------------------- second round -----------------------------
function secondStartSlide() {
let a = 1;
//*************************** here is the error **********************
console.log($('#2-slide'))
console.log(document.getElementById('2-slide'))
//**********************************************************************
}
setTimeout(secondStartSlide, 2 * (1500));
*{
padding: 0;
margin: 0;
}
/*--- slideWrapperContainer ---*/
.main{
margin: 100px auto;
border: 5px solid #000;
position: relative;
/*overflow: hidden;*/
}
/*------- slideWrapper ------*/
.outer-img-wrapper{
position: relative;
width: 100%;
height: 100%;
}
/*---------- slide ----------*/
.img-wrapper{
position: absolute;
top: 0;
left: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bigContainer">
<div class="main">
</div>
</div>
Using a code snippet I found online https://codepen.io/mattyfours/pen/LNgOWx
I made slight modifications and now, although the scroll/fixed functionality works, my 'fixed' side jumps when scrolling. I added 'background-size: contain' onto the fixed side which only works when scrolling has commenced However, on page load/ when no scrolling has occurred the image remains at its full-size meaning once scrolling begins the image goes from full width to 'contained' and created a jump.
Github:
https://github.com/tavimba/fixed-scroll
The issue can be seen in about.html
javascript:
var window_height;
var header_height;
var doc_height;
var posTop_sticky1;
var posBottom_sticky1;
var posTop_s2;
var posBottom_s2;
$(document).ready(function() {
getValues();
});
$(window).scroll(function(event) {
var scroll = $(window).scrollTop();
if (scroll < posTop_sticky1) {
$('.sticky').removeClass('fixy');
$('.sticky').removeClass('bottom');
}
if (scroll > posTop_sticky1) {
$('.sticky').removeClass('fixy');
$('.sticky').removeClass('bottom');
$('#sticky1 .sticky').addClass('fixy');
}
if (scroll > posBottom_sticky1) {
$('.sticky').removeClass('fixy');
$('.sticky').removeClass('bottom');
$('#sticky1 .sticky').addClass('bottom');
$('.bottom').css({
'max-height': window_height + 'px'
});
}
if (scroll > posTop_s2 && scroll < posBottom_s2) {
$('.sticky').removeClass('fixy');
$('.sticky').removeClass('bottom');
$('#s2 .sticky').addClass('fixy');
}
});
function getValues() {
window_height = $(window).height();
doc_height = $(document).height();
header_height = $('header').height();
//get heights first
var height_sticky1 = $('#sticky1').height();
var height_s2 = $('#s2').height();
//get top position second
posTop_sticky1 = header_height;
posTop_s2 = posTop_sticky1 + height_sticky1;
//get bottom position 3rd
posBottom_sticky1 = posTop_s2 - header_height;
posBottom_s2 = doc_height;
}
var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
getValues();
}
}
CSS:
section {
width: 100%;
min-height: 100%;
float: left;
position: relative;
}
header {
width: 100%;
height: 5vw;
background-color: black;
float: left;
}
.sticky {
height: 100%;
width: 60%;
float: left;
position: absolute;
}
.sticky.fixy {
position: fixed;
top: 0;
left: 0;
}
.sticky.bottom {
position: absolute;
bottom: 0;
}
.green {
background-image: url(../imgs/front%20view.jpg);
background-size: cover;
}
.stickyBg {
background-image: url(../imgs/bonnets.jpg);
background-size: cover;
}
.scrolling {
float: right;
width: 50%;
padding: 20px;
h5 {
margin-left: 135px;
}
p {
margin-left: 135px;
font-size: 1em;
line-height: 1.5;
}
}
The jump is caused by change of position from absolute to fixed in combination with 100% height.
Besides, the above code has the following flaws:
Max-height assignment looks inconsistent.
JS assumes exactly two sections in HTML: #section1 and #s2. The third section won't work.
Window resize is handled incorrectly. The half-page-scroll logic consists of the two steps: CalculateVars and AdjustDOMElementPositions. For the smooth look these two actions have to be done in 3 cases: onDocumentLoad, onResize and onScroll.
Global vars.
Looks like, it needs some refactoring to get work ;)
<section class="js-half-page-scroll-section"><!-- Get rid of id -->
...
</section>
function halfPageScroll() {
let scrollTop, windowHeight, headerHeight; // and some other common vars
// Calculate vars
scrollTop = $(window).scrollTop();
//...
let repositionSection = function($section) {
let sectionHeight; // and some other vars related to current section
// Some logic
}
$('.js-half-page-scroll-section').each((i, el) => repositionSection($(el)));
}
$(document).ready(halfPageScroll);
$(window).scroll(halfPageScroll);
$(window).resize(halfPageScroll); // TODO: add some debounce wrapper with timeouts
I am creating chinese checkers, I use span tag to create circles. Added only left padding to the top corner. I have two questions:
1) Why rows seem to have distance between them, but not columns.
2) To fix 1) I added padding-left, but instead of adding distance the padding became part of the circle, why?
Here's the link how it looks:
Here's part of code:
.player0{
height: 40px;
width: 40px;
padding-right: 5px;
background-color: transparent;
border-radius: 50%;
display: inline-block;
}
divs += "<span class='player"+fullBoardArr[fullArrIter]+" 'onclick='send()'></span>"
divs += "<div class='clear_float'> </div>" //for separation of rows
As I said in comments, you need to use margin instead of padding.
I would not use "clear_float" (I assume this is about the float CSS property). Instead wrap elements that belong in the same row, in a separate div element.
From the image you included, it seems that you have a problem in aligning the cells. You can use many ways to solve this, but as your board is symmetric horizontally (ignoring the colors), you can just use text-align: center.
I had some fun in creating JavaScript logic for the board itself. You may find some aspects interesting to reuse:
class Cell {
constructor(rowId, colId) {
this._value = 0;
this.rowId = rowId;
this.colId = colId;
this.elem = document.createElement("span");
this.elem.className = "cell";
this.selected = false;
}
get value() {
return this._value;
}
set value(value) {
this._value = value;
this.elem.style.backgroundColor = ["", "grey", "blue", "red"][value];
}
toggleSelected() {
this.selected = !this.selected;
this.elem.classList.toggle("selected", this.selected);
}
}
class Board {
constructor() {
this._container = document.createElement("div");
this._container.className = "board";
this.elemMap = new Map;
this.grid = [[0,0,0,0,2,0,0,0,0,0,0,0,0],
[0,0,0,0,2,2,0,0,0,0,0,0,0],
[0,0,0,0,2,2,2,0,0,0,0,0,0],
[0,0,0,0,2,2,2,2,0,0,0,0,0],
[3,3,3,3,1,1,1,1,1,4,4,4,4],
[0,3,3,3,1,1,1,1,1,1,4,4,4],
[0,0,3,3,1,1,1,1,1,1,1,4,4],
[0,0,0,3,1,1,1,1,1,1,1,1,4],
[0,0,0,0,1,1,1,1,1,1,1,1,1]];
// create the data structure for the game and produce the corresponding DOM
this.grid.forEach((row, rowId) => {
let div = document.createElement("div");
row.forEach((value, colId) => {
if (!value--) return;
let cell = row[colId] = new Cell(rowId, colId);
cell.value = value;
div.appendChild(cell.elem);
this.elemMap.set(cell.elem, cell);
});
this._container.appendChild(div);
});
}
set container(elem) {
elem.appendChild(this._container);
}
getEventCell(e) {
return this.elemMap.get(e.target);
}
set selected(cell) {
if (this._selected) {
this._selected.toggleSelected();
this._selected = null;
}
if (!cell) return;
cell.toggleSelected();
this._selected = cell;
}
get selected() {
return this._selected;
}
move(cellFrom, cellTo) {
// TODO: Implement the real move rules here
if (!cellFrom.value) return; // must move a piece
if (cellTo.value) return; // capturing not allowed
cellTo.value = cellFrom.value;
cellFrom.value = 0;
board.selected = null;
}
}
let container = document.querySelector("#container");
let board = new Board();
board.container = container;
container.addEventListener("click", e => {
let cell = board.getEventCell(e);
if (!cell) return; // click was not on a cell
if (!board.selected || cell.value) {
board.selected = cell;
} else {
board.move(board.selected, cell);
}
});
.board {
text-align: center;
margin-left: auto; margin-right: auto;
}
.cell {
height: 15px;
width: 15px;
margin: 0px 2px;
border: 1px solid;
border-radius: 50%;
display: inline-block;
}
.selected {
border-color: orange;
}
<div id="container"></div>
You can click to select a piece and then click again on an empty spot to move it there.
Use margin instead of padding:
.player0{
height: 40px;
width: 40px;
margin-right: 5px;
background-color: transparent;
border-radius: 50%;
display: inline-block;
}
As an easy-to-remember quick reference, margin changes the position starting from outside the element border, padding from the inside
I want to create some divs and place the around the body. That means left , right, up and down. I create a div every time a client connect via socket. and here is the code
var parent = document.getElementById("#parent-div")
socket.on("isConnected", function(data) {
// Receive the 'data' and check if 'isConnected' is true
if(data.isConnected == true) {
parent.innerHTML += "<div class='new-div'></div>"
}
});
and here is the style of the div :
.ZE {
position: fixed;
width: 400px;
height: 100px;
background-color: #73AD81;
overflow: hidden;
border-radius: 20px 60px;
border: 2px solid #965D31;
}
how can i do that ?
Your code will work as you have it once you've made a few adjustments.
jsFiddle Demo
First, you have a number symbol (#) you don't need in your getElementById():
Should be:
var parent = document.getElementById("parent-div");
Next, create classes for the locations you want to place them in:
.ZE.left {
top: 50%;
transform: translateY(-50%);
}
.ZE.right {
right: 0;
top: 50%;
transform: translateY(-50%);
}
.ZE.up {
left: 50%;
transform: translateX(-50%);
}
.ZE.down {
left: 50%;
transform: translateX(-50%);
bottom: 0;
}
Up to you how you place them. Above is just one way to place them left/right/top/bottom and may not be the best way at that but I've based it on your existing code.
Lastly you'll want to add those classes, incrementally, or otherwise in your callback function:
// for demo purposes
var data = {
isConnected: true
},
classes = ['left', 'right', 'up', 'down'];
//socket.on("isConnected", function(data) {
// Receive the 'data' and check if 'isConnected' is true
// loop for demo purposes
for (var i = 0; i < 4; i++) {
if(data.isConnected === true) {
parent.innerHTML += "<div class='ZE " + classes[i] + "'></div>"
}
}
//});
var newDiv = document.createElement("div");
var parentDiv = document.getElementById("div_to_place_within");
parentDiv.appendChild(newDiv);
newDiv.id = "some_id";
newDiv.className = "some classnames";
createElement & appendChild
I am creating a learning module for an education company where i create 25 animal sprites (canvas with an image in it) and put them in a farm (div with a background image). I then reorder their z-index according to their location on the background, so that closer sprites will be on top of farther ones (both the background DIV and the sprites are position:absolute;).
This is the function that rearranges the sprites:
Array.prototype.sortIndices = function (func) {
var i = j = this.length,
that = this;
while (i--) {
this[i] = { k: i, v: this[i] };
}
this.sort(function (a, b) {
return func ? func.call(that, a.v, b.v) :
a.v < b.v ? -1 : a.v > b.v ? 1 : 0;
});
while (j--) {
this[j] = this[j].k;
}
}
function rearrangeSprites() {
var zSprites = new Array();
for (var i = 0; i < sprites.length; i++) {
var a = $('#sprite_'+i).css('bottom');
a = a.substr(0, a.length - 2);
zSprites[i] = { b : -a*1 };
}
zSprites.sortIndices(function(a,b) { return a.b - b.b; });
for (var i = 0; i < zSprites.length; i++) {
spriteObjects[zSprites[i]].style.zIndex = (1001 + i) + '';
}
}
It works great in IE and Firefox, but Chrome doesn't respect the z-index order.
any ideas?
Response to answers:
justspamjustin: Tried negative z-indices, as the article seemed to note, at some point. also tried reordering the objects, using this code:
$('.sprite').detach();
for (var i = 0; i < zSprites.length; i++) {
$('#Stage_udi_meadow').append(spriteObjects[zSprites[i]]);
spriteObjects[zSprites[i]].style.zIndex = (i + 1000) + '';
}
nada!
Francis: it would be quite a thing to replace the canvases with, say... DIVs, as a lot of code is built around the canvas features. I also need it to be canvases, because i am using transparency, PNG shadows and doing hit tests for the drag, which will not work with a simple DIV, so I will save this delicious option for last.
apsillers: CSS (as requested):
for the sprites:
element.style {
width: 60.674351585014406px;
height: 60.674351585014406px;
left: 204.55043227665706px;
top: 22.550432276657062px;
cursor: pointer;
z-index: 1003;
}
.sprite {
background-repeat: no-repeat;
margin: 0px;
padding: 0px;
overflow: hidden;
position: absolute;
z-index: 140;
}
.EDGE-122375087, .EDGE-122375087 * {
-webkit-transform: translateX(0px);
}
for the background:
element.style {
position: absolute;
margin: 0px;
left: 0px;
top: 177px;
width: 566px;
height: 347px;
right: auto;
bottom: auto;
background-size: 100%;
background-image: url(http://localhost:9090/cet_html5/publish/images/udi_meadow.png);
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
opacity: 1;
background-position: 0px 0px;
background-repeat: no-repeat no-repeat;
}
#Stage_udi_meadow {
}
.EDGE-122375087, .EDGE-122375087 * {
-webkit-transform: translateX(0px);
}
user agent stylesheetdiv {
display: block;
}
Inherited from body
Style Attribute {
cursor: auto;
}
Sometimes z-index can be a bit tricky. This article from the W3 may be of some help. But that spec may be a bit confusing. If I can't get z-index to work, then I make sure that my elements in the DOM are ordered properly. Generally elements lower in the DOM, have a higher visibility preference. So under some conditions, this might be true:
<div style="z-index:9999">I'm on bottom</div>
<div>I'm on top</div>
Try reordering the elements in the DOM.