Why does the script not work? - javascript

I tried to make an on-click div appear draggable div. Searched the right javascript in Google but when I copied it to my html then it does not work. Could someone please explain why and how to fix it?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script type="text/javascript" src="script.js"></script>
<link type="text/css"href="./Style.css" rel="stylesheet">
<link type="text/javascript"href="./Style.js" rel="stylesheet">
</head>
<body>
<span class="about" id="but01">Click on me 1</span>
<span class="about" id="but02">Click on me 2</span>
<div id="s1" class="hidden" id="draggable-element">
<div id="draggable-element">Text here</div>
</div>
<div id="s2" class="hidden">2</div>
</body>
</html>
The CSS:
body{
background-color: #101010;
color: #ff9900;
}
.hidden{
display:none;
}
[draggable=true] {
cursor: move;
}
#draggable-element {
width:100px;
height:100px;
background-color:#ff9900;
color:white;
padding:10px 12px;
cursor:move;
position:relative; /* important (all position that's not `static`) */
}
The JS:
$('span[id^="but0"]').click(function(){
var id = $(this).attr('id').substr(4);
if($('#s' + id).is(':visible'))
$('#s' + id).hide();
else
$('#s' + id).show();
});
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;+

I found the + sign at the end of the last line. By removing it, I see it working as in the example below.
document.onmouseup = _destroy;+
Here is the example:
$('span[id^="but0"]').click(function() {
var id = $(this).attr('id').substr(4);
if ($('#s' + id).is(':visible'))
$('#s' + id).hide();
else
$('#s' + id).show();
});
var selected = null, // Object of the element to be moved
x_pos = 0,
y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0,
y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function() {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
body {
background-color: #101010;
color: #ff9900;
}
.hidden {
display: none;
}
[draggable=true] {
cursor: move;
}
#draggable-element {
width: 100px;
height: 100px;
background-color: #ff9900;
color: white;
padding: 10px 12px;
cursor: move;
position: relative;
/* important (all position that's not `static`) */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<span class="about" id="but01">Click on me 1</span>
<span class="about" id="but02">Click on me 2</span>
<div id="s1" class="hidden" id="draggable-element">
<div id="draggable-element">Text here</div>
</div>
<div id="s2" class="hidden">2</div>

Change this part:
<link type="text/javascript"href="./Style.js" rel="stylesheet">
to
<script src='./Style.js' >

Related

Moving a rectangle up down left and right

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>

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>

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>

Getting mouse click position on image in javascript?

I wrote below code to get co-ordinate of x/y in JAVASCRIPT , it's not working .
I want to create a color picker using this image
when ever some one click on button pick color then it prompts a window with color and button cancel , When user clicked on image than i need to find x/y co-ordinate so that i can specify which color it is .
Problem is that these alerts are not working
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display:none;
position: fixed;
background: #f2f2f2;
border-radius:5px;
z-index: 10;
}
#dialogboxhead{background:white;height:40px;margin:10px;}
#text {float:left; text-align:center;margin:10px; font-size:19px;}
#cancel{float:left;margin:9px;}
#image{
margin-top:0px;
padding:10px;
}
</style>
<script type="text/javascript">
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function position(e){
var offsetl = document.getElementById('image').offsetLeft;
var offsett = document.getElementById('image').offsetTop;
alert(offsetl);
alert(offsett);
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
}
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div id="dialogboxhead">
<p id="text">Select color</p>
<input type="button" onClick="Alert.cancel()" id="cancel" name="Cancel" value="Cancel"/>
</div>
<div>
<img id="image" src="color.png" onClick="position()"/>
</div>
</div>
<button onclick="Alert.render('Hello World');" >pick color </button>
</body>
</html>
I recommend use jQuery and attach click event handler in you image. The event object return in jQuery include two properties, pageX and pageY. This properties contains mouse position relative to the top edge of the document (jQuery Event Object). The code look like this:
$(document).ready(function () {
$('img#image').click(position);
});
function position(e) {
var offsetX = e.pageX,
offsetY = e.page;
}
The sample is in JSFiddle http://jsfiddle.net/zV3dH/.
I hope this help you.
Try this code buddy.. Sure it works
function getClickPos(e) {
return {x:e.clientX,y:e.clientY};
}
Now u can use it like this:
document.querySelector("#img").onclick = function(e) {
var pos= getClickPos(e);
alert(pos.x);
};

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