Moving a rectangle up down left and right - javascript

I wanted to make a rectangle move in 4 directions with a click of a button on JavaScript. Only the Right and Down works and the other two does not work. I tried finding it on internet and so far had not have any luck.
var currentXpos = 0;
function moveRectRight() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}
function moveRectDown() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}
#rectangle {
background-color: red;
width: 200px;
height: 100px;
margin-left: 0px;
}
<div id='rectangle'></div>
<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />

Your problem lies on this code
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}
when you move left you tried to add the margin right and when you move up you add margin bottom. This is a wrong concept, you shouldn't imagine it like the box is being pushed from 4 side like this image
When you code in HTML & CSS, try to imagine that in coordinate, the 0,0 (x and y) is on your upper left corner of browser, and to move them you can only move them away or closer to the 0,0, like below
I suggest you to learn/debug using the developer tools you can see where it goes wrong,
So the answer is just changing the code to marginLeft and marginTop
That aside, I made my own version maybe you want to check it out
<html>
<head>
<style>
#rectangle {
background-color: red;
width: 200px;
height: 100px;
position: fixed;
}
</style>
</head>
<body>
<div id='rectangle' style="top:100px;left:100px;"></div>
<input type="button" value="Right" onclick="moveRect(this)" />
<input type="button" value="Left" onclick="moveRect(this)" />
<input type="button" value="Up" onclick="moveRect(this)" />
<input type="button" value="Down" onclick="moveRect(this)" />
<script>
const distance = 10;
const directionMap = {
'Up': {
'prop': 'top',
'value': -1
},
'Down': {
'prop': 'top',
'value': 1
},
'Left': {
'prop': 'left',
'value': -1
},
'Right': {
'prop': 'left',
'value': 1
},
}
const parsePosition = (prop) => parseFloat(rectangle.style[prop]) || 0;
const moveRect = (element) => {
let {
prop,
value
} = directionMap[element.value];
rectangle.style[prop] = (parsePosition(prop) + (value * distance)) + "px";
}
</script>
</body>
</html>

Because margins in the HTML, depend on having a neightbor. So, you'll not see margin-right and margin-bottom working, hence you'll not see the box going up or left.
Instead, what you can do, is affect the same property with addition and substraction. For Y affect only margin-top and for X affect only margin-left
CSS Documentation
<html>
<head>
<style>
#rectangle {
background-color: red;
width: 200px;
height: 100px;
margin-left: 0px;
}
</style>
</head>
<body>
<div id='rectangle'>
</div>
<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />
<script>
var currentXpos = 0;
function moveRectRight() {
var rect = document.getElementById('rectangle');
console.log(rect)
currentXpos += 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos -= 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentXpos -= 100; // move by 100 px to the right
rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}
function moveRectDown() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}
</script>
</body>
</html>

Thremulant gave a very good solution but there was something missed something the "current position" variable should be different for X and Y axis. This way it will not show abnormal behaviour.
<html>
<head>
<style>
#rectangle {
background-color: red;
width: 200px;
height: 100px;
margin-left: 0px;
}
</style>
<script>
var currentXpos = 0;
var currentYpos = 0;
function moveRectRight() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos -= 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentYpos -= 100; // move by 100 px to the right
rect.style.marginTop = currentYpos + 'px'; // re-draw rectangle
}
function moveRectDown() {
var rect = document.getElementById('rectangle');
currentYpos += 100; // move by 100 px to the right
rect.style.marginTop = currentYpos + 'px'; // re-draw rectangle
}
</script>
</head>
<body>
<div id='rectangle'></div>
<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />
</body>
</html>

Related

How to moves the divs by clicking on each one

I want to when I click on every div
It's the first to be in front of everyone and the others div are moved.for example div4 is in front of everyone.when I click on div1 I want to put div1 in place of div4 and Then again, on each one that I click on, it's the front but My code does not work properly after several times and does not display one of the shapes.
$(".haml-category").click(function() {
var top = $(this).data("top");
var zindex = $(this).data("zindex");
var temp = $(".haml-category-container").find(".selected");
$(".haml-category-container").find(".selected").removeClass("selected").data("zindex", zindex).data("top", top).css({
"z-index": zindex,
"top": top
});
$(this).data("zindex", temp.data("zindex")).data("top", temp.data("top")).addClass("selected");
});
.haml-category-container {
position: relative;
background-color:#ccc;
}
.haml-category {
position: absolute;
width: 100%;
height: 500px;
top: 0;
right: 0;
border: 1px solid black;
transition: top 1s;
}
.sec-saheb-bar {
z-index: 0;
}
.sec-ranande {
z-index: 1;
top: 40px;
}
.sec-barbar {
z-index: 2;
top: 85px;
}
.sec-bazaryab {
z-index: 3;
top: 130px;
}
.selected {
z-index: 3;
top: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="haml-category-container">
<div class="haml-category sec-saheb-bar" id="sec-saheb-bar" data-zindex="0" data-top="0">
<h6>div1</h6>
<p> content div1</p>
</div>
<div class="haml-category sec-ranande" id="sec-ranande" data-zindex="1" data-top="40">
<h6>div2</h6>
<p> content div2</p>
</div>
<div class="haml-category sec-barbar" id="sec-barbar" data-zindex="2" data-top="85">
<h6>div3</h6>
<p> content div3</p>
</div>
<div class="haml-category sec-bazaryab selected" id="sec-bazaryab" data-zindex="3" data-top="130">
<h6>div4</h6>
<p> content div4</p>
</div>
</div>
The variable temp may has be changed,modified as below.
$(".haml-category").click(function() {
var top = $(this).data("top");
var zindex = $(this).data("zindex");
var temp = $(".haml-category-container").find(".selected");
var top2 = temp.data("top");
var zindex2 = temp.data("zindex");
$(this).data("zindex", zindex2).data("top", top2).css({
"z-index": zindex2,
"top": top2
}).addClass("selected");
temp.removeClass("selected").data("zindex", zindex).data("top", top);
temp.css({
"z-index": zindex,
"top": top
});
});
.haml-category-container {
position: relative;
}
.haml-category {
position: absolute;
width: 100%;
height: 500px;
top: 0;
right: 0;
border: 1px solid black;
transition: top 1s;
}
.sec-saheb-bar {
z-index: 0;
}
.sec-ranande {
z-index: 1;
top: 40px;
}
.sec-barbar {
z-index: 2;
top: 85px;
}
.sec-bazaryab {
z-index: 3;
top: 130px;
}
.selected {
z-index: 3;
top: 130px;
}
#sec-saheb-bar{
background-color:#0077CC;
}
#sec-ranande{
background-color:#1F1D1C;
}
#sec-barbar{
background-color:#FECD45;
}
#sec-bazaryab{
background-color:#1AA160;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="haml-category-container">
<div class="haml-category sec-saheb-bar" id="sec-saheb-bar" data-zindex="0" data-top="0">
<h6>div1</h6>
</div>
<div class="haml-category sec-ranande" id="sec-ranande" data-zindex="1" data-top="40">
<h6>div2</h6>
</div>
<div class="haml-category sec-barbar" id="sec-barbar" data-zindex="2" data-top="85">
<h6>div3</h6>
</div>
<div class="haml-category sec-bazaryab selected" id="sec-bazaryab" data-zindex="3" data-top="130">
<h6>div4</h6>
</div>
</div>
I did this FRANKENSTEIN's monster in 2010 for testing purpose.how you can see i put everywhere z-index:9 watch the demo try to drag every element over other element.with some modifications you can convert it in jquery
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE></TITLE>
<style></style>
<meta charset="UTF-8">
<SCRIPT LANGUAGE="JavaScript">
<!--
// function returns array of box bounds
box_offset = function (box) {
var scrollPosition = getScrollPosition(), // get scroll position
oLeft = 0,// - scrollPosition[0], // define offset left (take care of horizontal scroll position)
oTop = 0,// - scrollPosition[1], // define offset top (take care od vertical scroll position)
box_old = box; // remember box object
// loop to the root element and return box offset (top, right, bottom, left)
do {
oLeft += box.offsetLeft;
oTop += box.offsetTop;
box = box.offsetParent;
}
while (box);
// return box offset array
// top right, bottom left
//return [ oTop, oLeft + box_old.offsetWidth, oTop + box_old.offsetHeight, oLeft ];
// top right, bottom left
return [
oLeft,
oLeft + box_old.offsetWidth,
oTop,
oTop + box_old.offsetHeight
];
};
// function returns scroll positions in array
getScrollPosition = function () {
// define local scroll position variables
var scrollX, scrollY;
// Netscape compliant
if (typeof(window.pageYOffset) === 'number') {
scrollX = window.pageXOffset;
scrollY = window.pageYOffset;
}
// DOM compliant
else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
scrollX = document.body.scrollLeft;
scrollY = document.body.scrollTop;
}
// IE6 standards compliant mode
else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
scrollX = document.documentElement.scrollLeft;
scrollY = document.documentElement.scrollTop;
}
// needed for IE6 (when vertical scroll bar was on the top)
else {
scrollX = scrollY = 0;
}
// return scroll positions
return [ scrollX, scrollY ];
};
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
swdrag = false;
var picwidth;
var picheight;
var picxpos;
var picypos;
var Drag = {
obj : null,
init : function(o, resizer, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
{
o.onmousedown = Drag.start;
o.resizer = resizer;
o.root = o;
if ( isNaN(parseInt(o.root.style.left ))) o.root.style.left = "0px";
if ( isNaN(parseInt(o.root.style.top ))) o.root.style.top = "0px";
o.root.onDragStart = new Function();
o.root.onDragEnd = new Function();
o.root.onDrag = new Function();
calculate();
},
start : function(e)
{
var o = Drag.obj = this;
e = Drag.fixE(e);
var y = parseInt( o.root.style.top );
var x = parseInt( o.root.style.left );
o.root.onDragStart(x, y);
o.lastMouseX = e.clientX;
o.lastMouseY = e.clientY;
document.onmousemove = Drag.drag;
document.onmouseup = Drag.end;
calculate();
return false;
},
drag : function(e)
{
e = Drag.fixE(e);
var o = Drag.obj;
var nx, ny;
var ey = e.clientY;
var ex = e.clientX;
var changeX = (ex - o.lastMouseX);
var changeY = (ey - o.lastMouseY);
nx = parseInt(o.root.style.left ) + changeX;
ny = parseInt(o.root.style.top ) + changeY;
if (o.xMapper) nx = o.xMapper(y)
else if (o.yMapper) ny = o.yMapper(x)
Drag.obj.root.style["left"] = nx + "px";
Drag.obj.root.style["top"] = ny + "px";
Drag.obj.lastMouseX = ex;
Drag.obj.lastMouseY = ey;
Drag.obj.root.onDrag(nx, ny);
Drag.xmouse = Drag.obj.lastMouseX;
Drag.ymouse = Drag.obj.lastMouseY;
Drag.xmouse = e.clientX;
Drag.ymouse = e.clientY;
calculate();
calculate2();
swdrag=true;
return false;
},
end : function()
{
document.onmousemove = null;
document.onmouseup = null;
Drag.obj.root.onDragEnd( parseInt(Drag.obj.root.style["right"]),
parseInt(Drag.obj.root.style["bottom"]));
Drag.obj = null;
calculate();
if (swdrag){
swdrag = false;
}
},
fixE : function(e)
{
if (typeof e == 'undefined') e = window.event;
if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
Drag.xmouse=e.clientX;
Drag.ymouse=e.clientY;
calculate();
return e;
},
xmouse:0,
ymouse:0
};
function start(){
IMAGE.style.left=x_pic_ini;
IMAGE.style.top=y_pic_ini;
//calculate();
}
function calculate(){
widthIMAGE=parseInt(IMAGE.clientWidth);
picwidth=widthIMAGE;
heightIMAGE=parseInt(IMAGE.clientHeight);
picheight=heightIMAGE;
xposex=parseInt(IMAGE.style.left);
yposex=parseInt(IMAGE.style.top);
picxpos=xposex;
picypos=yposex;
IMAGE.left=picxpos;
IMAGE.top=picypos;
}
function calculate2(){
oobj=document.f1;
oobj.xpic.value=picxpos;
oobj.ypic.value=picypos;
//fiecare celula | every box
if(lastbox!=null)
{
//lastbox.style.background='white';
//lastbox.style.color='black';
}
mxrows=document.getElementById("tb1").rows.length;
for(i=0;i<mxrows;i++){
mxcols=document.getElementById("tb1").rows[i].cells.length;
for(u=0;u<3;u++){
//a("i"+i+u+"=");
theboxobj=eval(document.getElementById("i"+i+u));
xyb=box_offset(theboxobj);
oox=picxpos;
ooy=picypos+(heightIMAGE-theboxobj.clientHeight)/2;
if ((oox>xyb[0])&&(oox<xyb[1])&&(ooy>xyb[2])&&(ooy<xyb[3]))
{
a('i('+i+' '+u+')');
theboxobj.style.background='red';
theboxobj.style.color='yellow';
lastbox=theboxobj;
if(!swdrag){
break;
// imobj=document.getElementById("image");
//document.write(obj2(obj,'obj'));
// oldobj=imobj.outerHTML;
// imobj=new Object();
// lastbox.appendChild(imobj);
lastbox.parentNode.removeChild(lastbox);
//imobj=new Object();
lastbox.parentNode.appendChild(imobj);
lastbox.parentNode.outerHTML='<td>xx</td>';
// imobj.parentNode.removeChild(imobj);
// lastbox.innerHTML=oldobj;
}
//alert(oldobj);
break;
}
}
}
}
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
//---------------obj 2 --------------------------------
function obj2(obj, obj_name) {
var result = "";
for (var i in obj)
result += obj_name + "." + i + " = " + obj[i] +'-'+typeof obj[i]+ "\n<br>\n";
return result
}
function obj1(obj,txt){//obj(this.style)
tt=document.open('about:blank','here','');
tt.document.write(obj2(obj,txt));
}
//-----------------------------------------------------
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
ids=new Array();
ids[0]='dsdsad';
ids[1]='tre1';
ids[2]='image';
ids[3]='image2';
ids[4]='newd';
ids[5]='txt';
function overb(obj){
color='#FF0000';
width='3px';
obj.style.borderTopWidth = width;
obj.style.borderTopColor =color;
obj.style.borderTopStyle ='solid';
obj.style.borderLeftWidth = width;
obj.style.borderLeftColor =color;
obj.style.borderLeftStyle ='solid';
obj.style.borderRightWidth = width;
obj.style.borderRightColor =color;
obj.style.borderRightStyle ='solid';
obj.style.borderBottomWidth = width;
obj.style.borderBottomColor =color;
obj.style.borderBottomStyle ='solid';
obj.style.zIndex='999';
off=box_offset(obj);
x_pic_ini=off[0];
y_pic_ini=off[2];
IMAGE=document.getElementById(obj.id);
//obj1(IMAGE,'IMAGE');
Drag.init(IMAGE);
start();
}
function outb(obj){
obj.style.borderTopWidth = '0px';
obj.style.borderLeftWidth = '0px';
obj.style.borderRightWidth = '0px';
obj.style.borderBottomWidth = '0px';
obj.style.zIndex='9'
}
//-->
</SCRIPT>
</HEAD>
<BODY onload="">
<FORM METHOD=POST ACTION="#" NAME="f1">
<div style="position:absolute;left:50;top:50;z-index:9;"
onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="canalica">xpic<INPUT TYPE="text" NAME="xpic"></div>
<div style="position:absolute;left:50;top:75;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="tre1">ypic<INPUT TYPE="text" NAME="ypic"></div>
<div style="position:absolute;left:50;top:75;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="submit">ypic<INPUT TYPE="submit" NAME="submit" value="submit"></div>
</FORM><HR>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="image">Yes!</div>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);doit(this);" onmouseout="outb(this);" id="image2">yep yep !</div>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);/*document.write(obj2(this.style,'this.style'));*/doit(this)" onmouseout="outb(this);" id="newd"><TABLE border="1px" CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="500" id="tb1" align="left" style="margin:0;">
<TR>
<TD id="i00">11</TD>
<TD id="i01">12</TD>
<TD id="i02">13</TD>
</TR>
<TR>
<TD id="i10">21</TD>
<TD id="i11">22</TD>
<TD id="i12">23</TD>
</TR>
<TR>
<TD id="i20">31</TD>
<TD id="i21">32</TD>
<TD id="i22">33</TD>
</TR>
</TABLE></div>
<FORM METHOD=POST ACTION="#" NAME="f3">
<TEXTAREA style="position:absolute;left:50;top:175;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="txt" NAME="aa" ROWS="20" COLS="20"></TEXTAREA>
</FORM>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<script type="text/javascript">
//-----------------------------------------------------
var x_pic_ini, y_pic_ini,IMAGE;
function doit(obj){
}
//------------------------------------------------------
</script>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* for(i=0;i<ids.length;i++){
oo=document.getElementById(ids[i]);
//obj1(oo,'oo');
oo.style.Left=i*20;
oo.style.Top=i*20;
//alert(ids[i]);
}*/
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
function a(val){
ww=document.f3.aa.value+val;
document.f3.aa.value=ww;
}
var div1=document.getElementById("newd");
div1.style.left=600;
div1.style.top=200;
//fiecare celula
for(i=0;i<3;i++){
for(u=0;u<3;u++){
a("i"+i+u+"=");
a(box_offset(eval(document.getElementById("i"+i+u)))+'\n');
}
}
var lastbox=null;
//doar div-ul..
//alert(box_offset(div1));
//-->
</SCRIPT>
</BODY></HTML>

Make image face movement direction html

I am trying to make an image face the direction it moves. For example, the player presses "up" and the image faces up. How would I achieve this?
Code:
Javascript
function move_img(str) {
var step=10;
switch(str){
case "down":
var x=document.getElementById('braum').offsetTop;
x= x + step;
document.getElementById('braum').style.top= x + "px";
break;
case "up":
var x=document.getElementById('braum').offsetTop;
x= x -step;
document.getElementById('braum').style.top= x + "px";
break;
case "left":
var y=document.getElementById('braum').offsetLeft;
y= y - step;
document.getElementById('braum').style.left= y + "px";
break;
case "right":
var y=document.getElementById('braum').offsetLeft;
y= y + step;
document.getElementById('braum').style.left= y + "px";
break;
}
}
Code:HTML
<img src=images/braum.png id='braum' style="position:absolute; left: 500; top: 100;">
<br><br><br><br>
<input type=image onClick=move_img('up') src="images/uparrow.png">
<br>
<input type=image onClick=move_img('left') src="images/leftarrow.png">
<input type=image onClick=move_img('right') src="images/rightarrow.png"'>
<br>
<input type=image onClick=move_img('down') src="images/downarrow.png">
</body>
</html>
Thanks for your help!
Generally your algorithm is right, but, you have many problems with your syntax and organization
you should wrap onclick value with quotation mark > onclick="move_img('...')"
In your inline CSS - you are missing px unit, so it should be > left: 500px; top: 100px
In your right button - you have an extra apostrophe in the end (before the ending > sign
Though not completely wrong, in some cases - offsetLeft and offsetTop differ from top and left - so it is not wise to use them together
In order to change the rotation you should use the transform CSS property, in order to access it by JS use element.style.transform - the value is rotate(Xdeg) where X is the degrees that you want to rotate the element by
This is a working example for such thing (I made some changes to the HTML because I don't have the images, but the logic stays the same):
function move_img(side){
var step = 10;
var element = document.getElementById('braum');
var left = parseInt(element.style.left);
var top = parseInt(element.style.top);
var rotation = 0;
switch(side){
case 'up': top-=step; rotation = -90; break;
case 'right': left+=step; rotation = 0; break;
case 'left': left-=step; rotation = 180; break;
case 'down': top+=step; rotation = 90; break;
}
element.style.top = top+'px';
element.style.left = left+'px';
element.style.transform = 'rotate('+rotation+'deg)';
}
#braum{
width: 40px;
height: 40px;
color: white;
text-align: center;
transition: transform 0.5s; /* Remove This to remove the animation */
background: green;
position:absolute;
}
<div id='braum' style="left: 100px; top: 100px;">Hi</div>
<input type="button" onclick="move_img('up')" value="up" >
<input type="button" onclick="move_img('left')" value="left" >
<input type="button" onclick="move_img('right')" value="right" >
<input type="button" onclick="move_img('down')" value="down" >

How to move one image randomly when you click on the other image using html & javascript

I am a beginner with javascript. I have two images. One is for clicking, and the other one is for moving 10px to the left & right randomly. Once I click on the "high5" image, "pic2" image has to move randomly in any direction no more than 10 pixels. Every click is added to the score to generate total score at the end. I am stuck at this point, and I don't know where to go. Can someone help me, please?
As you can see, I have edited my code. I'm still having problems in:
Creating scoreboard to keep track of how many clicks the user
clicked within 30 seconds.
I need a timer that counts 30 seconds.
Every time the picture in the middle moves, it keep going to the
left.
HTML code:
<!DOCTYPE html>
<!-- game.html
Uses game.js
Illustrates visibility control of elements
-->
<html lang="en">
<head>
<title>Visibility control</title>
<meta charset="utf-8" />
</head>
<body>
<div id="score">
0
</div>
<div id="high5" style="position: relative; left: 10px;">
<img onclick= "moveImg(); clicked();" src="pics/high5.jpg"
style="height:250px; width:250px; " alt="Minion High Five" />
</div>
<div id="pic2" style="position: relative; top: 20px; left: 650px;">
<img src="pics/pic2.gif" style="height:250px; width:350px;"/>
</div>
<script type="text/javascript" src="game.js" ></script>
</body>
</html>
javascript:
var x = 0;
var y = 0;
var timer = 30;
var count = 0;
var isDone = true;
function moveImg() {
x += Math.floor(Math.random() * 20) - 10;
y += Math.floor(Math.random() * 20) - 10;
pic2.style.left = x + "px";
pic2.style.top = y + "px";
if(timer > 0) {
setTimeout("moveImg()", 50);
timer--;
}
else {
timer = 30;
}
}
function clicked() {
timer = 30;
count++;
score.innerHTML = count;
}
Try something like this: DO not use onclick inside HTML.I have added some jquery part,if you don't need change it accordingly or let me know.
var high5,myVar;
$(function(){
$("img").on("click",function(){
console.log($(this));
if($(this).data('id') == "minion"){
high5=document.getElementById('pic2');
high5.style.left="10px";
moveImg();
}
});
setInterval(function(){ myStopFunction(); }, 3000);//call to stop shacking after 3000 miliseconds.
});
function moveImg() {
//alert("hi");
var x;
x = Math.floor(Math.random()*4)+1;
left = parseInt(high5.style.left.replace('px', ''));
console.log(x+ "," +left);
if (x==4 && left >= 10) {
high5.style.left = (left - 10) + 'px';;
}
if (x==3 && left <= 650) {
high5.style.left = (left + 10) + 'px';
}
if (x==2 && left >= 10) {
high5.style.left = (left - 10) + 'px';;
}
if (x==1 && left <= 450) {
high5.style.left = (left + 10) + 'px';
}
myVar = setTimeout(function(){moveImg();},100);
}
function myStopFunction() {
clearTimeout(myVar);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "high5" style = "position: absolute;">
<img src="pics/high5.jpg" style="height:250px; width:250px;
margin-top: 50px; margin-left: 50px; border:none;"
alt="Minion High Five" data-id="minion"/>
</div>
<div id = "pic2" style=" position: absolute; width:350px;height:250px;margin-left: 550px;border:1px solid black;margin-top:150px;">
<img src="pics/pic2.gif" style="width:350px;height:250px;" alt="Minion High Five"/>
</div>

Image zoom in and out with respect to the centre of div not working

I have an image zoom property in one of my website.I want to zoom an image with respect to the centre of the div.
<div class="img"><img src="http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/men-wedding-rings.jpg" /></div>
<input class="beta" type="button" onclick="zoom(1.1)" value="+">
<input class="beta" type="button" onclick="zoom(0.9)" value="-">
And the zoom funcction is as follows.
function zoom(zm)
{
img=document.getElementById("pic")
wid=img.width
ht=img.height
img.style.width=(wid*zm)+"px"
img.style.height=(ht*zm)+"px"
}
I want to zoom the image with respect to the centre.
Thanks in advance.
How about this http://jsfiddle.net/sajith/J6Y3X/
JS
function zoom(zm) {
img = document.getElementById("pic")
wid = img.width
ht = img.height
img.style.width = (wid * zm) + "px"
img.style.height = (ht * zm) + "px"
img.style.marginLeft = "-" + (wid * zm)/2 + "px"
img.style.marginTop = "-" + (ht * zm)/2 + "px"
}
CSS
.img {
width:450px;
height:450px;
}
#pic {
position: absolute;
left: 225px;
top: 225px;
margin: -225px 0 0 -225px;
}
HTML
<div class="img"><img id="pic" src="http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/men-wedding-rings.jpg" /></div>
<input class="beta" type="button" onclick="zoom(1.1)" value="+">
<input class="beta" type="button" onclick="zoom(0.9)" value="-">

Fix a zoom in and out coding

I am using the following coding
<html>
<head>
<style>
#thediv {
margin:0 auto;
height:400px;
width:400px;
overflow:hidden;
}
img {
position: relative;
left: 50%;
top: 50%;
}
</style>
</head>
<body>
<input type="button" value ="-" onclick="zoom(0.9)"/>
<input type="button" value ="+" onclick="zoom(1.1)"/>
<div id="thediv">
<img id="pic" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Nokota_Horses_cropped.jpg"/>
</div>
<script>
window.onload = function(){
zoom(1)
}
function zoom(zm) {
img=document.getElementById("pic")
wid=img.width
ht=img.height
img.style.width=(wid*zm)+"px"
img.style.height=(ht*zm)+"px"
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}
</script>
</body>
</html>
For making a simple zoom in and zoom out function.
I this i have a difficulty of the image is zooming indefinitely. i want to fix a position to zoom in and zoom out. The image must not exceed that position while zooming in and zooming out.
I am adding a fiddle to this link
Here you go:
var zoomLevel = 100;
var maxZoomLevel = 105;
var minZoomLevel = 95;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel++;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel--;
}else{
return;
}
}
wid = img.width;
ht = img.height;
img.style.width = (wid*zm)+"px";
img.style.height = (ht*zm)+"px";
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}​
You can modify the zoom levels to whatever you want.
I modified the fiddle a bit, since you only need to add javascript to the bottom-left area.

Categories

Resources