Adding dots to an image - beginner - javascript

I have a URL like http://weburl/mine/dot.html?gid=4&x=266y=647&x=191y=355&x=100y=893
From the above URL. i need to draw dots on the screen by taking the x and y values.
According to the above example there are 3 such values.
x=266 y=647
x=191 y=355
x=100 y=893
There are 2 parts to this question:
1.) How can I break the values from the URL and put it to an array in order to construct the image? (Since there are multiple values for x in the above URL)
2.) How can I draw the dot on the image? fiddle added.
Note: Following is the CSS of the dot.
position: 'absolute',
top: ev.pageY + 'px',
left: ev.pageX + 'px',
width: '10px',
height: '10px',
background: '#000000'

1)
// for str use window.location.search.replace("?", "");
var str = 'gid=4&x=266y=647&x=191y=355&x=100y=893';
var data = str.match(/(x|y)=(\d+)/g), pointsX = [], pointsY = [];
for(var i = 0; i < data.length; i++)
{
var tmp = data[i].split('=');
if (tmp[0] == 'x')
pointsX.push(tmp[1]);
else
pointsY.push(tmp[1]);
}
2) place a div with background or border above the image or use html5 + canvas http://jsfiddle.net/dh0swt43/
var str = 'gid=4&x=20y=30&x=40y=50&x=100y=100';
var data = str.match(/(x|y)=(\d+)/g), pointsX = [], pointsY = [];
for(var i = 0; i < data.length; i++)
{
var tmp = data[i].split('=');
if (tmp[0] == 'x')
pointsX.push(tmp[1]);
else
pointsY.push(tmp[1]);
}
for(var i = 0; i < pointsX.length; i++)
{
var div = document.createElement('div');
div.className = 'dot';
div.style.left = pointsX[i] + 'px';
div.style.top = pointsY[i] + 'px';
document.getElementById('wrapper').appendChild(div);
}
.dot {
height: 2px;
width: 2px;
position: absolute;
border: 2px solid red;
z-index: 10;
}
<div style='position:relative' id='wrapper'>
<img src='http://bestclipartblog.com/clipart-pics/earth-clip-art-3.jpg'>
</div>

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

JavaScript - Stop laser once its in its incrementation cycle

To see a working example simply copy code into notepad++ and run in chrome as a .html file, I have had trouble getting a working example in snippet or code pen, I would have given a link to those websites if I could get it working in them.
The QUESTION is; once I fire the laser once it behaves exactly the way I want it to. It increments with lzxR++; until it hits boarder of the game arena BUT if I hit the space bar WHILST the laser is moving the code iterates again and tries to display the laser in two places at once which looks bad and very choppy, so how can I get it to work so the if I hit the space bar a second time even whilst the laser was mid incrementation - it STOPS the incrementing and simply shoots a fresh new laser without trying to increment multiple lasers at once???
below is the Code:
<html>
<head>
<style>
#blueCanvas {
position: absolute;
background-color: black;
width: 932px;
height: 512px;
border: 1px solid black;
top: 20px;
left: 20px;
}
#blueBall {
position: relative;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 10px;
border-radius: 100%;
top: 0px;
left: 0px;
}
#laser {
position: absolute;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 1px;
top: 10px;
left: 10px;
}
#pixelTrackerTop {
position: absolute;
top: 530px;
left: 20px;
}
#pixelTrackerLeft {
position: absolute;
top: 550px;
left: 20px;
}
</style>
<title>Portfolio</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
document.addEventListener("keydown", keyBoardInput);
var topY = 0;
var leftX = 0;
var lzrY = 0;
var lzrX = 0;
function moveUp() {
var Y = document.getElementById("blueBall");
topY = topY -= 1;
Y.style.top = topY;
masterTrack();
if (topY < 1) {
topY = 0;
Y.style.top = topY;
};
stopUp = setTimeout("moveUp()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYup();
console.log('moveUp');
};
function moveDown() {
var Y = document.getElementById("blueBall");
topY = topY += 1;
Y.style.top = topY;
masterTrack();
if (topY > 500) {
topY = 500;
Y.style.top = topY;
};
stopDown = setTimeout("moveDown()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYdown();
console.log('moveDown');
};
function moveLeft() {
var X = document.getElementById("blueBall");
leftX = leftX -= 1;
X.style.left = leftX;
masterTrack();
if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};
stopLeft = setTimeout("moveLeft()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXleft();
console.log('moveLeft');
};
function moveRight() {
var X = document.getElementById("blueBall");
leftX = leftX += 1;
X.style.left = leftX;
masterTrack();
if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};
stopRight = setTimeout("moveRight()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXright();
console.log('moveRight');
};
function masterTrack() {
var pxY = topY;
var pxX = leftX;
document.getElementById('pixelTrackerTop').innerHTML =
'Top position is ' + pxY;
document.getElementById('pixelTrackerLeft').innerHTML =
'Left position is ' + pxX;
};
function topStop() {
if (topY <= 0) {
clearTimeout(stopUp);
console.log('stopUp activated');
};
if (topY >= 500) {
clearTimeout(stopDown);
console.log('stopDown activated');
};
};
function leftStop() {
if (leftX <= 0) {
clearTimeout(stopLeft);
console.log('stopLeft activated');
};
if (leftX >= 920) {
clearTimeout(stopRight);
console.log('stopRight activated');
};
};
function stopConflictYup() {
clearTimeout(stopDown);
};
function stopConflictYdown() {
clearTimeout(stopUp);
};
function stopConflictXleft() {
clearTimeout(stopRight);
};
function stopConflictXright() {
clearTimeout(stopLeft);
};
function shootLaser() {
var l = document.getElementById("laser");
var lzrY = topY;
var lzrX = leftX;
fireLaser();
function fireLaser() {
l.style.left = lzrX; /**initial x pos **/
l.style.top = topY; /**initial y pos **/
var move = setInterval(moveLaser, 1);
/**continue to increment laser unless IF is met**/
function moveLaser() { /**CALL and start the interval**/
var bcrb = document.getElementById("blueCanvas").style.left;
if (lzrX > bcrb + 920) {
/**if the X axis of the laser goes beyond the
blueCanvas 0 point by 920 then stop incrementing the laser on its X
axis**/
clearInterval(move);
/**if statement was found true so stop increment of laser**/
} else {
lzrX++;
l.style.left = lzrX;
};
};
};
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
shootLaser();
};
if (i == 38) {
if (topY > 0) {
moveUp();
};
};
if (i == 40) {
if (topY < 500) {
moveDown();
};
};
if (i == 37) {
if (leftX > 0) {
moveLeft();
};
};
if (i == 39) {
if (leftX < 920) {
moveRight();
};
};
};
/**
!! gradual progression of opacity is overall
!! being able to speed up element is best done with setTimout
!! setInterval is constant regards to visual speed
!! NEXT STEP IS ARRAYS OR CLASSES
IN ORDER TO SHOOT MULITPLE OF SAME ELEMENT? MAYBEE?
var l = document.getElementById("laser");
lzrX = lzrX += 1;
l.style.left = lzrX;
lzrY = topY += 1;
l.style.top = lzrY;
**/
</SCRIPT>
</head>
<div id="blueCanvas">
<div id="laser"></div>
<div id="blueBall">
</div>
</div>
<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>
</body>
</html>
Solved the problem with using a variable called "g" and incrementing it once the laser is shot!
var g = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
if (g < 1) {
shootLaser();
g++;
};
};

Getting the wrong element in click handler with overlapping "circle" divs

I am trying dynamically add HTML elements with click handlers. When the click handler is activated it targets wrong element(it always target the outer circle). Where could be the problem?
(function() {
//selector, jQuery style
var $ = function(selector) {
return document.querySelector(selector);
}
//getting quantity of circles
var quantity = $('.circles').getAttribute('quantity');
//setting outer width/height for circles
$('.circles').style.width = (quantity * 50) + 4 + 'px';
$('.circles').style.height = (quantity * 50) + 4 + 'px';
//creating element for children
var childCircle = document.createElement('div');
childCircle.className = 'subCircle';
//click function for children
function onClick() {
this.attributes.style.value += 'border-color: red;'
alert(this.clientHeight);
}
//append sub circles
for (var i = 0; i < quantity; i++) {
$('.circles').appendChild(childCircle.cloneNode());
}
//iterate over .circles .subCircle and add onClick function for each subCircle and css aswell
var subCircle = $('.circles').getElementsByClassName('subCircle');
for (var i = 0; i < subCircle.length; i++) {
subCircle[i].onclick = onClick;
subCircle[i].style.width = ((i + 1) * 50) + 'px';
subCircle[i].style.height = ((i + 1) * 50) + 'px';
}
})();
.circles {
position: absolute;
}
.subCircle {
position: absolute;
border-radius: 50%;
transform: translateX(-50%) translateY(-50%);
border: 2px solid black;
top: 50%;
left: 50%;
}
<body>
<div class="circles" quantity=10></div>
</body>
Also on jsFiddle: https://jsfiddle.net/martin_borman/1srkL5bf/
The problem isn't this, which is actually getting set by the event callback mechanism just fine. It's that your largest circle is on top.
Changing the loop that sets the size lets you put the smaller circles on top:
for (var i = 0; i < subCircle.length; i++) {
subCircle[i].onclick = onClick;
subCircle[i].style.width = ((subCircle.length - i) * 50) + 'px';
subCircle[i].style.height = ((subCircle.length - i) * 50) + 'px';
}
The key bit there is (subCircle.length - i) * 50 rather than (i + 1) * 50.
I'd also use
this.style.borderColor = 'red';
rather than
this.attributes.style.value += 'border-color: red;'
Example:
(function() {
//selector, jQuery style
var $ = function(selector) {
return document.querySelector(selector);
}
//getting quantity of circles
var quantity = $('.circles').getAttribute('quantity');
//setting outer width/height for circles
$('.circles').style.width = (quantity * 50) + 4 + 'px';
$('.circles').style.height = (quantity * 50) + 4 + 'px';
//creating element for children
var childCircle = document.createElement('div');
childCircle.className = 'subCircle';
//click function for children
function onClick() {
this.style.borderColor = 'red';
alert(this.clientHeight);
}
//append sub circles
for (var i = 0; i < quantity; i++) {
$('.circles').appendChild(childCircle.cloneNode());
}
//iterate over .circles .subCircle and add onClick function for each subCircle and css aswell
var subCircle = $('.circles').getElementsByClassName('subCircle');
for (var i = 0; i < subCircle.length; i++) {
subCircle[i].onclick = onClick;
subCircle[i].style.width = ((subCircle.length - i) * 50) + 'px';
subCircle[i].style.height = ((subCircle.length - i) * 50) + 'px';
}
})();
.circles {
position: absolute;
}
.subCircle {
position: absolute;
border-radius: 50%;
transform: translateX(-50%) translateY(-50%);
border: 2px solid black;
top: 50%;
left: 50%;
}
<body>
<div class="circles" quantity=10></div>
</body>
Just add the z-index property for each circle
subCircle[i].style['z-index'] = subCircle.length-i;
Actually the larger circle is overlapping all the inner circle.

Why can't i create divs and appenidng divs in a loop with javascript?

So I'm using this jquery plugin to have turnable cards. They're made by a div with the class card which has two appending divs with the class front respectively back. Each card has a different id (card-1, card2 etc.) witch different x and y coordinates, because, they're slightly offset, so you can see the edge of the next card.
So this function is to make the cards "flippable":
$(function(){
$(".card").flip({
axis: "y",
reverse: "false",
trigger: "click",
speed: 700,
front: 'autostrict',
back: 'autostrict'
});
});
And for the loop i got this script:
var i = 1;
var l = 10;
var t = -238;
var z = 2;
//nrFragen is gotten from a db, at the moment it equals 2
while (i <= (nrFragen)) {
var newDiv = document.createElement('div');
var frontDiv = document.createElement('div');
var backDiv = document.createElement('div');
newDiv.className = 'card';
newDiv.id = 'card-' + i;
newDiv.style.left = l + "px";
newDiv.style.top = t + "px";
newDiv.style.zIndex = z;
frontDiv.className = 'front';
backDiv.className = 'back';
newDiv.appendChild(frontDiv);
frontDiv.innerHTML = frontDiv.innerHTML + "Front";
newDiv.appendChild(backDiv);
backDiv.innerHTML = backDiv.innerHTML + "Back";
document.getElementsByTagName('body')[0].appendChild(newDiv);
i++;
l += 10;
t -= 10;
z++;
}
And this is the CSS:
.card {
position: absolute;
width: 400px;
height: 248px;
}
.front, .back {
background-color: #F3ECE2;
border: 5px blue solid;
padding: 10px;
border-radius: 25px;
}
#card-0{
left: 0px;
top: 0px;
z-index: 1;
}
There is allready a card-0 which is set with
<div class="card" id="card-0">
<div class="front">
Kategorie 1
</div>
<div class="back">
Alle Kategorien
</div>
If I'm running it nothing's happening, so what did I do wrong?

Getting the exact position of the div

I want to get the exact positions of the div using its class name. Here is the screenshot.. My script which is finding a div position is highlighted in yellow and the div i am looking for is at the bottom highlighted red. Since my script is placed above the div so i am finding the parent div of the document and then comparing the div class with the div class i am looking for and thats how i am getting the positions. The positions are not exact. For example if the Top and Left position of the div is 50,150 then i am getting like 55,155.
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
var left = 0;
var top = 0;
var i = 0;
while (element) {
xPosition = (element.offsetLeft);
yPosition = (element.offsetTop);
console.log("TOP Pos: "+yPosition+"Left Pos: "+xPosition);
if (i == 1) {
left = xPosition;
top = yPosition;
}
element = element.offsetParent;
i++;
}
return {
x: left,
y: top
};
}
And this is how i am using this method.
function ReadDivPos(selector) {
var _divPos = "";
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
var pos = getPosition(parentDiv[i]);
var x = pos["x"];
var y = pos["y"];
console.log("Values+ Top: " + y + " Left: " + x);
var w = parentDiv[i].offsetWidth;
_divPos += x + "," + w + "," + y + "," + (x + w) + ","+window.screen.availWidth+"\\n";
}
}
console.log("Values+ x: " + _divPos);
return _divPos;
}
This is working fine but i am just wondering is there any other better way to make it done using jquery or any other method. Thanks in advance!.
See :
$(function() {
var x = $(".target").offset().left,
y = $(".target").offset().top;
$(".target").html("x: " + x + " y: " + y);
});
body
{
padding: 0;
}
.target
{
background-color: lightgreen;
width: 7em;
height: 7em;
line-height: 7em;
text-align: center;
left: 100px;
top: 20px;
font-family: Calibri;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target"></div>

Categories