How to edit the "hitbox" of an image using getBoundingClientRect(); - javascript

I have an image floating around a page and I need to make it so when it hits something, something happens. While doing this, I used the getBoundingClientRect(); in order to find the position of the image to find when it hits. Annoyingly, the position of the image is about 100 px off (not exact) from what it shows online. How do I fix this?
I've already attempted to change this height/width elements of the image, it hasn't worked.
<!dOcTyPe HtMl>
<meta name="viewport" content="width=device-width, initial-
scale=1">
<style>
span{
height: 25px;
width: 25px;
border-radius: 13px;
background-color: white;
display: inline-block;
position: fixed;
}
#myDiv{
max-width: 100px;
}
#eve{
margin-top: 0px;
margin-left: 0px;
background-color: white;
height: 300px;
border-radius: 25px;
border: 3px gray solid;
}
.body{
background-color: black;
}
.circimg{
height: 25px;
width: 25px;
background: none;
}
#dot{
position: absolute;
top: 50px;
}
</style>
<body class="body">
<audio id="audio"
src="http://www.willmargulies.com/gimn_rf_t3-
[AudioTrimmer.com].mp3" autoplay="false" ></audio>
<img id="dot" class="circimg" top="0px"
src="https://www.willmargulies.com/PinClipart.com_label-
clipart_183729.png">
<script>
function playSound() {
var sound = document.getElementById("audio");
sound.play();
}
</script>
<script>
document.getElementsByTagName("img").top = "50px";
var div = document.getElementById("dot");
var x = 0
var lr = 1;
var concise = 1;
var y = 0;
var he = window.innerWidth - 50;
var inwit = window.innerWidth - 30;
var inhei = window.innerHeight - 15;
function func(){
div.style.top = y + "px";
div.style.left = x + "px";
if(div.style.left === he + "px"){lr = 0;}
if(div.style.left === "20px"){lr = 1;}
if(lr === 1){x = x + 1}else{x = x - 1}
if(div.style.top === inhei + "px"){concise = 0;}
if(div.style.top === "15px"){concise = 1;}
if(concise === 1){y = y + 1}
else{y = y - 1}
if(div.style.left === "0" && div.style.top === "0px"){
playSound();
}
var span1 = document.getElementById("dot");
var button = document.getElementById("eve");
var rect1 = span1.getBoundingClientRect();
var rect2 = button.getBoundingClientRect();
var overlap = (rect1.right == rect2.left ||
rect1.left == rect2.right ||
rect1.bottom == rect2.top ||
rect1.top == rect2.bottom)
if(overlap){
alert("holy bjesus")
}
}
setInterval(func, 5);
</script>
<center>
<button id="eve" class="" onClick="if(touches(span, btn))
{alert('k');}">Putin The Bootin</button>
</center></body>

Related

JavaScript not placing object in correct mouse position

I have a stormTrooper characters randomly placed around my circle called deathStar. I am trying to make my stormTroopers place in the location that my mouse clicks once they have already been clicked. But instead they are placing in random locations. I'm still having problems grasping the concept of getBoundingClientRect() and offset. I thought adding them together and subtracting from mouseClick would be the solution. I'm also open to any other advice for this project. The area I'm having problems with is the mouseDown event listener.
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = window.scrollX + deathStar.getBoundingClientRect().left; // top left X
const y1 = window.scrollY + deathStar.getBoundingClientRect().top; // top left Y
const x2 = window.scrollY + deathStar.getBoundingClientRect().right; // bottom right X
const y2 = window.scrollY + deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
var xposition = (e.clientX - stormTrooperChecker.getBoundingClientRect().left + stormTrooperChecker.offsetLeft);
var yposition = (e.clientY - stormTrooperChecker.getBoundingClientRect().top + stormTrooperChecker.offsetTop);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) > pTheoremC(radius) || pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>
The translate positioning is relative to the Death Star element's center, so I updated that.
translate does not affect offsetTop/Left, so your "in Death Star" logic was failing. I fixed that.
Also, you do not need to adjust for the scroll position (comes into effect only when scrolled). I fixed that.
Lastly, I had to put in some code in the handler to calculate the new midpoint of the Death Star element, as you only calculated it on initialization (it should be recalcuated on every use).
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
var xposition = (e.clientX - midPointX);
var yposition = (e.clientY - midPointY);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(yposition, xposition) > pTheoremC(radius) || pTheoremAB(yposition, xposition) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>

Optimized solution for filling entire page with DIVs

I want to have a webpage whose entire viewable area is filled with divs. I am currently using the following code:
var wh= window.innerHeight;
var ww= window.innerWidth;
var area= wh * ww;
i= 1;
while(area > 0) {
document.getElementById("map").innerHTML+= "<div class='map-box' id='box" + i + "'></div>";
area-= 20 * 20;
i+=1;
}
.map-box {width: 20px; height: 20px; border-color: grey; border-width: 1px; border-style: solid; display: inline-block; margin: 0; padding: 0;}
<body>
<div id='map'></div>
</body>
If you try to use this code is your browser, you will see that there are two flaws in this:
First, it creates too many extra divs which go outside the viewable screen.
Second, this code is also somewhat slow.
Can someone here help me address both of these flaws and also optimize this code for faster performance?
1.) That <div> is not 20x20, because of the border:
let d = document.getElementById("test");
console.log(d.offsetWidth, d.offsetHeight);
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
<div id="test" class="map-box"></div>
2.) There's still the default border around the entire thing, and also some spacing between the lines:
var wh = window.innerHeight;
var ww = window.innerWidth;
var area = wh * ww;
i = 1;
while (area > 0) {
document.getElementById("map").innerHTML += "<div class='map-box' id='box" + i + "'></div>";
area -= 22 * 22; // hardcoding is not that nice
i += 1;
}
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
#map {
background: blue;
}
body {
background: red;
}
<div id='map'></div>
3.) Half cells are evil, so the width/height should be rounded downwards to a multiple of 22. Suddenly the grid is becoming an actual rectangle, at least in Chrome/Edge. The between-spacing is still a problem:
var wh = Math.floor(window.innerHeight / 22) * 22; // <--!!
var ww = Math.floor(window.innerWidth / 22) * 22; // <--!!
var area = wh * ww;
i = 1;
while (area > 0) {
document.getElementById("map").innerHTML += "<div class='map-box' id='box" + i + "'></div>";
area -= 22 * 22;
i += 1;
}
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
#map {
background: blue;
}
body {
background: red;
margin: 0; // <--!!
padding: 0; // <--!!
}
<div id='map'></div>
I don't actually know how to use line-height properly, this one works on my machine with my scaling/DPI, in Chrome/Edge, but that's all I can say about it. The 22-s are cut back, area now simply stores the number of <div>s to generate.
var wh = Math.floor(window.innerHeight / 22);
var ww = Math.floor(window.innerWidth / 22);
var area = wh * ww;
i = 1;
while (area > 0) {
document.getElementById("map").innerHTML += "<div class='map-box' id='box" + i + "'></div>";
area--;
i += 1;
}
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
#map {
line-height: 0.6;
}
body {
margin: 0;
padding: 0;
}
<div id='map'></div>
Instead of accessing dom element's inner html on each loop iteration - do it once after the loop with "prepared" data to set there
const wh = window.innerHeight;
const ww = window.innerWidth;
let area = wh * ww;
i = 1;
const ms = Date.now();
const divs = [];
while (area > 0) {
divs.push("<div class='map-box' id='box" + i + "'></div>");
area -= 20 * 20;
i += 1;
}
document.getElementById("map").innerHTML = divs.join("");
console.log("done fast", Date.now() - ms);
js fiddle with comparison https://jsfiddle.net/aL7zqwy9/
The final solution, not ideal but
<html>
<body>
<div id='map'></div>
</body>
<style>
body {
margin: 0;
padding: 0;
/* Overflow appears when last row is added and shrinks the "width" */
overflow-y: hidden;
}
#map {
/* To exclude space between rows */
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.map-box {
width: 20px;
height: 20px;
border: 1px solid grey;
display: block;
margin: 0;
padding: 0;
/* So border thickness will not affect element size */
box-sizing: border-box;
}
</style>
<script>
const cellSize = 20; // px
const wh = window.innerHeight;
const ww = window.innerWidth;
// not always divisible by cell size without a remainder
const columnsCount = Math.floor(ww / cellSize);
const rowsCount = Math.floor(wh / cellSize);
const cellsCount = columnsCount * rowsCount;
console.log(`wh: ${wh}, ww: ${ww}, cols: ${columnsCount}, rows: ${rowsCount}`);
const divs = [];
for (let i = 0; i < cellsCount; i++) {
divs.push(`<div class='map-box' id='box${i}'></div>`);
}
document.getElementById("map").innerHTML = divs.join("");
</script>
</html>

How to stop image after the last image appears?

I have Created Image Slider with 2 buttons Next and Previous, the buttons are working correctly like when last image comes slider gets stop but on sliding the image slider with the help of mouse problem is that the slider continue going to left and right with empty space.
JavaScript:-
var leftFrom = 10;
var scrollPosition = 0;
var scrollOffSet = 400;
$(document).ready(function () {
function PhotoGallery() {
$('#thumbs_container').css('width', '100%');
$('#thumbs_container').css('position', 'absolute');
$('#thumbs_container').css('overflow-y', 'hidden');
//$('#thumbs_container').css('left', '1.9%')
$('#thumbs_container').css('float', 'left');
$('#thumbs_container').css('height', '215px')
//I have Created image Slider Dynamically:-
//var container = document.getElementById('thumbs_container');
var buttoncontainer = document.getElementById('inner');
var nextButton = document.createElement('button');
nextButton.className = 'next';
nextButton.innerHTML = '❯';
//container.appendChild(nextButton);
buttoncontainer.appendChild(nextButton);
//Next Button Functionality:-
var next = function () {
console.log("Next Clicked" + " " + $('#thumbs_container').width());
if ((scrollPosition + scrollOffSet) < $('#thumbs_container').width()) {
scrollPosition = scrollPosition + scrollOffSet;
$('#thumbs_container').animate({ scrollLeft: scrollPosition }, 750);
}
else {
if ((scrollPosition + scrollOffSet) > $('#thumbs_container').width())
scrollPosition = scrollPosition + scrollOffSet;
$('#thumbs_container').animate({ scrollLeft: scrollPosition }, 750);
}
}
//Previous Button Functionality:-
var prevButton = document.createElement('button');
prevButton.className = 'previous';
prevButton.innerHTML = '❮';
//container.appendChild(prevButton);
buttoncontainer.appendChild(prevButton);
var previous = function ()
{
console.log('Clicked Left');
var leftOffSet = $('#thumbs_container').scrollLeft();
console.log("leftOffset" + " " + leftOffSet);
if ((leftOffSet - scrollOffSet) > 0) {
scrollPosition = scrollPosition - scrollOffSet;
$('#thumbs_container').animate({ scrollLeft: scrollPosition }, 750);
} else {
if (leftOffSet > 0)
$('#thumbs_container').animate({ scrollLeft: 0 }, 750);
}
}
//Adding Images Dynamically Into Slider:-
this.imagecreate = function (name, src) {
var container = document.getElementById('thumbs_container');
var img = document.createElement('img');
img.src = src;
img.alt = name;
img.className = 'thumb';
img.style.width = '300px';
img.style.height = '150px';
img.style.position = 'absolute';
img.style.left = leftFrom + 'px';
leftFrom = leftFrom + 310;
container.appendChild(img);
}
//Adding Videos Dynamically Into Slider:-
this.videocreate = function (src, type) {
var container = document.getElementById('thumbs_container');
var video = document.createElement('video');
var source = document.createElement('source');
source.src = src;
source.type = type;
video.autoplay = true;
video.loop = true;
video.controls = false;
video.style.display = 'inline-block';
video.style.width = '260px';
video.style.height = '260px';
video.style.position = 'absolute';
video.style.top = '-41px';
video.style.left = leftFrom + 'px';
leftFrom = leftFrom + 270;
video.appendChild(source);
container.appendChild(video);
}
nextButton.addEventListener('click', next);
prevButton.addEventListener('click', previous);
}
var photoGallery = new PhotoGallery();
photoGallery.imagecreate('1', 'img/1.jpg');
photoGallery.imagecreate('2', 'img/2.jpg');
photoGallery.imagecreate('3', 'img/3.jpg');
photoGallery.imagecreate('4', 'img/4.jpg');
// photoGallery.videocreate('img/mcvideo.mp4', 'video/mp4');
photoGallery.imagecreate('5', 'img/5.jpg');
photoGallery.imagecreate('6', 'img/6.jpg');
photoGallery.imagecreate('7', 'img/7.jpg');
photoGallery.imagecreate('8', 'img/8.jpg');
//photoGallery.videocreate('img/SampleVideo_640x360_1mb.mp4', 'video/mp4');
photoGallery.imagecreate('9', 'img/9.jpg');
photoGallery.imagecreate('10', 'img/10.jpg');
photoGallery.imagecreate('11', 'img/006.jpg');
// photoGallery.videocreate('img/small.mp4', 'video/mp4');
photoGallery.imagecreate('12', 'img/007.jpg');
//Mouse Sliding Functionality:-
var sliding;
var dir;
var startClientX = 0;
$mainDiv = $('#thumbs_container');
function move(dir) {
var img = $mainDiv.find('img');
imgWidth = img.width();
//var video = $mainDiv.find('video');
//videoWidth = video.width();
var total = dir * imgWidth;
img.animate({ left: '+=' + (total) }, 750);
//video.animate( { left: '+=' + (dir * videoWidth) }, 200);
}
$mainDiv.mousedown(function (event) {
sliding = true;
startClientX = event.clientX;
return false;
}).mouseup(function (event) {
var step = event.clientX - startClientX,
dir = step > 0 ? 1 : -1;
step = Math.abs(step);
move(dir);
});
CSS:-
#thumbs_container {
width: 100%; /*width:400px;*/
padding: 14px 40px; /*Gives room for arrow buttons*/
box-sizing: border-box;
position: relative;
background-color: red;
-webkit-user-select: none;
user-select: none;
/*max-width: 1600px;
max-height: 600px;*/
overflow:hidden;
}
.inner {
width: 95%;
padding: 14px 40px;
box-sizing: border-box;
position: relative;
background-color: yellow;
-webkit-user-select: none;
user-select: none;
overflow: hidden;
}
.thumb{
margin-right: 1px;
}
button{position: fixed;
top: 40%;
z-index: 99999;
left: 50%;
background-color: #4CAF50;
color: #fff;
border: none;
height: 30px;
width: 30px;
line-height: 30px;}
.previous {
background-color: #4CAF50;
border: none;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
position: fixed;
margin-left: -33px;
top: 7%;
left: 2%;
}
.next {
background-color: #4CAF50;
border: none;
color: white;
padding: 2px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
position: fixed;
left: 98%;
top: 7%;
}
.round {
border-radius: 50%;
}
HTML:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DynamicSlider</title>
<!--<link href="css/thumbs2.css" rel="stylesheet" />
<link href="css/thumbnail-slider.css" rel="stylesheet" />
<script src="js/thumbnail-slider.js" type="text/javascript"></script>
<script src="js/readImages.js"></script>-->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>-->
<script src="js/jquery1.6.2.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<link href="css/DynamicSlider.css" rel="stylesheet" />
<script src="js/DynamicSlider.js"></script>
</head>
<body>
<div id='thumbs_container'>
</div>
<div id="inner">
</div>
</body>
</html>

How to create (or at least, describe) horizontal progress bar with thresholds?

I'm looking to create a horizontal chart with thresholds at certain percentages- if you've ever used Battle.Net, kind of similar to their download bar:
Blizzard Download Bar
I'm sure there's a name for it, I just don't know what it is...
Thanks!
I made this just in case it helps. Have 'fun'.
You can edit the little threshold pointer so they look stylish with css. But yea that all depends on what you want to do
// Btw, I'm a big fan of the canvas element that's why I'm doing this. Otherwise, you can also use a progress bar
var c = document.getElementById('progressBar'),
dt = document.getElementById('download-text'),
btn = document.querySelector('button'),
p2 = document.querySelector('progress');
var cx = c.getContext('2d');
var counter = 0,
loop;
btn.onclick = function() {
btn.innerText = 'N';
var timeInter = setInterval(function(){
btn.innerText += 'o';
},70);
setTimeout(function(){
clearTimeout(timeInter);
btn.hidden = true;
p2.hidden = false;
progress2();
},1000);
}
var loop2 = '',
counter2 = 0;
function progress2() {
counter2++;
var percentage = (counter2 / 17).toFixed(2);
if (percentage - 0 >= 100) {
percentage = 100;
}
p2.value = percentage - 0 +'';
if (percentage - 0 > 100) {
cancelAnimationFrame(loop2);
} else {
loop2 = requestAnimationFrame(progress);
}
//This is me failing to animate the progress bar
}
function progress() {
counter++;
var percentage = (counter / 17).toFixed(2);
if (percentage >= 100) {
percentage = 100+'.00';
}
dt.innerText = "Download: " + percentage + "%";
cx.fillStyle = '#00FFFF';
cx.fillRect(0, 0, c.width * percentage / 100, c.height);
cx.strokeStyle = '#ccc';
cx.beginPath();
cx.moveTo(100, 70);
cx.lineTo(100, 0);
cx.stroke();
cx.moveTo(300, 70);
cx.lineTo(300, 0);
cx.stroke();
if (percentage - 0 > 100) {
cancelAnimationFrame(loop);
} else {
loop = requestAnimationFrame(progress);
}
}
progress();
#progressBar {
border: 1px solid grey;
z-index: -10;
}
#progressBar,
#download-text,
#playable,
#optimal,
button,
progress{
position: absolute;
top: 0px;
left: 0px;
}
button,
progress{
top:200px;
}
#download-text {
height: 70px;
padding-top: 25px;
padding-left: 7px;
font-family: sans-serif;
background-color: transparent;
}
#playable,
#optimal {
width: 100px;
height: 43px;
text-align: center;
padding-top: 20px;
font-family: sans-serif;
font-weight: bolder;
}
#playable {
background-color: yellow;
position: absolute;
top: 72px;
left: 100px;
}
#optimal {
background-color: green;
position: absolute;
top: 72px;
left: 300px;
}
<div>
<canvas id="progressBar" width="430px" height="70px"></canvas>
<div id="download-text">Hello</div>
</div>
<div id="playable">PLAYABLE</div>
<div id="optimal">OPTIMAL</div>
<button type="button">Please don't press me just stick to canvas</button>
<progress max="100" hidden="true"></progress>

Html5 resizing object by dragging

I need to resize notes in my little application, but I don't know how. They have to be resized by dragging their bottom right corner and it must be done in pure java script.
Div with "+" adds new note and empty div is something like counter of all notes.
Code:
document.addEventListener("onload", Load());
var index = 0;
var cnt = 0;
var x = 0;
var y = 0;
var xx = 0;
var yy = 0;
var clicked = false;
var dragged = false;
var counter = 0;
var numberOfPapers = 0;
var state = 0;
function Load(){
var adder = document.querySelector("#add");
adder.setAttribute("onclick", "addClick()");
}
function addClick(){
cnt++;
numberOfPapers++;
document.querySelector("#counter").innerHTML = "Przebieg = " + cnt + "<br>" + "Liczba kartek = " + numberOfPapers;
var paper = document.createElement("div");
var paperX = document.createElement("div");
var paperR = document.createElement("div");
var paperS = document.createElement("div");
//papierek xD
paper.setAttribute("class", "paper");
paper.setAttribute("onmousedown", "movePaper(this,event)");
paper.setAttribute("onmouseup", "stop(this)");
paper.setAttribute("onmouseleave", "stop(this)");
paper.setAttribute("id", "id_" + cnt);
paper.style.top = "100px";
paper.style.left = "100px";
paper.style.zIndex = cnt;
//niszczyciel papierków
paperX.setAttribute("class", "deleter");
paperX.setAttribute("onclick", "deletePaper(this)");
//zmieniacz rozmiarów
paperR.setAttribute("class", "resizer");
paperR.ondragstart = function(e){
e.preventDefault();
};
paperR.setAttribute("onmousedown", "resize(this,event)");
//edytor tekstu tini emce
paperS.setAttribute("class", "txtEditor");
paperS.setAttribute("onclick", "editTxt()");
paper.appendChild(paperX);
paper.appendChild(paperR);
paper.appendChild(paperS);
document.body.appendChild(paper);
}
function stop(e){
e.setAttribute("onmousemove", null);
state = 1;
}
function resize(e,event){
state = 2;
}
function deletePaper(e){
e.parentElement.id = "del";
var del = document.querySelector("#del");
del.parentNode.removeChild(del);
numberOfPapers--;
document.querySelector("#counter").innerHTML = "Przebieg = " + cnt + "<br>" + "Liczba kartek = " + numberOfPapers;
}
function movePaper(e, event){
index++;
e.style.zIndex = index;
x = event.clientX;
y = event.clientY;
xx = e.style.left;
yy = e.style.top;
xx = xx.slice(0,xx.search("px"));
yy = yy.slice(0,yy.search("px"));
x = x - xx;
y = y - yy;
e.setAttribute("onmousemove","moreMove(this,event)");
}
function moreMove(e,event){
e.style.top = event.clientY - y + "px";
e.style.left = event.clientX - x + "px";
}
body{
margin: 0;
padding: 0;
}
#add{
position: absolute;
width: 45px;
height: 35px;
top: 25px;
right: 25px;
background-color: #F5574E;
text-align:center;
padding-top:10px;
border: solid black 1px;
}
#counter{
position: absolute;
width: 200px;
height: 45px;
top: 25px;
right: 80px;
background-color: #F5574E;
text-align:center;
border: solid black 1px;
}
.paper{
position: absolute;
width: 100px;
height: 100px;
top: 25px;
left: 25px;
background-color: #E3D67F;
border: solid black 1px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.deleter{
position: absolute;
width: 10px;
height: 10px;
top: 0px;
right: 0px;
background-color: red;
}
.resizer{
position: absolute;
width: 10px;
height: 10px;
bottom: 0px;
right: 0px;
background-color: green;
}
.txtEditor{
position: absolute;
width: 10px;
height: 10px;
top: 10px;
right: 0px;
background-color: yellow;
}
<body>
<div id="add">+
</div>
<div id="counter">
</div>
</body>
You can simply take replicate your move functions and instead of targeting top and left you target width and height of the parent node. Like this:
function resize(e, event) {
event.stopPropagation();//this to prevent move behavior to be triggered when clicking resize handle
state = 2;
index++;
e.style.zIndex = index;
x = event.clientX;
y = event.clientY;
xx = e.parentNode.style.width;
yy = e.parentNode.style.height;
xx = xx.slice(0, xx.search("px"));
yy = yy.slice(0, yy.search("px"));
x = x - xx;
y = y - yy;
e.setAttribute("onmousemove", "resizeMove(this,event)");
}
function resizeMove(e, event) {
console.log('resixe')
e.parentNode.style.height = event.clientY - y + "px";
e.parentNode.style.width = event.clientX - x + "px";
}
You'll have to declare width and height of your parentNode for it to work, you can add it to your paper section.
paper.style.width = "100px";
paper.style.height = "100px";

Categories