How to prevent a div from moving up when zooming in - javascript

So for starters this question may seem kind of vague, so I am going to do the best I can to describe my situation.
I have created a html page with adjustable sections (top left, top right, and bottom). There are dividers to adjust the X axis (between the top two sections) and to adjust the Y axis (between the top and bottom section). Everything appears to be working fine, however when I zoom in (using command + on the keyboard), it pushes the text within the bottom section above the Y axis adjuster.
I want instead for the text to be contained in the div beneath the Y axis adjuster and never slide on top of it (even when the screen is resized or zoomed in on).
The above image is what it looks like before zooming in. Notice how the text 'Element 3' is below the green line (Y axis adjuster).
The above image is what it looks like after zooming in. Notice how the text 'Element 3' raises above the green line (Y axis adjuster).
The error should be in the HTML code, not the JS, however I included the JS files for good measure.
I looked all over the internet for a solution but came up empty handed. I have tried simply bootstrapping the page by including the appropriate script tags but that did not work, as well as adjusting various css styles.
html file:
<!doctype html>
<head>
<title>resizer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="Common.js"></script>
<script type="text/javascript" src="resizer.js"></script>
<style>
.element{
border: 1px solid #999999;
border-radius: 4px;
margin: 5px;
padding: 5px;
}
</style>
<script type="text/javascript">
function onresize() {
var element1 = document.getElementById("element1");
var element2 = document.getElementById("element2");
var element3 = document.getElementById("element3");
var ResizerY = document.getElementById("resizerY");
ResizerY.style.top = element3.offsetTop - 15 + "px";
var topElements = document.getElementById("topElements");
topElements.style.height = ResizerY.offsetTop - 20 + "px";
var height = topElements.clientHeight - 32;
if (height < 0)
height = 0;
height += 'px';
element1.style.height = height;
element2.style.height = height;
}
function resizeX(x) {
var element2 = document.getElementById("element2");
element2.style.width =
element2.parentElement.clientWidth
+ document.getElementById('rezizeArea').offsetLeft
- x
+ 'px';
}
function resizeY(y) {
var element3 = document.getElementById("element3");
var height =
element3.parentElement.clientHeight
+ document.getElementById('rezizeArea').offsetTop
- y
;
if ((height + 100) > element3.parentElement.clientHeight)
return;//Limit of the height of the elemtnt 3
element3.style.height = height + 'px';
onresize();
}
var emailSubject = "Resizer example error";
</script>
</head>
<body>
<div id="rezizeArea" style="top=0; bottom=0; right=0; left=0; width:100%; height:100%; overflow:hidden; position: absolute;" class="element">
<div id="topElements" class="element" style="overflow:auto; position:absolute; left: 0; top: 0; right:0;">
<div id="element2" class="element" style="width: 30%; height:10px; float: right; position: relative;">
Element 2
</div>
<div id="resizerX" style="width: 10px; height:100%; background: red; float: right;"></div>
<script type="text/javascript">
resizerX("resizerX", function (e) {
resizeX(e.pageX + 25);
});
</script>
<div id="element1" class="element" style="height:10px; overflow:auto;">
Element 1
</div>
</div>
<div id="resizerY" style="height:10px; position:absolute; left: 0; right:0; background: green;"></div>
<script type="text/javascript">
resizerY("resizerY", function (e) {
resizeY(e.pageY + 25);
});
</script>
<div id="element3" class="element" style="display: inline-block; height:100px; position:absolute; left: 0; bottom: 0; right:0;">
Element 3
</div>
</div>
<script type="text/javascript">
onresize();
</script>
<hr>
</body>
</html>
resizer.js:
function resizer(resizerID, mousemove, cursor) {
consoleLog("resizer(" + resizerID + ")");
var resizer = document.getElementById(resizerID);
resizer.style.cursor = cursor;
resizer.mousemove = mousemove;
resizer.onmousedown = function (e) {
try{
consoleLog("resizer.onmousedown(e)");
document.documentElement.addEventListener('mousemove', resizer.doDrag, false);
document.documentElement.addEventListener('mouseup', resizer.stopDrag, false);
} catch (e) {
ErrorMessage("resizer.onmousedown(...) failed! Your browser does not support this feature. " + e.message);
}
}
resizer.doDrag = function (e) {
if (e.which != 1){
consoleLog("mouseup");
resizer.stopDrag(e);
return;
}
//consoleLog("doDrag(e)");
resizer.mousemove(e);
}
resizer.stopDrag = function (e) {
consoleLog("stopDrag(e)");
document.documentElement.removeEventListener('mousemove', resizer.doDrag, false);
document.documentElement.removeEventListener('mouseup', resizer.stopDrag, false);
}
}
function resizerX(resizerID, mousemove) {
resizer(resizerID, mousemove, "e-resize");
}
function resizerY(resizerID, mousemove) {
resizer(resizerID, mousemove, "n-resize");
}
Common.js:
function MessageElement(Message) {
var element = document.getElementById('Message');
if (element == null) {
alert('ERROR: element Message == null. ' + Message);
return;
}
if (element.innerHTML != Message)
{
//consoleLog('Message: ' + Message);
element.innerHTML = Message + '<hr><div align="center"><input type="button" onclick="javascript: return MessageElement(\'\')" value="Close" style="margin-top:5px;" /></div>';
if (Message == "")
element.style.display = "none";
else element.style.display = "block";
}
}
function ErrorMessage(message, emailMe) {
consoleError(message);
//http://www.htmlhelp.com/reference/html40/entities/special.html
var body;
if (emailMe != false) {
body = message;
body = body.replace(/\n/g, "%0D%0A");
body = body.replace(/ /g, "%20");
body = body.replace(/"/g, "%22");
body = body.replace(/&/g, "%26");
}
message = message.replace(/</g, '<');
message = message.replace(/>/g, '>');
message = message.replace(/\n/g, '<BR>');
if (emailMe != false) {
//http://www.rapidtables.com/web/html/mailto.htm
if (typeof myEmail == 'undefined')
myEmail = "XXX";
message += "<BR><BR><a href=\"mailto:" + myEmail + "?subject=" + emailSubject + "&body=" + body + "\" >Email me about problem</a>"
}
MessageElement('<FONT style="color: red; background-color: white">ERROR: ' + message + '</FONT>');
}
function consoleLog(message) {
try{
console.log(message);//Do not works in WP
} catch(e) {
}
}
function consoleError(msg)
{
try
{
console.error(msg);
} catch(e) {
// alert(msg);
}
}

Related

How to use vanilla script to bounce elements from each other

I've tried adding the top and left changes, and margin (with different positioning changes too) changes to each element if one approaches another but only the margin change works once. Is there a way to make them work more consistently?
This is where I've used a function to add the event listeners:
var three = document.getElementById('three');
var test = document.getElementById('test');
var two = document.getElementById('two');
var obj = null;
function testmovea(object, event) {
obj = document.getElementById(object.id);
document.addEventListener("mousemove", move);
}
function move(event) {
obj.innerText = event.clientX + ' ' + event.clientY;
obj.style.position = 'absolute';
obj.style.left = event.clientX + "px";
obj.style.top = event.clientY + "px";
three.addEventListener('mouseover', borders);
three.addEventListener('mouseleave', bordersOff);
two.addEventListener('mouseenter', bTwo);
test.addEventListener('mouseenter', bTest);
two.addEventListener('mouseleave', bTwoReset);
test.addEventListener('mouseleave', bTestReset);
document.addEventListener("mouseup", stopMove);
}
function bTwo() {
two.style.margin = "10%";
}
function bTwoReset() {
two.style.margin = "0%";
}
function bTest() {
test.style.margin = "10%";
}
function bTestReset() {
test.style.margin = "0%"
}
This is the mouse stop event I use:
function stopMove() {
document.removeEventListener('mousemove', move);
test.removeEventListener('mouseover', bTest);
two.removeEventListener('mouseover', bTwo);
test.removeEventListener('mouseleave', bTestReset);
two.removeEventListener('mouseleave', bTwoReset);
}
the testmovea function relies on a onmousedown property defined for a DOM element of the page
Update:
I've managed to get it to partially work:
function collide(el1, el2) {
if(twoBoundX >= threeBoundY || threeBoundY >= twoBoundX) {
two.style.margin = + event.clientX + "px";
two.style.margin = + event.clientY + "px";
}
}
where twoBoundX and threeBoundY are getBoundingClientRect() of the respective elements
Here's the full code snippet:
<html>
<head>
<style type="text/css">
#two {
border: 1px solid black;
padding: 1%;
margin: 1%;
margin-top: 10%;
width: 10%;
}
#three {
border: 1px solid black;
padding: 1%;
margin-top: 2%;
}
</style>
</head>
<body>
<div id="two" onmousedown="testmovea(this, event)" onclick="currentTwoPos()">
stop movement
</div>
<div id="three" onmousedown="testmovea(this)">Expand div</div>
<div style="height: 30%" id="two" contenteditable="true">
some contenteditable</div>
</body>
<script>
var three = document.getElementById('three');
var two = document.getElementById('two');
const twoBound = two.getBoundingClientRect();
const threeBound = three.getBoundingClientRect();
var threeBoundX = threeBound.x;
var threeBoundY = threeBound.y;
var twoBoundX = twoBound.x;
var twoBoundY = twoBound.y;
var twoBoundBottom = null;
var twoBoundTop = null;
var obj = null;
function collide(el1, el2) {
if(twoBoundX >= threeBoundY || threeBoundY >= twoBoundX) {
two.style.left = event.clientX + "px";
two.style.top = event.clientY + "px";
three.style.left = event.clientX + "px";
three.style.top = event.clientY + "px";
}
}
function testmovea(object, event) {
obj = document.getElementById(object.id);
document.addEventListener("mousemove", move);
}
function move(event) {
obj.innerText = event.clientX + ' ' + event.clientY;
obj.style.position = 'absolute';
obj.style.left = event.clientX + "px";
obj.style.top = event.clientY + "px";
two.addEventListener('mouseover', collide);
three.addEventListener('mouseover', collide);
document.addEventListener("mouseup", stopMove);
}
function stopMove() {
mousemove = false;
document.removeEventListener('mousemove', move);
three.removeEventListener('mouseover', collide);
two.removeEventListener('mouseover', collide);
}
</script>
</html>
collision detection
You need to define a function that checks whether two of your shapes collide. If you only have rectangles whose vertex are parallel with the OX and OY vertexes, it would look like this:
function areColliding(r1, r2) {
return !(
(r1.x > r2.x + r2.w) ||
(r1.x + r1.w < r2.x) ||
(r1.y > r2.y + r2.h) ||
(r1.y + r1.h < r2.y)
);
}
Of course, if some rotation or even other shapes are involved into your problem, then you need to extend/adjust the collision detector accordingly.
a shared function
You need to create a function that would receive the current status of the elements and the move that happens. It would look like this:
function handleMove(currentPositions, proposedPositions) {
while (!validPositions(proposedPositions)) {
proposedPositions = generateNewPositions(currentPositions, handleCollisions(proposedPositions));
}
refreshUI(proposedPositions);
}
currentPositions is the set of positions your elements currently have
proposedPositions is the set of positions your elements are going to have if there are no collisions
validPositions checks for any pair of shapes that would collide and returns true if none of those pair collide and false if at least one such pair collides
proposedPositions is being refreshed while there are still collisions
generateNewPositions is your handler for collision-based changes
handleCollisions effectuates changes to avoid collision
refreshUI refreshes the UI
event handling
your mouse events should handle change updates by loading all the positions of your elements and calling this shared functionality.
Note: If you have further problems, then you might need to create a reproducible example so we could see your exact structure, styling and code as well.
<html>
<head>
<style type="text/css">
#two {
border: 1px solid black;
width: 10%;
padding: 1%;
margin: 1%;
margin-top: 10%;
}
#three {
border: 1px solid black;
padding: 1%;
margin-top: 2%;
}
</style>
</head>
<body>
<div id="two" onmousedown="testmovea(this, event)" style="position: relative;">
stop movement
</div>
<div id="three" onmousedown="testmovea(this)" style="position: relative;">Expand div</div>
<!--<div style="height: 30%; position: relative;" id="two" contenteditable="true">
some contenteditable</div>-->
</body>
<script>
var three = document.getElementById('three');
var two = document.getElementById('two');
let moveStarted = false;
function collide() {
const first = two.getBoundingClientRect();
const second = three.getBoundingClientRect();
if (!(
(first.x + first.width < second.x) ||
(second.x + second.width < first.x) ||
(first.y + first.height < second.y) ||
(second.y + second.height < first.y)
)) {
two.style.left = event.clientX + "px";
two.style.top = event.clientY + "px";
three.style.left = event.clientX + "px";
three.style.top = event.clientY + "px";
}
}
function testmovea(object, event) {
obj = document.getElementById(object.id);
if (!moveStarted) {
document.addEventListener("mousemove", move);
moveStarted = true;
}
}
function move(event) {
//obj.innerText = event.clientX + ' ' + event.clientY;
obj.style.left = event.clientX + "px";
obj.style.top = event.clientY + "px";
if (!obj.classList.contains("dragged")) obj.classList.add("dragged");
collide(obj);
}
function stopMove() {
mousemove = false;
if (moveStarted) {
document.removeEventListener('mousemove', move);
moveStarted = false;
}
}
document.addEventListener("mouseup", stopMove);
</script>
</html>

How to apply a Javascript animation function to multiple images in for loop? [duplicate]

This question already exists:
How to apply a Javascript animation function to multiple elements in for loop? [duplicate]
Closed 10 months ago.
I am trying to apply animation to all of the images created in a for loop without manually doing it, but none of the images created in the for loop are showing any animation, I have tried in multiple ways such as using forEach and a regular for loop paired with querySelectorAll. When I tried to fix my problem with those methods, it either only affected the first image from the for loop or nothing happened at all.
Essentially, what I want is to make it so the 10 images created prior in a for loop can have the same animation as the first image that is being animated across the screen. I also want the other images created to have the same functionality as the first image, when the image is clicked, the click counter should also work similar to that of the first image sliding across the screen. Please help.
Full code is linked here: https://code.sololearn.com/Wwdw59oenFqB
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
zoom: 25%
}
.circle {
display: block;
background: black;
border-radius: 100%;
height: 100px;
width: 100px;
background: radial-gradient(circle at center,#31f541, #000);
}
.container {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.circle-image{
z-index: 2;
position: absolute;
margin-left: 50%;
margin-top: 50vh;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="container">
<img id = "firstImage" style = "height: 1000px; width: 1000px;" onclick = "change(); clickCounter(); animate(); saveData();"class="circle-image" src="data:image/jpe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tMYYVcfqzmlSrBHSLjjPcD7ml+HT1NKlWCf/2Q==">
<img id = "secondImage" style = "height: 1000px; width: 1000px;" onclick = "animate();"class="circle-image" src="https://en.meming.world/images/en/thumb/e/e2/Crying_Cat_screaming.jpg/300px-Crying_Cat_screaming.jpg">
<p style = "transform: scale(10, 10);"id = "clicker">Kitten has been pat: <a id="clickCounter">0</a> times in <a id = "timeCounter">0</a> seconds</p>
<figure class="circle"></figure>
</div>
<button onclick = "saveData();"id = "saveButton">Load progress</button>
<script>
const cats = [];
for(i = 0; i < 10; i++){
var img = document.createElement("img");
img.setAttribute("src", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAIQAWQMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAGAAIDBAUBB//EADsQAAIBAwMCAwYFAgMJAQAAAAECAwAEEQUSITFBBhNRIlJhcYGRFDJCofDB0SMzsRUkJVNiY5Ki4Qf/xAAYAQADAQEAAAAAAAAAAAAAAAABAgMABP/EAB8RAAMBAAMBAQEBAQAAAAAAAAABAhEDEiExQTJRBP/aAAwDAQACEQMRAD8AMAM1V1S7/BRI7ZwzbeKu45rJ8VRFtIaRR/lOrfTp/Wov4VlbSLlpeRXEWVkBPcHgj6VaAyOtCen3BghWd2AJ5OWxgVonUHaPzbJtxUZaPggj1GKDrqtKPj1+G4qmuiM9axG1SdUG4AEruxVaLVLozZ39DgCpP/olGXBRtahothqSBL+yguF/7iA4+vah+f8A/N/DLsXNk8WeoSdwPtmtE6pdkP5YDBf3NUbvU7gkrdzbe+wcAf3p5503iA+F/pUHhjwrpkga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JgdIwQpJIzmvRJdAifkqMH4VFF4e8sso8t0I9jd1X4fGlcMZVgBtf3Vn5cm0lCeR8KJLOeaeZCkDbCc4PpW7e+GYruzeJAqyFPZOOAan0eNR5azKsMxGDGR3HBx602NIGpsWnJOm1WiIY84AohtYliVuPbJ5NPCqFXaOi8/OuIecY6E5opf6Bseo9nA64610bcZPYenNNBw23BIHHSub8MQM/amARTRK+SwBPc5HpUP4KP3D9hVmTjlenyrm0f82sYqsxCkjt/enI29sN6fz/AFpUqBjp/Lk9hxXUUEtSpVjD04OMnjpUnBxkClSogOljj5iuRHJI90ZFcpVjDixJJPf+tMYYVcfqzmlSrBHSLjjPcD7ml+HT1NKlWCf/2Q==");
img.className = "catSwarm"
img.addEventListener('click', function handleClick(event) {
change(); clickCounter();
});
img.addEventListener('load', function handleClick(event) {
})
document.body.appendChild(img);
cats.push(img)
}
let clicks = 0;
function clickCounter() {
clicks += 1;
document.getElementById("clickCounter").innerHTML = clicks;
if (clicks != 10) {
}
else {
alert("Kitten has been pet 10 times")
}
};
let time = 0;
function timeCounter() {
time+=1
document.getElementById("timeCounter").innerHTML = time;
setTimeout(timeCounter, 1000)
if(time != 10) {
}
else{
setTimeout(function() {
alert ("Kitten has been pet " + clicks + " times in " + time + " seconds" + " with a whopping pats per second rate of " + clicks/time + "!")
}, 10);
}}
timeCounter();
function change() {
if(document.getElementById("firstImage").style.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAIQAWQMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAGAAIDBAUBB//EADsQAAIBAwMCAwYF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L/JHGGOeppOZoeE0bemwiKIscgsc+1U7MMhTw1MUlY1PcDmm7lkYnjdQn4CvWPCnII4GccCltP8amiR4c7/AGhjAIqT8RH/ANVE2HiUIwcjrU+4AVDHx0p7da5ygS6BeQeQIyR5oOMN0xT/ABLJbyQJAux5GOSVbO2hV8gcVbsruNxtc4ZabfDYX4lYSAxkHC+yDWxps8i7AwXaFOD9qyIYDv3BsjpkelXYUdME42AYqiYrG6neb9Ri3jlDkEfGiLSbgOVXZtLHAz3rFg038TMHcDg8UV6ZB/iKoHC0v1+h3zw1BwowR8eaYVjyGxjmpSVK8fSoZVLDk8+oqgguMn0x9qZti979/wD5UYk8olXBYetP/FL6j7GgE8pj0qUD8pqOazlTOUOMelejDT4wv5ail0uJ/wBPwxS9A6eayo3OQRUJgdIwQpJIzmvRJdAifkqMH4VFF4e8sso8t0I9jd1X4fGlcMZVgBtf3Vn5cm0lCeR8KJLOeaeZCkDbCc4PpW7e+GYruzeJAqyFPZOOAan0eNR5azKsMxGDGR3HBx602NIGpsWnJOm1WiIY84AohtYliVuPbJ5NPCqFXaOi8/OuIecY6E5opf6Bseo9nA64610bcZPYenNNBw23BIHHSub8MQM/amARTRK+SwBPc5HpUP4KP3D9hVmTjlenyrm0f82sYqsxCkjt/enI29sN6fz/AFpUqBjp/Lk9hxXUUEtSpVjD04OMnjpUnBxkClSogOljj5iuRHJI90ZFcpVjDixJJPf+tMYYVcfqzmlSrBHSLjjPcD7ml+HT1NKlWCf/2Q==") {
document.getElementById("firstImage").src = "https://en.meming.world/images/en/thumb/e/e2/Crying_Cat_screaming.jpg/300px-Crying_Cat_screaming.jpg";
}
else {document.getElementById("firstImage").style.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc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lC/leRqkaISuX5FFkcqXUnmMhLMv5sftWPrlt+GniuFH6wf3pV4U+o39PnARsDlQCKJLOU+WFTvk5+FClo+xQ6+7RBplyrxxjncw+wrokjSI/Flv59pboz4BuE/YE0zTIwqqXVmPQNU2vXURezhboXLf8AqamsvL/JHGGOeppOZoeE0bemwiKIscgsc+1U7MMhTw1MUlY1PcDmm7lkYnjdQn4CvWPCnII4GccCltP8amiR4c7/AGhjAIqT8RH/ANVE2HiUIwcjrU+4AVDHx0p7da5ygS6BeQeQIyR5oOMN0xT/ABLJbyQJAux5GOSVbO2hV8gcVbsruNxtc4ZabfDYX4lYSAxkHC+yDWxps8i7AwXaFOD9qyIYDv3BsjpkelXYUdME42AYqiYrG6neb9Ri3jlDkEfGiLSbgOVXZtLHAz3rFg038TMHcDg8UV6ZB/iKoHC0v1+h3zw1BwowR8eaYVjyGxjmpSVK8fSoZVLDk8+oqgguMn0x9qZti979/wD5UYk8olXBYetP/FL6j7GgE8pj0qUD8pqOazlTOUOMelejDT4wv5ail0uJ/wBPwxS9A6eayo3OQRUJgdIwQpJIzmvRJdAifkqMH4VFF4e8sso8t0I9jd1X4fGlcMZVgBtf3Vn5cm0lCeR8KJLOeaeZCkDbCc4PpW7e+GYruzeJAqyFPZOOAan0eNR5azKsMxGDGR3HBx602NIGpsWnJOm1WiIY84AohtYliVuPbJ5NPCqFXaOi8/OuIecY6E5opf6Bseo9nA64610bcZPYenNNBw23BIHHSub8MQM/amARTRK+SwBPc5HpUP4KP3D9hVmTjlenyrm0f82sYqsxCkjt/enI29sN6fz/AFpUqBjp/Lk9hxXUUEtSpVjD04OMnjpUnBxkClSogOljj5iuRHJI90ZFcpVjDixJJPf+tMYYVcfqzmlSrBHSLjjPcD7ml+HT1NKlWCf/2Q=="> {
}
}}
function saveData() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.querySelector("p").innerText = "Kitten has been pat: " + localStorage.clickcount + " times in " + time + " seconds";
}
}
const fps = 25;
let image = document.querySelector("img");
let angle = Math.PI / 2;
//store the previous time the animate function last fired
let prevTimeArg;
function animate(currentTimeParam){
if (prevTimeArg != null) {
angle += (currentTimeParam - prevTimeArg) * 0.004;
}
// Setting the previous time to the time the function currently fires
prevTimeArg = currentTimeParam ;
image.style.top = (Math.tan(angle) * 150) + "px";
image.style.left = (Math.tan(angle) * 150) + "px";
image.style.height = (Math.cos(angle) * 1000) + "px";
image.style.width = (Math.cos(angle) * 1000) + "px";
setTimeout(() => {
requestAnimationFrame(currentTime => animate(currentTime));
}, 0 / fps)}
for (i = 0; i < cats.length; i++) {
window.requestAnimationFrame(animate);
}
</script>
</body>
</html>
Thank you in advance..

How to get the width on where the mouse clicks a div?

I would like to use HTML/CSS/JS to have a <div> change its colour only up to a certain width. This certain length depends on where it is clicked inside the <div>.
Example:
I would give code, but it would just be of a <div>.
I don't know how to use CSS/JS to detect where the mouse clicks on <div> (i.e. on what width size).
You can achieve this like this
function changeWidth(event) {
let outerDiv = document.getElementById('outerDiv');
document.getElementById('innerDiv').style.width = event.clientX-outerDiv.offsetLeft+'px';
}
#outerDiv {
width: 400px;
height:200px;
border: 1px solid black;
}
#innerDiv {
width: 0px;
height: 200px;
background-color: red;
}
<div id = 'outerDiv' onclick = 'changeWidth(event)'>
<div id = 'innerDiv' ></div>
</div>
You have keep in check the position of the outerbox which you can get by using el.offSetLeft
A simple approach using background-image to create the color.
document.querySelector(".box").addEventListener("click", function(e){
var position = e.clientX - this.getBoundingClientRect().left;
this.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
});
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box"></div>
e.clientX is the position relative to the window. So you can use the left position of the div from .getBoundingClientRect().left and subtract it to get the exact click position.
If you need this to work for multiple divs:
1) Add inline onclick to each <div>
function colourBackground (e, div) {
var position = e.clientX - div.getBoundingClientRect().left;
div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
};
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box" onclick="colourBackground(event, this)"></div>
<div class="box" onclick="colourBackground(event, this)"></div>
<div class="box" onclick="colourBackground(event, this)"></div>
Or 2) Use a forEach loop to add a click event to each <div>
document.querySelectorAll(".box").forEach(function(div) {
div.addEventListener("click", function(e){
var position = e.clientX - div.getBoundingClientRect().left;
div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
});
})
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
I would do like:
//<![CDATA[
/* js/external.js */
let get, post, doc, html, bod, nav, M, I, mobile, S, Q, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
// you can ignore most of the above code (but it's useful, so keep it) - put below on a separate page on another load - except the load end
const block = I('block'), colorStyle = block.firstChild.style;
let down = false;
function colorIt(e){
if(down)colorStyle.width = e.clientX-e.target.offsetLeft+'px';
}
function touchMode(){
block.onmousedown = block.onmousemove = undefined;
block.ontouchstart = e=>{
down = true; colorIt(e.touches[0]);
}
block.ontouchmove = e=>{
colorIt(e.touches[0]);
}
}
function mouseMode(){
block.ontouchstart = block.ontouchmove = undefined;
block.onmousedown = e=>{
down = true; colorIt(e);
}
block.onmousemove = colorIt;
}
block.onclick = ()=>{
down = false;
}
if(mobile){
touchMode();
}
else{
mouseMode();
}
}); // load end
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
#block{
width:200px; height:75px; background:#fff; border:1px solid #000; cursor:pointer;
}
#block>div{
width:0; height:100%; background:green;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='block'><div></div></div>
</div>
</body>
</html>
Interesting question.
First, use this to get the location of your div: https://stackoverflow.com/a/10445639/11444910
Then get your mouse position on click: https://stackoverflow.com/a/23744762/11444910
Now that you can tell where your div is and where your mouse is when clicked, you should be able to tell if you are clicking inside of the div or not. Then it's a matter of applying the Y location of your mouse to the div, and using that to inform the color change.

Creating Circles(div) and appending it to div#canvas

I am trying to create new circles as my pen hovers on window.
I am having issues where I cannot add circles to the page. It just hovers around. How would i be able to modify my code to add circles as it hovers.
<!doctype html>
<html>
<head>
<title> JavaScript Environment: Project </title>
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#canvas {
background-color: yellow;
width: 100%;
height: 100%;
}
.pen {
position: absolute;
background-color: lightblue;
width: 10px;
height: 10px;
border-radius: 5px;
}
</style>
<script>
window.onload = function() {
function Circle(x, y) {
this.x = x;
this.y = y;
}
var canvas = document.getElementById("canvas");
canvas.onmousedown = function() {
mouseDown();
};
canvas.onmouseup = function() {
mouseUp()
};
canvas.onmousemove = function() {
mouseMove(event)
};
function mouseDown (){
console.log ("mouse down");
}
function mouseUp (){
console.log ("mouse up");
}
function mouseMove(e) {
var canvas = document.getElementById("canvas");
var pen = document.createElement("div");
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
pen.setAttribute("class", "pen");
pen.style.left = x + "px";
pen.style.top = y + "px";
document.getElementById("canvas").innerHTML = coor;
canvas.appendChild(pen);
addCircles(x, y);
console.log("location # " + x + " : " + y);
}
function addCircles(x, y) {
var canvas = document.getElementById("canvas");
var circle = document.createElement("div");
circle.setAttribute("class", "pen");
circle.style.left = x + "px";
circle.style.top = y + "px";
canvas.appendChild(circle);
}
canvas.addEventListener("mouseMove", mouseMove, false);
};
</script>
</head>
<body>
<div id="canvas"></div>
</body>
</html>
The problem is in the line document.getElementById("canvas").innerHTML = coor;
Try adding a span <span id="canvasText"></span> inside of your canvas div and then changing the above line to document.getElementById("canvasText").innerHTML = coor;.
As it stands, you "reset" the contents of the canvas every time the mouse moves, so the circles are instantly removed from it. Reset only the span inside the canvas to keep the circles around.

javascript for draw rectangle over a image

I was doing a project on php with java script.I was try to draw a rectangle over a image using javascript.The rectangle can draw any where of the image with any size as compare with image size and also display the co ordinate of drawing rectangle.Please any one help me...I was tried different ways.....
<STYLE>
#rubberBand {
position: absolute;
visibility: hidden;
width: 0px; height: 0px;
border: 2px solid red;
}
</STYLE>
</HEAD>
<BODY>
<img name="myImage" id="myImage" src="a.jpg">
<DIV ID="rubberBand"></DIV>
<SCRIPT>
var IMG;
function startRubber (evt) {
if (document.all) {
var r = document.all.rubberBand;
r.style.width = 0;
r.style.height = 0;
r.style.pixelLeft = event.x;
r.style.pixelTop = event.y;
r.style.visibility = 'visible';
IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
}
else if (document.getElementById) {
// firefox
evt.preventDefault();
var r = document.getElementById('rubberBand');
r.style.width = 0;
r.style.height = 0;
r.style.left = evt.clientX + 'px';
r.style.top = evt.clientY + 'px';
r.style.visibility = 'visible';
r.onmouseup = stopRubber;
}
IMG.onmousemove = moveRubber;
}
function moveRubber (evt) {
if (document.all) { // IE
var r = document.all.rubberBand;
r.style.width = event.x - r.style.pixelLeft;
r.style.height = event.y - r.style.pixelTop;
}
else if (document.getElementById) { // firefox
var r = document.getElementById('rubberBand');
r.style.width = evt.clientX - parseInt(r.style.left);
r.style.height = evt.clientY - parseInt(r.style.top);
}
return false; // otherwise IE won't fire mouseup :/
}
function stopRubber (evt) {
IMG.onmousemove = null;
}
function cancelDragDrop()
{
window.event.returnValue = false;
}
IMG = document.getElementById('myImage');
IMG.onmousedown = startRubber;
IMG.onmouseup = stopRubber;
</SCRIPT>
You need a wrapper so you can absolutely-position elements inside. The dimensions will vary, depending on your photo and where you want the box.
HTML:
<div class="wrapper">
<img src="...." />
<div class="box"></div>
</div>
CSS:
.wrapper {
position:relative;
}
.box {
position:absolute;
top:10px;
left:10px;
width:50px;
height:50px;
border:2px solid #ffffff;
background-color:transparent
}

Categories