Modifying CSS position with JS - javascript

I'm using document.getElementById("").style.top = var; to randomly change the position of an object every time I click on it, but I can only randomly change the position by pixels and not percentage. How do I randomly generate a number with % ?
document.getElementById("randObject").onclick = function () {
var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random()*100;
var xAxis = Math.random()*100;
document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
}

document.getElementById("randObject").style.top = yAxis + "%";
document.getElementById("randObject").style.left = xAxis + "%";
I should point out that your color generator is also not valid 1/16 of the time. You need to left-zero-pad the string:
"#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
Another shortcut you can use to save DOM lookup time is to use the this keyword in your click event. All together it looks like:
Lastly, you might consider using .addEventListener('click', function() { ... }) since that is the current standard, though what you're doing works alright if you reeeally want to support IE6.
Let's check out the demo since this looks like a pretty neat script now:
document.getElementById("randObject").addEventListener('click', function() {
var bColor = "#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
var yAxis = Math.random() * 100;
var xAxis = Math.random() * 100;
this.style.backgroundColor = bColor;
this.style.top = yAxis + "%";
this.style.left = xAxis + "%";
});
:root {
/* change this value to update the size of playing field and #randObject */
--size: 50px;
}
html {
position: absolute;
margin: 0 var(--size) var(--size) 0;
padding: 0;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
body {
margin: 0;
padding: 0;
}
#randObject {
position: absolute;
top: 0;
left: 0;
width: var(--size);
height: var(--size);
background-color: #000000;
border-radius: 50%;
cursor: pointer;
transition-property: top, left, background-color;
transition-duration: 0.4s;
}
<div id="randObject"></div>

I added positioning to your code and I was able to make it to move by percentage.
<img id="randObject" width=100 height=100>
<script>
document.getElementById("randObject").onclick = function () {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random() + '%';
var xAxis = Math.random() + '%';
document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
document.getElementById("randObject").style.position = 'absolute';
}
</script>

Related

How to recalculate position of marker inside div with vh html,css,js

I trying to create a map framework for some games and i have a problem with recalc position of marker. Look url to test, with wheel you can resize div with image but the dot red not come back to own position. Sorry but im new on this y trying to learn more about js and css. Thanks
$('.map-live').css('width', "928px");
$('.map-live').css('height', "928px");
$('.map-live').css('background-size', "100%");
$('.map-live').bind('mousewheel DOMMouseScroll', function(event) {
var divSize = $('.map-live').css('width');
console.log(divSize);
divSize = divSize.replace('px', '')
divSize = parseInt(divSize);
console.log("oldSize: " + divSize);
var delta_px = event.originalEvent.wheelDelta > 0 ? (divSize + (divSize * 0.15)) : (divSize - (divSize * 0.15));
console.log("NewSize: " + delta_px);
$(this).css('width', delta_px + "px");
$(this).css('height', delta_px + "px");
$(this).css('background-size', "100%");
UpdatePoints();
});
$(function() {
$("#map-live").draggable();
});
document.getElementById('map-live').addEventListener('click', printPosition)
function getPosition(e) {
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
return {
x,
y
}
}
function printPosition(e) {
var position = getPosition(e);
console.log('X: ' + position.x + ' Y: ' + position.y);
var divX = parseInt($('.map-live').css('width').replace('px', ''));
var divY = parseInt($('.map-live').css('height').replace('px', ''));
var vhX = (position.x / divX) * 100;
var vhY = (position.y / divY) * 100;
console.log('vhX: ' + vhX + ' vhY: ' + vhY);
}
function UpdatePoints() {
$('.point').css('top', '2.477565353101834vh');
$('.point').css('left', '2.477565353101834vh');
$('.point').css('position', 'absolute');
}
body {
margin: 0;
overflow: hidden;
}
.map-live {
position: absolute;
left: 10px;
z-index: 9;
background-image: url(https://i.ibb.co/d2y5G1y/map.jpg);
width: 222px;
height: 222px;
transition: all 0.2s linear;
}
.point {
position: absolute;
left: 2.477565353101834vh;
top: 2.477565353101834vh;
width: 10px;
height: 10px;
background-color: red;
border-radius: 50%;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="map-live ui-widget-content" id="map-live">
<div class="point"></div>
</div>
jsfiddle.net/f84mto52
Someone can correct me, but I believe your use of position: absolute is what is making the <div class="point"></div> stay in place.
Your UpdatePoints is setting always the same position in the div. With 'vh' you are calculating and absolute position proportional to viewport, no to parent container.
So, you are zooming the background image but the position (x, y) will be always be (x, y), positions are not zoomed. You need to recalculate which is the new position.
So you need to calculate new position.
function UpdatePoints(){
var divW = parseInt($('.map-live').css('width').replace('px',''));
var divH = parseInt($('.map-live').css('height').replace('px',''));
var topPosition = (2.477565353101834 / 928) * divH;
var leftPosition = (2.477565353101834 / 928) * divW;
$('.point').css('top', topPosition+'vh');
$('.point').css('left', leftPosition+'vh');
$('.point').css('position', 'absolute');
}
Also, instead using 'vh' I recommend to calculate the px position instead. I have added the already calculated delta_px parameter to UpdatePoints function:
<style>
.point {
position: absolute;
left: 22.99180647678502px;
top: 22.99180647678502px;
width: 10px;
height: 10px;
background-color: red;
border-radius: 50%;
}
</style>
<script>
function UpdatePoints(delta_px){
var position = (delta_px/100)*2.477565353101834;
$('.point').css('top', position+'px');
$('.point').css('left', position+'px');
$('.point').css('position', 'absolute');
}
</script>
Also, here we are calculating the top-left position of the .point element, not the position for the center. As it is a circle, it work fine, but if you use any other shape the position translation should be calculated from its center.
I recommend to do some research about how to translate elements. You can start here:
Calculating relative position of points when zoomed in and enlarged by a rectangle!
Zoom in on a point (using scale and translate)!
How do I effectively calculate zoom scale?!

how to code a circle that changes color when clicked in CSS

I wanna change the color of my circle between red and green when someone clicks on the circle. Both the colors should randomly switch. For Example when someone clicks on a red circle it can switch to green color or stay red and vice versa.(R,R,G,G,G,G,R.....)
The demo currently looks like this. https://jsfiddle.net/sidsingh29/591hfwLd/12/
HTML:
<div id="test"></div>
CSS:
#test {
position:absolute;
height: 55px;
width: 55px;
background-color: red;
border-radius: 50%;
display: inline-block;}
JavaScript + jQuery (edge):
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
});
Just set background property also with left and top based on Math.random() > 0.5 or not:
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
background: Math.random() > 0.5 ? 'red' : 'green', // setting background here
});
});
#test {
position:absolute;
height: 55px;
width: 55px;
background-color: red;
border-radius: 50%;
display: inline-block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="test"></div>
This task cannot be done using entirely CSS, so I have used Javascript and jQuery to do it. Sometimes it can keep the same colour over and over, because I am using random generated numbers to change the colour. I have also put in a timer that times the time you take to click on the circle, in case you were making a reaction tester.
var colour = 1 + Math.floor(Math.random() * 10);
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
function checkNumber(argNumber) {
var result = oddOrEven(argNumber);
if (result == "even") {
$("#circle").css("background-color", "red");
} else {
$("#circle").css("background-color", "green");
};
start = new Date().getTime();
}
$(document).ready(function() {
checkNumber(colour)
});
function makeShapeAppear() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
circle = $('#circle'),
circleWidth = circle.width(),
circleHeight = circle.height(),
heightMax = docHeight - circleHeight,
widthMax = docWidth - circleWidth;
circle.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
display: "block",
});
colour = 1 + Math.floor(Math.random() * 10);
checkNumber(colour)
};
$('#circle').click(function() {
makeShapeAppear();
});
document.getElementById("circle").onclick = function() {
document.getElementById("circle").style.display = "none";
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
document.getElementById("timeTaken").innerHTML = timeTaken + " seconds taken";
}
#circle {
height: 100px;
width: 100px;
border: 0x solid black;
border-radius: 50%;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="circle" onclick="makeShapeAppear()"></div>
<h3>Time Taken = </h3><div id="timeTaken"></div>

Get the current position of moving element - on mouse click

I have an HTML element that is moving from point A to point B.
I want to get the specific position of this element when I click the mouse while the element is moving to point B.
How can I do this?
HTML
<div id="contentContainer">
<div id="thing"></div>
</div>
css
#thing {
border-radius: 50%;
position: absolute;
width: 40px;
height: 40px;
left: 0px;
top: 0px;
background-color: red;
transition: 1s cubic-bezier(.5, .51, .7, .68),
1s cubic-bezier(.5, .51, .7, .68);
}
js
var theThing= document.querySelector("#thing");
var container = document.querySelector("#contentContainer");
//create random position to move the #thing to it
var xPosition = Math.random()*(container.clientWidth-40);
var yPosition = Math.random()*(container.clientHeight-40);
// add the new position
theThing.style.left = xPosition + "px";
theThing.style.top = yPosition + "px";
container.addEventListener("click", function(event) {
//here i want to click to get current specific position of #thing
}
Check this code:
// Code goes here
window.onload = function() {
var theThing = document.querySelector("#thing");
var container = document.querySelector("#contentContainer");
//create random position to move the #thing to it
var xPosition = Math.random() * (container.clientWidth - 40);
var yPosition = Math.random() * (container.clientHeight - 40);
// add the new position
theThing.style.left = xPosition + "px";
theThing.style.top = yPosition + "px";
document.body.addEventListener("click", function(event) {
var pos = getPosition(theThing);
alert(pos.top + "," + pos.left);
});
}
function getPosition(element) {
var x = window.scrollX + element.getBoundingClientRect().left;
var y = window.scrollY + element.getBoundingClientRect().top;
return {
top: x,
left: y
};
}

Get color from distance

I was playing around with JavaScript/canvas and I want my objects color to depend on the distance to its center from current mouse position.This is my current function that gets color every mousemove event:
function getColorFromDistance(node1,node2){
var dist = getDist(node1,node2); //Getting distance;
var cl = (Math.round(255/dist*255)).toString(16); //this needs to be a propper formula
return "#" + cl + cl + cl; //converting to hex
}
Currently I get a blink effect when the distance gets 255.
I need a way to get the colors strength be depended on the distance, so that the further mouse is away from object the more its darken and when mouse is on the objects center its fully white.Well you get the idea.I just need the formula
The formula would be calculate the distance between the two points and get a percentage based on the maximum value (width of canvas/window)
//this would need to be recalulated on resize, but not doing it for demo
var targetElem = document.querySelector("div.x span");
box = targetElem.getBoundingClientRect(),
x = box.left + box.width/2,
y = box.top + box.height/2,
winBox = document.body.getBoundingClientRect(),
maxD = Math.sqrt(Math.pow(winBox.width/2, 2) + Math.pow(winBox.height/2, 2));
document.body.addEventListener("mousemove", function (evt) {
var diffX = Math.abs(evt.pageX-x),
diffY = Math.abs(evt.pageY-y),
distC = Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2)),
strength = Math.ceil(255 - (distC/maxD*255)).toString(16),
color = "#" + strength + strength + strength;
targetElem.style.backgroundColor = color;
});
html, body { height: 100%; }
div.x { position: absolute; top: 50%; left:50%; }
span { display: inline-block; width: 20px; height: 20px; border-radius: 50%; border: 1px solid black; overflow: hidden; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Test</p>
<div class="x"><span> </span></div>

Background position animation on hover

I have a div1 which animates background position on hover direction of mouse by jquery.
But it's working properly. it's going not right direction and I want it to work on every single mouse hover on the div.
Find jsfiddle
code:
$(function() {
$(".mainCont").hover(function(e) {
// $(this).addClass("hoverOnce");
var edge = closestEdge(e.pageX, e.pageY, $(this).width(), $(this).height());
}, function(){
$(this).removeClass('top right bottom left');
// $(this).removeClass("hoverOnce");
});
});
function closestEdge(x,y,w,h) {
var topEdgeDist = distMetric(x,y,w/2,0);
var bottomEdgeDist = distMetric(x,y,w/2,h);
var leftEdgeDist = distMetric(x,y,0,h/2);
var rightEdgeDist = distMetric(x,y,w,h/2);
var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist);
switch (min) {
case leftEdgeDist:
$(".hoverOnce").addClass("left");
case rightEdgeDist:
$(".hoverOnce").addClass("right");
case topEdgeDist:
$(".hoverOnce").addClass("top");
case bottomEdgeDist:
$(".hoverOnce").addClass("bottom");
}
}
function distMetric(x,y,x2,y2) {
var xDiff = x - x2;
var yDiff = y - y2;
return (xDiff * xDiff) + (yDiff * yDiff);
}
The size of this image that you use in the background is 700x500:
http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png
I think that if you add these settings to .mainCont that this will get you the desired result:
width: 700px;
height: 500px;
position: absolute;
For example:
.mainCont {
width: 700px;
height: 500px;
background: url(http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png) no-repeat center center;
transition: all 0.5s ease-in-out;
margin: 100px auto;
position: absolute;
}
Fiddle
Finally, It got solved.
find fiddle demo
$('.mainCont').hover(function(e){
var dir = determineDirection($(this), {x: e.pageX, y: e.pageY});
$(this).addClass('direction_'+dir);
}, function() {
$(this).removeClass('direction_3 direction_1 direction_2 direction_0');
});
function determineDirection($el, pos){
var w = $el.width(),
h = $el.height(),
x = (pos.x - $el.offset().left - (w/2)) * (w > h ? (h/w) : 1),
y = (pos.y - $el.offset().top - (h/2)) * (h > w ? (w/h) : 1);
return Math.round((((Math.atan2(y,x) * (180/Math.PI)) + 180)) / 90 + 3) % 4;
}

Categories

Resources