I have a CSS grid layout and want to get the cell position below my cursor.
Imagine the following example:
If my cursor is where the star in the image is, I’m looking for a javascript function which returns {grid-row-start: 2, grid-row-end: 3, grid-column-start: 5, grid-column-end: 6}.
Does anybody of you knows about a native function to do this? Or do i have to calculate the values myself?
Thanks :)
The code of my example looks like the following:
<html>
<head>
<style>
.container {
display: grid;
grid-gap: 10px;
background-color: blue;
grid-template-columns: repeat(6, 1fr);
height: 400px;
}
.container div {
background-color: green;
}
.grid-stack-item {
}
</style>
</head>
<body>
<div class="container">
<div class="grid-stack-item" data-gs-x="0" data-gs-y="0" data-gs-width="2" data-gs-height="1">
<div class="grid-stack-item-content">1</div>
</div>
<div class="grid-stack-item" data-gs-x="2" data-gs-y="0" data-gs-width="2" data-gs-height="2">
<div class="grid-stack-item-content">2</div>
</div>
<div class="grid-stack-item" data-gs-x="4" data-gs-y="0" data-gs-width="1" data-gs-height="1">
<div class="grid-stack-item-content" style="overflow: hidden">3</div>
</div>
<div class="grid-stack-item" data-gs-x="5" data-gs-y="0" data-gs-width="1" data-gs-height="1">
<div class="grid-stack-item-content"> 4</div>
</div>
<div class="grid-stack-item" data-gs-x="0" data-gs-y="1" data-gs-width="1" data-gs-height="1">
<div class="grid-stack-item-content">5</div>
</div>
<div class="grid-stack-item" data-gs-x="1" data-gs-y="1" data-gs-width="1" data-gs-height="2">
<div class="grid-stack-item-content">6</div>
</div>
<div class="grid-stack-item" data-gs-x="0" data-gs-y="2" data-gs-width="1" data-gs-height="1">
<div class="grid-stack-item-content">8</div>
</div>
<div class="grid-stack-item" data-gs-x="2" data-gs-y="2" data-gs-width="2" data-gs-height="1">
<div class="grid-stack-item-content">9</div>
</div>
<div class="grid-stack-item" data-gs-x="4" data-gs-y="2" data-gs-width="1" data-gs-height="1">
<div class="grid-stack-item-content">10</div>
</div>
<div class="grid-stack-item" data-gs-x="5" data-gs-y="2" data-gs-width="1" data-gs-height="1">
<div class="grid-stack-item-content">11</div>
</div>
</div>
<script>
for(let elm of document.getElementsByClassName('grid-stack-item')){
elm.style['grid-column-start'] = parseInt(elm.getAttribute('data-gs-x')) + 1;
elm.style['grid-column-end'] = parseInt(elm.getAttribute('data-gs-x')) + parseInt(elm.getAttribute('data-gs-width')) + 1;
elm.style['grid-row-start'] = parseInt(elm.getAttribute('data-gs-y')) +1 ;
elm.style['grid-row-end'] = parseInt(elm.getAttribute('data-gs-y')) + parseInt(elm.getAttribute('data-gs-height')) +1;
}
</script>
</body>
</html>
What you want to do is figure out which element the mouse is over, and then get the window.getComputedStyle(element).gridColumnStart (and others) from that element.
The simplest way to do this would be to just add a mouseenter event to each of the grid-stack-item elements.
Here's a rough example:
let currentCellPosition = {
"grid-row-start": null,
"grid-row-end": null,
"grid-column-start": null,
"grid-column-end": null
}
Array.from(document.getElementsByClassName("grid-stack-item")).forEach(element => {
element.addEventListener("mouseenter", () => {
const style = window.getComputedStyle(element);
currentCellPosition = {
"grid-row-start": style.gridRowStart,
"grid-row-end": style.gridRowEnd,
"grid-column-start": style.gridColumnStart,
"grid-column-end": style.gridColumnEnd
}
})
})
In this example, currentCellPosition will always have the most recent cell position.
document.addEventListener("DOMContentLoaded", () => {
const output = document.getElementById("output");
Array.from(document.getElementsByClassName("cell")).forEach(element => {
element.addEventListener("mouseenter", () => {
const style = window.getComputedStyle(element)
output.innerHTML = `
row start: ${style.gridRowStart}
row end: ${style.gridRowEnd}
column start: ${style.gridColumnStart}
column end: ${style.gridColumnEnd}
`;
})
})
});
.container {
border: 2px solid green;
display: grid;
grid-template-columns: auto auto;
grid-template-rows: auto auto;
height: 200px;
width: 100%;
}
.a {
grid-row-start: 1;
grid-row-end: 2;
grid-column-start: 1;
grid-column-end: 2;
background-color: lightblue;
}
.b {
grid-row-start: 2;
grid-row-end: 3;
grid-column-start: 1;
grid-column-end: 3;
background-color: orange;
}
.c {
grid-row-start: 1;
grid-row-end: 2;
grid-column-start: 2;
grid-column-end: 3;
background-color: lightgreen;
}
<div class="container">
<div class="a cell"></div>
<div class="b cell"></div>
<div class="c cell"></div>
</div>
<p id="output">
</p>
the idea here is to add an extra grid layer beyond the container. lets call it "pseudoContainer".
This pseudoContainer will be absolute postioned.
It will contain elements in columns with 16,6% width and a heigth that will match to the grid.
Now we can bind the mouseenter to the pseudo elements.
Based on #Ian answer I have made a fiddle:
first create some pseudo elements:
var cont = $(".pseudoContainer");
for (var i = 0; i < 18; i++) {
var newDiv = document.createElement("div");
newDiv.setAttribute('class', 'pseudoitem');
newDiv.innerHTML = '<div class="pseudoitem-inner"></div>';
cont.append(newDiv);
}
then add listener:
Array.from(document.getElementsByClassName("pseudoitem-inner")).forEach(element => {
element.addEventListener("mouseenter", () => {
const style = window.getComputedStyle(element);
currentCellPosition = {
"grid-row-start": style.gridRowStart,
"grid-row-end": style.gridRowEnd,
"grid-column-start": style.gridColumnStart,
"grid-column-end": style.gridColumnEnd
}
console.log(currentCellPosition);
})
})
with some styling you can see:
.pseudoContainer{
position:absolute;
top:0;
left:0;
width: 100%;
display: block;
padding: 3px;
z-index:1;
}
.pseudoitem{
width: calc(16.6% - 10px);
height: 126px;
float: left;
padding: 5px 5px 5px;
z-index:2;
}
.pseudoitem-inner{
background-color: red;
height: 100%;
width: 100%;
}
.container{
z-index:1;
}
.grid-stack-item{
z-index:3;
}
now you only to refine the pseudo elements creation process so that they contain the grid information.
here is a fiddle
EDIT:
Now you will get the desired information onmouseover.
The way here is also to add an extra grid layer beyond the container and set position absolute.
Unfortunately this will work only for this grid and it is really not my best work.
In priciple it is the same as solution one but now make also use of grid style here.
var cont = $(".pseudoContainer");
var y,x;
for (var i = 0; i < 18; i++) {
if(i <= 5) y = 0, x = i;
if(i > 5 && i <= 11) y = 1, x = i - 6;
if(i > 11 && i <= 18) y = 2, x = i - 12;
var newDiv = document.createElement("div");
newDiv.setAttribute('class', 'pseudoitem');
newDiv.setAttribute('data-gs-width', '1');
newDiv.setAttribute('data-gs-height', '1');
newDiv.setAttribute('data-gs-x', x);
newDiv.setAttribute('data-gs-y', y);
newDiv.innerHTML = '<div class="pseudoitem-inner"></div>';
cont.append(newDiv);
}
for(let elm of document.getElementsByClassName('pseudoitem')){
elm.style['grid-column-start'] = parseInt(elm.getAttribute('data-gs-x')) + 1;
elm.style['grid-column-end'] = parseInt(elm.getAttribute('data-gs-x')) + parseInt(elm.getAttribute('data-gs-width')) + 1;
elm.style['grid-row-start'] = parseInt(elm.getAttribute('data-gs-y')) +1 ;
elm.style['grid-row-end'] = parseInt(elm.getAttribute('data-gs-y')) + parseInt(elm.getAttribute('data-gs-height')) +1;
}
let currentCellPosition = {
"grid-row-start": null,
"grid-row-end": null,
"grid-column-start": null,
"grid-column-end": null
}
Array.from(document.getElementsByClassName("pseudoitem")).forEach(element => {
element.addEventListener("mouseenter", () => {
const style = window.getComputedStyle(element);
currentCellPosition = {
"grid-row-start": style.gridRowStart,
"grid-row-end": style.gridRowEnd,
"grid-column-start": style.gridColumnStart,
"grid-column-end": style.gridColumnEnd
}
console.log(currentCellPosition);
})
})
and the styling:
.pseudoContainer{
position:absolute;
top:10px;
left:10px;
width: 100%;
height: 400px;
display: grid;
z-index:1;
grid-template-columns: repeat(6, 1fr);
grid-gap: 0px;
}
.pseudoitem{
z-index:2;
}
.pseudoitem-inner{
height: 100%;
width: 100%;
}
.container{
z-index:1;
}
.grid-stack-item{
z-index:3;
}
EDIT2:
I have rewritten the calculation. now you can define "repeat" and "rows" parameter and layer2 grid will be automatically created.
the fiddle is updated and here is the code change:
var cont = $(".pseudoContainer");
var y,x;
var repeat = 6;
var rows = 3;
for (var i = 0; i < rows*repeat; i++) {
if(i%repeat === 0) {
y = i/repeat;
}
x = i- y * repeat;
var newDiv = document.createElement("div");
newDiv.setAttribute('class', 'pseudoitem');
newDiv.setAttribute('data-gs-width', '1');
newDiv.setAttribute('data-gs-height', '1');
newDiv.setAttribute('data-gs-x', x);
newDiv.setAttribute('data-gs-y', y);
newDiv.innerHTML = '<div class="pseudoitem-inner"></div>';
cont.append(newDiv);
}
for(let elm of document.getElementsByClassName('pseudoitem')){
elm.style['grid-column-start'] = parseInt(elm.getAttribute('data-gs-x')) + 1;
elm.style['grid-column-end'] = parseInt(elm.getAttribute('data-gs-x')) + parseInt(elm.getAttribute('data-gs-width')) + 1;
elm.style['grid-row-start'] = parseInt(elm.getAttribute('data-gs-y')) +1 ;
elm.style['grid-row-end'] = parseInt(elm.getAttribute('data-gs-y')) + parseInt(elm.getAttribute('data-gs-height')) +1;
}
let currentCellPosition = {
"grid-row-start": null,
"grid-row-end": null,
"grid-column-start": null,
"grid-column-end": null
}
Array.from(document.getElementsByClassName("pseudoitem")).forEach(element => {
element.addEventListener("mouseenter", () => {
const style = window.getComputedStyle(element);
currentCellPosition = {
"grid-row-start": style.gridRowStart,
"grid-row-end": style.gridRowEnd,
"grid-column-start": style.gridColumnStart,
"grid-column-end": style.gridColumnEnd
}
console.log(currentCellPosition);
})
})
Related
I'm trying to create a tile-like content carousel for a website I'm creating. Basically I need the ordinary content carousel functionality that comes in a lot of different jQuery plug-ins etc. - but instead of the slider being linear, I need the items to shift tiles in a circular manner like this:
Step 1:
Step 2:
Step 3:
I tried creating the setup using Flexbox and some simple jQuery:
$(document).ready(function () {
$(".item").each(function (index) {
$(this).css("order", index);
});
$(".prev").on("click", function () {
// Move all items one order back
$(".item").each(function (index) {
var currentOrder = parseInt($(this).css("order"));
if (currentOrder == undefined) {
currentOrder = index;
}
var newOrder = currentOrder - 1;
if (newOrder < 0) {
newOrder = 5;
}
$(this).css("order", newOrder);
});
});
$(".next").on("click", function () {
// Move all items one order forward
$(".item").each(function (index) {
var currentOrder = parseInt($(this).css("order"));
var newOrder = currentOrder + 1;
if (newOrder > 5) {
newOrder = 0;
}
$(this).css("order", newOrder);
});
});
});
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 500px;
}
.item {
width: 125px;
height: 75px;
color: white;
text-align: center;
font-size: 24px;
border: 1px solid white;
padding-top: 50px;
box-sizing: content-box;
background-color: rgb(42, 128, 185);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="prev">Prev</button>
<button class="next">Next</button>
<div class="container">
<div class="item one">1</div>
<div class="item two">2</div>
<div class="item three">3</div>
<div class="item four">4</div>
<div class="item five">5</div>
<div class="item six">6</div>
</div>
but this leaves me with some unresolved issues:
How do I animate the tiles when changing the order (when clicking next/prev)?
How do I fix the order so that the items move in a continuous line instead of wrapping to the start of next line (I'd like the order to be like displayed in step 2 -> 3)?
Any existing plug-in (I've looked but can't find any) or codepen etc. would be very much appreciated as I'm not sure if my approach is maintainable (or even doable).
Thanks a bunch :)
I've used absolute position formula from index to (top, left). Then i've used jQuery to animate that. That's lame but can be improved if that's an issue. It looks nice.
const containerBox = document.querySelector('#container')
let divs = [...containerBox.querySelectorAll('div')]
var size = 100
var margin = 2
function get_top_left(pos) {
if (pos < divs.length / 2) {
return {
left: pos * size + margin * (pos),
top: 0
}
} else {
return {
left: (divs.length - pos - 1) * size + margin * (divs.length - pos - 1),
top: size + margin
}
}
}
var offset = 0
function draw() {
divs.forEach(function(div, index) {
var len = divs.length
index = ((index + offset) % len + len) % len
var pos = get_top_left(index);
//div.style.left = pos.left + "px"
//div.style.top = pos.top + "px"
$(div).animate({
"left": pos.left + "px",
"top": pos.top + "px"
})
})
}
next.onclick = _ => {
offset += 1
draw()
}
prev.onclick = _ => {
offset -= 1
draw()
}
draw();
#container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 500px;
height: 260px;
margin: 10px;
position: relative;
}
#container>div {
width: 100px;
height: 66px;
color: white;
text-align: center;
font-size: 24px;
border: 1px solid white;
padding-top: 34px;
box-sizing: content-box;
background: #2a80b9;
position: absolute;
top: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="prev">Prev</button>
<button id="next">Next</button>
<div id="container">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
<div> 5 </div>
<div> 6 </div>
</div>
This kind of carousel ?
const
containerBox = document.querySelector('#container')
, nextOrder = [3,0,1,4,5,2]
, prevOrder = [1,2,5,0,3,4]
;
next.onclick =_=>
{
let divs = [...containerBox.querySelectorAll('div')]
nextOrder.forEach(n=> containerBox.appendChild( divs[n]) )
}
prev.onclick =_=>
{
let divs = [...containerBox.querySelectorAll('div')]
prevOrder.forEach(n=> containerBox.appendChild( divs[n]) )
}
#container {
display : flex;
flex-direction : row;
flex-wrap : wrap;
width : 500px;
margin : 20px;
}
#container > div {
width : 125px;
height : 75px;
color : white;
text-align : center;
font-size : 24px;
border : 1px solid white;
padding-top : 50px;
box-sizing : content-box;
background : #2a80b9;
}
<button id="prev">Prev</button>
<button id="next">Next</button>
<div id="container">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 6 </div>
<div> 5 </div>
<div> 4 </div>
</div>
Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.
So I have a div wrap whose size is a percentage of the screen width. Inside this wrap is multiple .item divs. As the window gets smaller it breaks into new lines obviously.
I wrote some code which basically takes the width of the wrap and divides it by the sum of the widths of the .item boxes. But the flaw is that it looks at it thinking how many boxes could fit in total, were one to mix and match them perfectly like building blocks, but that's not how it works because the ordering is stagnant.
How could I make this logic work?
CodePen
jQuery:
var itemWidth = 0;
var lineCount = 1;
$(window).on('resize', function(){
var lineWidth = $('.line').width();
var itemWidthSum = 0;
lineCount=1;
$('.item').each(function(index, element) {
if(itemWidthSum < (lineWidth - $(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = 0;
}
});
});
HTML:
<div id="container">
<div class="rect">
<div class="line">
</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<h1 class="answer"></h1>
CSS:
body {
padding:25px;
}
.answer {
position:fixed;
bottom:0;
left:0;
}
#container {
border: 1px solid rgb(200,200,200);
height: auto;
width: 30%;
margin:0 auto;
}
.item {
padding: 10px;
background-color: #aef2bd;
float: left;
}
.rect {
height: 100px;
width:100%;
position: relative;
}
.rect .line {
position:absolute;
height:50px;
width: 100%;
bottom:0;
border-top: 1px solid red;
}
Figured out my logic mistake by debugging each step.
The correct jQuery:
var itemWidth = 0;
var lineCount = 1;
$(window).on('resize', function(){
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var list = [];
lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
});
This question already has answers here:
How to move an element into another element
(16 answers)
Closed 7 years ago.
I am new at JavaScript. I am trying to make Snakes and Ladders game with native JavaScript code as much as possible. My problem is that I can not move players from their initial position according to the random number generated when pressing on dice image. Can anyone help me on how to move players?
var gameBoard = {
createBoard: function(dimension, mount, intialPosition) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table, intialPosition);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = 'lastCell';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = 'firstCell';
intialPosition();
return gameBoard;
}
};
window.onload = (function(e) {
gameBoard.createBoard(10, "#grid", intialPosition);
});
var face1 = new Image()
face1.src = "d1.gif"
var face2 = new Image()
face2.src = "d2.gif"
var face3 = new Image()
face3.src = "d3.gif"
var face4 = new Image()
face4.src = "d4.gif"
var face5 = new Image()
face5.src = "d5.gif"
var face6 = new Image()
face6.src = "d6.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
function intialPosition() {
$("#firstCell").append($("#player1"));
$("#firstCell").append($("#player2"));
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#lastCell {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="oie_eRDOY2iqd5oQ.gif" />
</div>
<div id="bigSnake">
<img src="oie_485727sRN4KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="humanPiece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="computerPiece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="reset">New Game</button>
</div>
<div>
<button type="button" name="reset">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
<!--<h2 id="status" style="clear:left;"></h2>-->
</div>
</div>
</div>
<script src="JavaScript1.js"></script>
</body>
</html>
I fell miserable about not being able to finish the game. I really need help. Thanks in advance.
Well, first of all this question has been already asked and answered on SO and table cells are just the same as usual elements :)
Since you're using jQuery anyway, you can use .detach()
var element = $('td:eq(0) span').detach();
$('td:eq(1)').append(element);
Here's a jsfiddle.
Or, as proposed in this answer, you can use a native js solution.
I am new to web development but highly fascinated by it. So, basically I am creating a light-box where thumbnails of images will be appear on screen and they will appear bigger in size when user clicks over them. Now, I want when user hovers over the gallery images/thumbnails then some text should appear over the current image with may be some animation or basically mouser-hover should cause some event to happen but I am unable to do it. Text should be added dynamically or may be previously stored in an array or something of that sort. Please have a look at my code and tell me how to modify it in order to achieve such effect and if you know a better and easier way to do so then feel free to share. Thank you so much!!
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
JAVASCRIPT:
var gallery_slider = new Array();
gallery_slider[0] = "im1.jpg";
gallery_slider[1] = "im2.jpg";
gallery_slider[2] = "im3.jpg";
function displayAllImages() {
var i = 0,
len = gallery_slider.length;
for (; i < gallery_slider.length; i++) {
var img = new Image();
img.src = gallery_slider[i];
img.style.width = '200px';
img.style.height = '120px';
img.style.margin = '3px';
img.style.cursor = 'pointer';
document.getElementById('images').appendChild(img);
}
};
$(function() {
displayAllImages();
});
$(function() {
$('img').click(function() {
var hell = (this).src;
display(hell);
});
});
function display(hello) {
$('header').css('display', 'none'); /*for some other purposes*/
$('.limage').html("<img src=" + hello + " >");
$('.lightbox').css("display", "block");
$('.lightbox').fadeIn();
$('.right').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p >= (im.length - 1)) {
p = -1;
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p + 1] + ">");
$('.limage').fadeIn(500);
hello = im[p + 1];
});
$('.left').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p == 0) {
p = (im.length);
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p - 1] + ">");
$('.limage').fadeIn(500);
hello = im[p - 1];
});
$('.close').click(function() {
$('.lightbox').fadeOut();
$('header').css('display', 'block'); /*for some other purposes*/
});
};
CSS:
.gallery {
width: 100%;
height: 400px;
overflow: hidden;
margin: auto;
}
.gallery ul {
list-style: none;
}
.lightbox {
background-color: rgba(0, 0, 0, 0.3);
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
z-index: 106;
}
.close {
color: #fff;
border: 1px solid #fff;
border-radius: 100px;
background-color: #000;
position: absolute;
top: 10px;
right: 20px;
padding: 10px;
font-family: firstfont;
font-size: 30px;
z-index: 101;
cursor: pointer;
}
.close:hover {
background-color: #ebebeb;
color: #000;
}
.left {
width: 50%;
height: 100%;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
.right {
width: 50%;
height: 100%;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
.limage {
position: relative;
margin: auto;
top: 17%;
left: 15%;
max-width: 90%;
max-height: 90%;
}
There might be some bugs in coding. Watch out.
This code is working for displaying images as thumbnails as a matrix and as slider in lightbox when clicked upon them. I am not able to figure out how to add hover functionality to initial thumbnails.
Jsfiddle :
http://jsfiddle.net/psd6cbd7/1/
I'd suggest putting a div inside the image div containing the text and then using CSS to hide/show it.
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
<div class=".caption">Caption here</div>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
CSS:
.limage { position: relative; }
.caption { display: none; }
.limage:hover .caption { display: block; position: absolute;}
Why you using array to store the images? Anyways, assume that you still using array, below is some example code that you want try:
HTML:
<ul id="images">
</ul>
<!-- assume this is the place that you want to display the caption -->
<div id="caption"></div>
Javascript:
var images = new Array();
images[0] = "p1.png";
images[1] = "p2.png";
images[2] = "p3.png";
images[3] = "p4.png";
var captions = new Array();
captions[0] = "Picture 1";
captions[1] = "Picture 2";
captions[2] = "Picture 3";
captions[3] = "Picture 4";
var x = $("#images");
var y = $("#caption");
const prefix = "image-";
if you are using HTML5:
for (var i = 0; i < images.length; i++) {
x.append("<img class='roll' src='" + images[i] + "' data-caption='" + captions[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
y.html($(this).attr("data-caption"));
});
If you want to backward compatible:
for (var i = 0; i < images.length; i++) {
x.append("<img id='" + prefix + i + "' class='roll' src='" + images[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
var index = $(this).attr("id").substring(prefix.length);
y.html(captions[index]);
});
Hope that this will help.