Javascript switch shape of an existing shape - javascript

i have a project in javascript which is about a square that is moving using the keyboard ( up, down, right , left) now i want to be able to change the shape of the square into a triangle or a circle for example. I want to do this by pressing for example 1 and change the shape into a circle, 2 and change the shape into a triangle. At the same time i want the new shape to be able to move using up, down,left,right
The question is, How can i change the shape of my square into a triangle? or a circle?
html
<!DOCTYPE html>
<html>
<head>
<title>Interactiune cu tastatura</title>
<script src="./main.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="patrat"></div>
<div id="triangle"></div>
<div id="circle"></div>
<p id="demo"></p>
</body>
</html>
CSS
#CHARSET "UTF-8";
#patrat {
position: absolute;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
background-color: blue;
}
#triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
#circle {
width: 100px;
height: 100px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
main.js
var step = 100,
squareLeft = 0,
squareTop = 0,
squareSide = 100,
triangleLeft = 0,
triangleTop = 0,
triangleSide = 100,
circleLeft = 0,
circleTop = 0,
circleSide = 0,
screenWidth = 1920,
screenHeight = 1080;
document.addEventListener('keydown', function(event)
{
var keyCode = event.keyCode,
spaceLeft = 0,
x = document.getElementById("patrat");
y = document.getElementById("triangle");
switch (keyCode) {
case(49):
document.getElementById("circle");
case (13): /*ENTER*/
/*document.getElementById("demo").innerHTML = "Text test";*/
/*document.getElementById("demo").innerHTML = x.style.backgroundColor;*/
x.style.backgroundColor = "rgb(255,255,0)";
break;
case (37): /*ArrowLeft*/
if (squareLeft > 0) {
squareLeft = (squareLeft > step) ? squareLeft - step : 0;
x.style.left = squareLeft + "px";
}
break;
case (39): /*ArrowRight*/
spaceLeft = screenWidth - squareLeft - squareSide;
if (spaceLeft > 0) {
squareLeft += (spaceLeft > step) ? step : spaceLeft;
x.style.left = squareLeft + "px";
}
break;
case (38): /*ArrowUp*/
if (squareTop > 0) {
squareTop = (squareTop > step) ? squareTop - step : 0;
x.style.top = squareTop + "px";
}
break;
case (40): /*ArrowDown*/
spaceLeft = screenHeight - squareTop - squareSide;
if (spaceLeft > 0) {
squareTop += (spaceLeft > step) ? step : spaceLeft;
x.style.top = squareTop + "px";
}
break;
default:
alert("Aceasta tasta nu este utilizata");
break;
}
}
);

If your triangle CSS class is correct, it looks like you could start by changing the ID of the element:
document.getElementById('circle').id = 'triangle';
...but this architecture is brittle and not recommended. A step down the road to improvement would be use classnames:
document.querySelector('.circle').className = 'triangle';
which will turn the first DOM element with a class of circle into a triangle. Your CSS will look like
.circle {
...
}
.triangle {
...
}
To turn all .circles into .triangles, do something like:
document.querySelectorAll('.circle').forEach(function(element) {
element.className = triangle;
});
Again, this is assuming your CSS classes are rendering the shapes as expected.

Related

Why can't JavaScript read more than 3 keys at times?

I have an array of keys that stores which keys are being pressed. Whenever I press the left arrow, spacebar, and the up arrow together, the array will only keep two of the keycodes, leaving one not to be pushed into the array. When these three keys are pressed, the character is supposed to move left, jump up, and shoot a bullet. One of those three actions won't occur. I am using Google Chrome, and I don't know what will happen on other browsers.
var $c = $('canvas');
var ctx = $c[0].getContext('2d');
var x = 20;
var y = 150;
var keys = [];
var bulletX = x + 2;
var bulletY = 0;
var bullets = [];
var face = 1;
function plr() {
ctx.fillStyle = 'black';
ctx.fillRect(x, y, 20, 20);
}
$c.keydown(function(e) {
if (_.includes(keys, e.which) === false) {
keys.push(e.which);
}
});
$c.keyup(function(e) {
_.pull(keys, e.which);
});
function shoot() {
bullets.forEach(function(bullet) {
ctx.fillStyle = 'red';
ctx.fillRect(bullet.bX, bullet.bY, 8, 4);
if (bullet.direction === 0) {
bullet.bX -= 7;
}
if (bullet.direction === 1) {
bullet.bX += 7;
}
if (bullet.bX > 700 || bullet.bX < 0) {
_.pull(bullets, bullet);
}
});
}
setInterval(function() {
ctx.clearRect(0, 0, 700, 500);
if (keys.includes(32)) {
bullets.push({
direction: face,
bX: x + face * 12,
bY: y + 8
});
}
if (keys.includes(37)) {
face = 0;
x -= 3;
}
if (keys.includes(38)) {
y-=3;
}
if (keys.includes(39)) {
face = 1;
x += 3;
}
plr();
shoot();
}, 30);
.canvas {
background-color: #a3c2ba;
outline: none;
border: #fff;
margin: auto;
display: block;
position: relative;
top: 50px;
border-radius: 0px;
}
body {
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js'></script>
</head>
<body>
<canvas class='canvas' width='300' height='200' tabindex='1' />
</body>
</html>
I have concluded that this is a problem with my keyboard. I tried this on my brother's computer and it worked fine. Thanks to everyone who attempted to help though!

Colliding two circles without using canvas

I have created three circles and made it bounce off the wall without using HTML canvas. Now I want two circles to collide with each other and move those circles in the opposite direction. I tried to detect the collision by checking it's position but it doesn't work. I don't know where I went wrong.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Bounce Ball</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.circle{
height: 50px;
width: 50px;
position: absolute;
border-radius: 50%;
}
.container {
height: 300px;
width: 300px;
background-color: skyblue;
position: relative;
}
</style>
</head>
<body>
<div class ="container" id ="container">
<div class="circle" id = "circle1" style="background-color:black;
height: 50px; width: 50px;top:0; left:0"></div>
<div class="circle" id ="circle2" style="background-color:rgb(197, 100,
100);height: 50px; width: 50px;top:200px;left: 150px"></div>
<div class="circle" id ="circle3" style="background-color:brown;height:
50px;width: 50px;top:50px;left: 640px"></div>
</div>
<script>
var container = document.getElementById("container");
container.style.width="700px";
container.style.height = "300px";
var balls = document.getElementsByClassName("circle");
for(var i=0; i <balls.length; i++){
var speed={x:3,y:-3}
setInterval(draw, 50 , balls[i], speed);
}
function draw(ball, speed) {
if(parseInt(ball.style.left) > (parseInt(container.style.width)-
parseInt(ball.style.width)) || (parseInt(ball.style.left) <0) ){
speed.x = -speed.x;
}
ball.style.left = parseInt(ball.style.left) + speed.x + 'px';
if(parseInt(ball.style.top) > (parseInt(container.style.height)-
parseInt(ball.style.height)) || (parseInt(ball.style.top) <0)){
speed.y = -speed.y;
}
ball.style.top = parseInt(ball.style.top) + speed.y + 'px';
//for colliding two circles
for(var i =0 ; i <= balls.length-1; i++){
for(var j = i + 1; j < balls.length; j++){
if(parseInt(balls[i].style.left) +
parseInt(balls[i].style.width) ==
parseInt(balls[j].style.left) ||
parseInt(balls[j].style.left) +
parseInt(balls[j].style.width) ==
parseInt(balls[i].style.left) &&
parseInt(balls[i].style.top) +
parseInt(balls[i].style.height) ==
parseInt(balls[j].style.top) || parseInt(balls[j].style.top)
+ parseInt(balls[j].style.height) ==
parseInt(balls[i].style.top)) {
speed.x = - speed.x;
speed.y = -speed.y;
}
ball[i].style.left = parseInt(ball[i].style.left) +
speed.x + 'px';
ball[j].style.left = parseInt(ball[j].style.left) +
speed.x + 'px';
ball[i].style.top = parseInt(ball[i].style.top) +
speed.y + 'px';
ball[j].style.top = parseInt(ball[j].style.top) +
speed.y + 'px';
}
}
}
</script>
</body>
</html>
I would recommend moving as much as possible into javascript variables so you don't need to consult the HTML for every parameter.
You had quite the number of typos, among them speed.x = - speed.x; where you meant speed.x = -speed.x; and your code was difficult to read without any comments or helper functions to explain what's going on.
I have fixed your typos and restructured your code in the snippet below. Try checking the developer console, typically by pressing F12, as this will show you code errors with line number and severity rating.
In my snippet below i have tried to move the parameters into JavaScript to show how that would work, while still leaving some on the HTML nodes:
//Basic properties
var width = 700;
var height = 300;
//Get container
var container = document.getElementById("container");
// Set dimensions
container.style.width = width + "px";
container.style.height = height + "px";
//Load balls
var balls = Array.prototype.slice.call(document.getElementsByClassName("circle"))
.map(function(ball) {
return {
HTMLNode: ball,
xPos: parseInt(ball.style.left),
yPos: parseInt(ball.style.top),
xAcc: 3,
yAcc: -3,
size: 50
};
});
//Utility functions
function angleBetween(x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1);
}
function distanceBetween(x1, y1, x2, y2) {
return Math.abs(y2 - y1) + Math.abs(x2 - x1);
}
//Draw function
function draw() {
//Loop through balls
for (var ballIndex1 = 0; ballIndex1 < balls.length; ballIndex1++) {
var ball1 = balls[ballIndex1];
//Collide with horisontal wall
if (ball1.xPos > width - ball1.size || ball1.xPos < 0) {
ball1.xAcc = -ball1.xAcc;
}
//Collide with vertical wall
if (ball1.yPos > height - ball1.size || ball1.yPos < 0) {
ball1.yAcc = -ball1.yAcc;
}
//Collide with other balls
for (var ballIndex2 = ballIndex1 + 1; ballIndex2 < balls.length; ballIndex2++) {
var ball2 = balls[ballIndex2];
//Test within collision distance
if (distanceBetween(ball1.xPos, ball1.yPos, ball2.xPos, ball2.yPos) > ball1.size) {
continue;
}
//Get angle of collision
var angle = angleBetween(ball1.xPos, ball1.yPos, ball2.xPos, ball2.yPos);
//Apply force to acceleration
ball1.xAcc = -Math.cos(angle) * 3;
ball2.xAcc = -ball1.xAcc;
ball1.yAcc = -Math.sin(angle) * 3;
ball2.yAcc = -ball1.yAcc;
}
//Apply acceleration to position
ball1.yPos += ball1.yAcc;
ball1.xPos += ball1.xAcc;
//Apply to node
ball1.HTMLNode.style.left = ball1.xPos + "px";
ball1.HTMLNode.style.top = ball1.yPos + "px";
}
}
//Start simulation
setInterval(draw, 1000 / 60);
.circle {
position: absolute;
border-radius: 50%;
height: 50px;
width: 50px;
}
.container {
height: 300px;
width: 300px;
background-color: skyblue;
position: relative;
}
<div class="container" id="container">
<div class="circle" id="circle1" style="background-color:black;
top:0; left:0"></div>
<div class="circle" id="circle2" style="background-color:rgb(197, 100,
100);top:200px;left: 150px"></div>
<div class="circle" id="circle3" style="background-color:brown;top:50px;left: 640px"></div>
</div>

How to recognize hover/click of a border in CSS and JS

Hi I am working on a CodePen to make a draggable and resizavle box without Jquery. What I am trying to accomplish is that when you hover/click over the main body of the div you can drag it around and will have the "move" cursor.
When you hover/click on the border, you can resize the box, based on which side you click on and have the "col-resize" or "row-resize" cursor.
What I am really wondering is if it is even possible to select the border with JS and CSS, and if so how.
This is an example of how to determine which border you're hovering (good luck with your other calculations):
var div = document.querySelector("#div");
var delta = 10; // the thickness of the hovered border area
div.onmousemove = function(e) {
var rect = div.getBoundingClientRect();
var x = e.clientX - rect.left, // the relative mouse postion to the element
y = e.clientY - rect.top, // ...
w = rect.right - rect.left, // width of the element
h = rect.bottom - rect.top; // height of the element
var c = ""; // which cursor to use
if(y < delta) c += "n"; // north
else if( y > h - delta) c += "s"; // south
if(x < delta) c += "w"; // west
else if(x > w - delta) c += "e"; // east
if(c) // if we are hovering at the border area (c is not empty)
div.style.cursor = c + "-resize"; // set the according cursor
else // otherwise
div.style.cursor = "pointer"; // set to pointer
}
#div {
background-color: red;
width: 100px;
height: 100px;
}
<div id="div"></div>
<br>Psst! Hover at the border area! Corners too.
Note: The above method doesn't relly on wether or not the element has borders, and wether or not it could have child nodes (for example img...).
I don't think that you can detect a click just on the border without any workaround. You could detect the border by checking where the mouse is in relation to box, as #ibrahim mahrir did, but I prefer just using a wrapper element it:
Undynamic to CSS values
The most simple. Set the width of the "border" manually. Use if you're never going to change the padding/width of the "border".
var border = document.getElementById("border");
var bor = 4;
border.onclick = function(e) {
if (e.target !== e.currentTarget) return;
console.log("border-clicked")
}
border.onmouseover = function(e) {
y = e.offsetY;
if (y <= bor || y >= this.offsetHeight - bor) c = "row"
else c = "col"
this.style.cursor = c + "-resize";
}
#border {
padding: 4px;
background: blue;
box-sizing: border-box;
}
.box{
height: 100px;
width: 100%;
background: white;
cursor: default;
}
<div id="border">
<div class="box"></div>
</div>
Dynamic to one CSS value
Set the width of the "border" by selecting one of the values of the padding. Use this if are going to change the value of the padding and has the same width throughout.
var border = document.getElementById("border");
var bor = parseInt(window.getComputedStyle(border, null).getPropertyValue('padding-left') )
border.onclick = function(e) {
if (e.target !== e.currentTarget) return;
console.log("border-clicked")
}
border.onmouseover = function(e) {
y = e.offsetY;
if (y <= bor || y >= this.offsetHeight - bor) c = "row"
else c = "col"
this.style.cursor = c + "-resize";
}
#border {
padding: 4px;
background: blue;
box-sizing: border-box;
}
.box{
height: 100px;
width: 100%;
background: white;
cursor: default;
}
<div id="border">
<div class="box"></div>
</div>
Dynamic to both CSS values
Set the width of the "border" by selecting a horizontal and vertical value of the padding. Use this if the padding is like padding: #px #px.
var border = document.getElementById("border");
var borderStyles = window.getComputedStyle(border, null);
var borLeft = parseInt( borderStyles.getPropertyValue('padding-left') )
var borTop = parseInt( borderStyles.getPropertyValue('padding-top') )
border.onclick = function(e) {
if (e.target !== e.currentTarget) return;
console.log("border-clicked")
}
border.onmouseover = function(e) {
x = e.offsetX;
y = e.offsetY;
if (x < borLeft || x > this.offsetWidth - borLeft ) c = "col";
else if (y <= borTop || y >= this.offsetHeight - borTop) c = "row"
this.style.cursor = c + "-resize";
}
#border {
padding: 4px;
background: blue;
box-sizing: border-box;
}
.box{
height: 100px;
width: 100%;
background: white;
cursor: default;
}
<div id="border">
<div class="box"></div>
</div>
Create a div and make it is position absolute inside your hole div add the style of you border to it then give a hover effect and the event you want to it.
Set the position relative to the hole div and absolute to the border div you have to set left, right,top,bottom to minus value according to your border width you may need to make the background-color as transparent.

Javascript resize and crop on mobile devices

I implement this resize and crop tool on my website : http://tympanus.net/codrops/2014/10/30/resizing-cropping-images-canvas/
I changed some codes to have what I want, like a final crop picture with a size of 390px * 390px.
It works fine, but my site is responsive, and on a mobile device, the website width is 320px.
How can I changed my code to, on mobile version, have a smallest crop zone, but a final picture of 390px * 390px ?
Thanks.
Javascript code :
var resizeableImage = function(image_target) {
// Some variable and settings
var $container,
orig_src = new Image(),
image_target = $(image_target).get(0),
event_state = {},
constrain = false,
min_width = 100, // Change as required
min_height = 100,
max_width = 900, // Change as required
max_height = 900,
resize_canvas = document.createElement('canvas');
init = function(){
// When resizing, we will always use this copy of the original as the base
orig_src.src=image_target.src;
// Wrap the image with the container and add resize handles
$(image_target).wrap('<div class="resize-container"></div>')
.before('<span class="resize-handle resize-handle-nw"></span>')
.before('<span class="resize-handle resize-handle-ne"></span>')
.after('<span class="resize-handle resize-handle-se"></span>')
.after('<span class="resize-handle resize-handle-sw"></span>');
// Assign the container to a variable
$container = $(image_target).parent('.resize-container');
// Add events
$container.on('mousedown touchstart', '.resize-handle', startResize);
$container.on('mousedown touchstart', 'img', startMoving);
$('.js-crop').on('click', crop);
};
startResize = function(e){
e.preventDefault();
e.stopPropagation();
saveEventState(e);
$(document).on('mousemove touchmove', resizing);
$(document).on('mouseup touchend', endResize);
};
endResize = function(e){
e.preventDefault();
$(document).off('mouseup touchend', endResize);
$(document).off('mousemove touchmove', resizing);
};
saveEventState = function(e){
// Save the initial event details and container state
event_state.container_width = $container.width();
event_state.container_height = $container.height();
event_state.container_left = $container.offset().left;
event_state.container_top = $container.offset().top;
event_state.mouse_x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft();
event_state.mouse_y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
// This is a fix for mobile safari
// For some reason it does not allow a direct copy of the touches property
if(typeof e.originalEvent.touches !== 'undefined'){
event_state.touches = [];
$.each(e.originalEvent.touches, function(i, ob){
event_state.touches[i] = {};
event_state.touches[i].clientX = 0+ob.clientX;
event_state.touches[i].clientY = 0+ob.clientY;
});
}
event_state.evnt = e;
};
resizing = function(e){
var mouse={},width,height,left,top,offset=$container.offset();
mouse.x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft();
mouse.y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
// Position image differently depending on the corner dragged and constraints
if( $(event_state.evnt.target).hasClass('resize-handle-se') ){
width = mouse.x - event_state.container_left;
height = mouse.y - event_state.container_top;
left = event_state.container_left;
top = event_state.container_top;
} else if($(event_state.evnt.target).hasClass('resize-handle-sw') ){
width = event_state.container_width - (mouse.x - event_state.container_left);
height = mouse.y - event_state.container_top;
left = mouse.x;
top = event_state.container_top;
} else if($(event_state.evnt.target).hasClass('resize-handle-nw') ){
width = event_state.container_width - (mouse.x - event_state.container_left);
height = event_state.container_height - (mouse.y - event_state.container_top);
left = mouse.x;
top = mouse.y;
if(constrain || e.shiftKey){
top = mouse.y - ((width / orig_src.width * orig_src.height) - height);
}
} else if($(event_state.evnt.target).hasClass('resize-handle-ne') ){
width = mouse.x - event_state.container_left;
height = event_state.container_height - (mouse.y - event_state.container_top);
left = event_state.container_left;
top = mouse.y;
if(constrain || e.shiftKey){
top = mouse.y - ((width / orig_src.width * orig_src.height) - height);
}
}
// Optionally maintain aspect ratio
if(constrain || e.shiftKey){
height = width / orig_src.width * orig_src.height;
}
/*if(width > min_width && height > min_height && width < max_width && height < max_height){
// To improve performance you might limit how often resizeImage() is called
resizeImage(width, height);
// Without this Firefox will not re-calculate the the image dimensions until drag end
$container.offset({'left': left, 'top': top});
}*/
if(width > min_width && height > min_height /*&& width < max_width && height < max_height*/){
// To improve performance you might limit how often resizeImage() is called
resizeImage(width, height);
// Without this Firefox will not re-calculate the the image dimensions until drag end
$container.offset({'left': left, 'top': top});
}
}
resizeImage = function(width, height){
resize_canvas.width = width;
resize_canvas.height = height;
resize_canvas.getContext('2d').drawImage(orig_src, 0, 0, width, height);
$(image_target).attr('src', resize_canvas.toDataURL("image/png"));
};
startMoving = function(e){
e.preventDefault();
e.stopPropagation();
saveEventState(e);
$(document).on('mousemove touchmove', moving);
$(document).on('mouseup touchend', endMoving);
};
endMoving = function(e){
e.preventDefault();
$(document).off('mouseup touchend', endMoving);
$(document).off('mousemove touchmove', moving);
};
moving = function(e){
var mouse={}, touches;
e.preventDefault();
e.stopPropagation();
touches = e.originalEvent.touches;
mouse.x = (e.clientX || e.pageX || touches[0].clientX) + $(window).scrollLeft();
mouse.y = (e.clientY || e.pageY || touches[0].clientY) + $(window).scrollTop();
$container.offset({
'left': mouse.x - ( event_state.mouse_x - event_state.container_left ),
'top': mouse.y - ( event_state.mouse_y - event_state.container_top )
});
// Watch for pinch zoom gesture while moving
if(event_state.touches && event_state.touches.length > 1 && touches.length > 1){
var width = event_state.container_width, height = event_state.container_height;
var a = event_state.touches[0].clientX - event_state.touches[1].clientX;
a = a * a;
var b = event_state.touches[0].clientY - event_state.touches[1].clientY;
b = b * b;
var dist1 = Math.sqrt( a + b );
a = e.originalEvent.touches[0].clientX - touches[1].clientX;
a = a * a;
b = e.originalEvent.touches[0].clientY - touches[1].clientY;
b = b * b;
var dist2 = Math.sqrt( a + b );
var ratio = dist2 /dist1;
width = width * ratio;
height = height * ratio;
// To improve performance you might limit how often resizeImage() is called
resizeImage(width, height);
}
};
crop = function(){
//Find the part of the image that is inside the crop box
var crop_canvas,
left = $('.overlay').offset().left - $container.offset().left,
top = $('.overlay').offset().top - $container.offset().top,
width = $('.overlay').width(),
height = $('.overlay').height();
crop_canvas = document.createElement('canvas');
crop_canvas.width = width;
crop_canvas.height = height;
crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);
//window.open(crop_canvas.toDataURL("image/png"));
var canvasData = crop_canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'upload_picture.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData)
}
init();
};
HTML code :
<div id="crop_canvas">
<div class="overlay">
<div class="overlay-inner"></div>
</div>
<img class="resize-image" src="mypicture.jpg" />
</div>
<button class="btn-crop js-crop">Découper</button>
CSS code :
.resize-container {
position: relative;
display: inline-block;
cursor: move;
margin: 0 auto;
}
.resize-container img {
display: block
}
.resize-container:hover img,
.resize-container:active img {
outline: 2px dashed rgba(222,60,80,.9);
}
.resize-handle-ne,
.resize-handle-ne,
.resize-handle-se,
.resize-handle-nw,
.resize-handle-sw {
position: absolute;
display: block;
width: 10px;
height: 10px;
background: rgba(222,60,80,.9);
z-index: 999;
}
.resize-handle-nw {
top: -5px;
left: -5px;
cursor: nw-resize;
}
.resize-handle-sw {
bottom: -5px;
left: -5px;
cursor: sw-resize;
}
.resize-handle-ne {
top: -5px;
right: -5px;
cursor: ne-resize;
}
.resize-handle-se {
bottom: -5px;
right: -5px;
cursor: se-resize;
}
.overlay {
position: absolute;
left:40%;
top:31%;
margin-left: -100px;
margin-top: -100px;
z-index: 999;
width:390px;
height:390px;
border: solid 2px #f8b028;
box-sizing: content-box;
pointer-events: none;
}
.overlay:after,
.overlay:before {
content: '';
position: absolute;
display: block;
width: 394px;
height: 40px;
border-left: dashed 2px #f8b028;
border-right: dashed 2px #f8b028;
}
.overlay:before {
top: 0;
margin-left: -2px;
margin-top: -40px;
}
.overlay:after {
bottom: 0;
margin-left: -2px;
margin-bottom: -40px;
}
.overlay-inner:after,
.overlay-inner:before {
content: '';
position: absolute;
display: block;
width: 40px;
height: 394px;
border-top: dashed 2px #f8b028;
border-bottom: dashed 2px #f8b028;
}
.overlay-inner:before {
left: 0;
margin-left: -40px;
margin-top: -2px;
}
.overlay-inner:after {
right: 0;
margin-right: -40px;
margin-top: -2px;
}
.btn-crop {
position: absolute;
vertical-align: bottom;
right:20px;
bottom:13px;
padding: 6px 10px;
z-index: 999;
background-color:#f8b028;
border: none;
border-radius:0 0 5px 5px;
color: #FFF;
font-weight:700;
text-transform:uppercase;
}
#crop_modal .modal-dialog{width:980px;}
#crop_modal .modal-content{
background:#0082c6;
border-radius:0;
padding:10px 20px;
}
#crop_modal .modal-content p{
color:#fff;
font-size:12px;
}
#crop_canvas{
background:#fff;
border:3px solid #f8b028;
height:600px;
overflow:hidden;
margin-bottom:35px;
position:relative;
width:100%;
}
You can find a demo here : http://darkcid.olympe.in/

jQuery - Div follow touchmove/mousemove + autoalign

I want to make a very simple function in my jQuery script. When the finger/cursor touches/clicks on the screen, I want the pages to slide horizontally following the movements of the finger/cursor. I know there is a lot of plugins created by so many people, but I really don't need everybody else's solutions. The image is a visual view of how my HTML looks like. it is really simple.
The jQuery sciprt is obviously not correct, but I hope it would give you an idea about the simple function I need. I don't extra classes or fade-functions or anything.
$(document).live('touchmove' or 'mousemove', function() {
$('div[class=page_*], div[class=page_^]').[follow movements horizontally, and auto align to nearest edge when let go.];
});
Also I want to be able to do the same with one big div, so probably the width-variable of the element moving should be equal to $(window).width();. Actually I think that would be the best idea. I can always put more content inside the big div and make it larger, so keep it with that. It should be more simple to do and to focus on one element only.
So, here is my solution. I've made some changes so that now you can have more than 3 pages.
Also, I've defined a variable named threshold set to the half of a page. If you want to have a threshold bigger or smaller than the hakf of the page you will have to make some more changes.
HTML CODE:
<div class="container">
<div class="wrap">
<div class="page page1"></div>
<div class="page page2"></div>
<div class="page page3"></div>
<div class="page page4"></div>
</div>
</div>
CSS CODE:
.container, .page, .wrap {
width: 300px;
height: 400px;
}
.container {
background: #efefef;
box-shadow: 0px 0px 10px black;
overflow: hidden;
position: relative;
margin: 5px auto;
}
.wrap {
width: 1200px;
position: absolute;
top: 0;
left: 0;
}
.page {
float: left;
display: block;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
.page1 {
background: yellow;
}
.page2 {
background: green;
}
.page3 {
background: blue;
}
.page4 {
background: red;
}
As for the CSS code keep in mind that if you want to change the page size you will also have to change the container and wrap size.
JS CODE:
var mouseDown = false, right;
var xi, xf, leftX = 0;
var nPages = $(".page").size();
var pageSize = $(".page").width();
var threshold = pageSize/2;
var currentPage = 0;
$(".container").on("mousedown", function (e) {
mouseDown = true;
xi = e.pageX;
});
$(".container").on("mouseup", function (e) {
if (mouseDown) {
mouseDown = false;
xf = e.pageX;
leftX = parseInt($(".wrap").css("left").split("px")[0]);
if ((e.pageX - xi) < -threshold || (e.pageX - xi) > threshold) {
setFocusedPage();
} else {
restore();
}
}
});
$(".container").on("mouseleave", function (e) {
if (mouseDown) {
mouseDown = false;
xf = e.pageX;
leftX = parseInt($(".wrap").css("left").split("px")[0]);
if ((e.pageX - xi) < -threshold || (e.pageX - xi) > threshold) {
setFocusedPage();
} else {
restore();
}
}
});
$(".container").on("mousemove", function (e) {
if (mouseDown) {
$(".wrap").css({
"left": (leftX + (e.pageX - xi))
});
right = ((e.pageX - xi) < 0) ? true : false;
}
});
function restore() {
$(".wrap").stop().animate({
"left": -(currentPage * pageSize)
}, 200, function () {
leftX = parseInt($(".wrap").css("left").split("px")[0]);
});
}
function setFocusedPage() {
if (leftX >= (-threshold)) { // First Page
currentPage = 0;
} else if (leftX < (-threshold) && leftX >= (-(nPages + 1) * threshold)) { // Second to N-1 Page
(right) ? currentPage++ : currentPage--;
} else if (leftX < -((nPages + 1) * threshold)) { // Third Page
currentPage = nPages - 1;
}
$(".wrap").stop().animate({
"left": -(currentPage * pageSize)
}, 200, function () {
leftX = parseInt($(".wrap").css("left").split("px")[0]);
});
}
Remember here that if you want a different threshold you will have to make some changes especially in the setFocusedPage() function.
Here is my last DEMO

Categories

Resources