How to moves the divs by clicking on each one - javascript

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>

Related

zoom in zoom out image on scrolling in javascript

I created tabs with image.When I scroll on the image it will zoom in and zoom out. But I am facing the problem,in only first tab it is working with function zoom in & zoom out(when i scroll).I didn't get what i'm doing wrong.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>zoom</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
ul li{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
</ul>
</span>
</div>
<div class="panel-body">
<br />
<br />
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="container">
<div class="slide">
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab2">
<div class="container">
<div class="slide">
<img class='zoom' src='abc.jpg' alt='abc' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab3">
<div class="container">
<div class="slide">
<img class='zoom' src='xy.jpg' alt='xy' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab4">
<div class="container">
<div class="slide">
<img class='zoom' src='rec.png' alt='rec' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- <img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
<br />
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/> -->
<script src="wheelzoom.js"></script>
<script>
wheelzoom(document.querySelector('img.zoom'));
</script>
</body>
</html>
wheelzoom.js
window.wheelzoom = (function(){
var defaults = {
zoom: 0.10,
maxZoom: false,
initialZoom: 1,
};
var main = function(img, options){
if (!img || !img.nodeName || img.nodeName !== 'IMG') { return; }
var settings = {};
var width;
var height;
var bgWidth;
var bgHeight;
var bgPosX;
var bgPosY;
var previousEvent;
var cachedDataUrl;
function setSrcToBackground(img) {
img.style.backgroundRepeat = 'no-repeat';
img.style.backgroundImage = 'url("'+img.src+'")';
cachedDataUrl = 'data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" width="'+img.naturalWidth+'" height="'+img.naturalHeight+'"></svg>');
img.src = cachedDataUrl;
}
function updateBgStyle() {
if (bgPosX > 0) {
bgPosX = 0;
} else if (bgPosX < width - bgWidth) {
bgPosX = width - bgWidth;
}
if (bgPosY > 0) {
bgPosY = 0;
} else if (bgPosY < height - bgHeight) {
bgPosY = height - bgHeight;
}
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
}
function reset() {
bgWidth = width;
bgHeight = height;
bgPosX = bgPosY = 0;
updateBgStyle();
}
function onwheel(e) {
var deltaY = 0;
e.preventDefault();
if (e.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
// As far as I know, there is no good cross-browser way to get the cursor position relative to the event target.
// We have to calculate the target element's position relative to the document, and subtrack that from the
// cursor's position relative to the document.
var rect = img.getBoundingClientRect();
var offsetX = e.pageX - rect.left - window.pageXOffset;
var offsetY = e.pageY - rect.top - window.pageYOffset;
// Record the offset between the bg edge and cursor:
var bgCursorX = offsetX - bgPosX;
var bgCursorY = offsetY - bgPosY;
// Use the previous offset to get the percent offset between the bg edge and cursor:
var bgRatioX = bgCursorX/bgWidth;
var bgRatioY = bgCursorY/bgHeight;
// Update the bg size:
if (deltaY < 0) {
bgWidth += bgWidth*settings.zoom;
bgHeight += bgHeight*settings.zoom;
} else {
bgWidth -= bgWidth*settings.zoom;
bgHeight -= bgHeight*settings.zoom;
}
if (settings.maxZoom) {
bgWidth = Math.min(width*settings.maxZoom, bgWidth);
bgHeight = Math.min(height*settings.maxZoom, bgHeight);
}
// Take the percent offset and apply it to the new size:
bgPosX = offsetX - (bgWidth * bgRatioX);
bgPosY = offsetY - (bgHeight * bgRatioY);
// Prevent zooming out beyond the starting size
if (bgWidth <= width || bgHeight <= height) {
reset();
} else {
updateBgStyle();
}
}
function drag(e) {
e.preventDefault();
bgPosX += (e.pageX - previousEvent.pageX);
bgPosY += (e.pageY - previousEvent.pageY);
previousEvent = e;
updateBgStyle();
}
function removeDrag() {
document.removeEventListener('mouseup', removeDrag);
document.removeEventListener('mousemove', drag);
}
// Make the background draggable
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
function load() {
var initial = Math.max(settings.initialZoom, 1);
if (img.src === cachedDataUrl) return;
var computedStyle = window.getComputedStyle(img, null);
width = parseInt(computedStyle.width, 10);
height = parseInt(computedStyle.height, 10);
bgWidth = width * initial;
bgHeight = height * initial;
bgPosX = -(bgWidth - width)/2;
bgPosY = -(bgHeight - height)/2;;
setSrcToBackground(img);
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
img.addEventListener('wheelzoom.reset', reset);
img.addEventListener('wheel', onwheel);
img.addEventListener('mousedown', draggable);
}
var destroy = function (originalProperties) {
img.removeEventListener('wheelzoom.destroy', destroy);
img.removeEventListener('wheelzoom.reset', reset);
img.removeEventListener('load', load);
img.removeEventListener('mouseup', removeDrag);
img.removeEventListener('mousemove', drag);
img.removeEventListener('mousedown', draggable);
img.removeEventListener('wheel', onwheel);
img.style.backgroundImage = originalProperties.backgroundImage;
img.style.backgroundRepeat = originalProperties.backgroundRepeat;
img.src = originalProperties.src;
}.bind(null, {
backgroundImage: img.style.backgroundImage,
backgroundRepeat: img.style.backgroundRepeat,
src: img.src
});
img.addEventListener('wheelzoom.destroy', destroy);
options = options || {};
Object.keys(defaults).forEach(function(key){
settings[key] = options[key] !== undefined ? options[key] : defaults[key];
});
if (img.complete) {
load();
}
img.addEventListener('load', load);
};
// Do nothing in IE9 or below
if (typeof window.btoa !== 'function') {
return function(elements) {
return elements;
};
} else {
return function(elements, options) {
if (elements && elements.length) {
Array.prototype.forEach.call(elements, main, options);
} else if (elements && elements.nodeName) {
main(elements, options);
}
return elements;
};
}
}());
When i scroll it is zoom in and zoom out but only in first tab.What I did wrong,i can't understand.Please help me.Thank you.
Nice work i worked it out and find that you are using wheelzoom(document.querySelector('img.zoom')); here in this code you are using querySelector where this code will return only one element not all element instead of this code you need to use wheelzoom(document.querySelectorAll('img.zoom')); then your example will work . I have tried and its working

I want to make a game to count the number of clicks on the image in 1 minute

I've made this code to make a game that counts the number of clicks on the moving image .. but i can't make the Countdown or the counter .. i want when the user press start the game an countdown begins .. and every click on the image the number in (the counter) increased by one .. Thnx
var x_position = 0 ;
var theSpace = document.getElementById("gamespace");
var textt=document.getElementById("text");
var theMission = document.createTextNode(" - Press the tree as fast as you can ");
var theTree = document.createElement("img");
var moving;
function movingf() {
theSpace.appendChild(theTree);
theTree.style.left=Math.floor(Math.random() * 401) + "px";
theTree.style.right=Math.floor(Math.random() * 401) + "px";
theTree.style.top=Math.floor(Math.random() * 401) + "px";
theTree.style.bottom=Math.floor(Math.random() * 401) + "px";
moving=setTimeout(movingf,500);
theTree.addEventListener("click",theCounter);
}
function theGame() {
textt.style.clear="both";
theTree.setAttribute("src","http://franklinccc.org/wp-content/uploads/2014/03/ccc-tree-logo.jpg");
theTree.style.position="absolute";
theSpace.appendChild(theTree);
textt.appendChild(theMission);
moving=setTimeout(movingf,50);
theTree.onclick = theCounter();
}
function theCounter() {
var time = 0;
time = time + 1 ;
var theCount = document.getElementById("times").innerHTML=time;
}
#gamespace{
border:2px solid black ;
width:500px;
height:500px;
top:215px;}
p{position:absolute;
border:1px solid black;}
button{position:absolute;
top:60px;}
#here{position:absolute;
top:45px;
}
<h1> PICTURE GAME .. </h1>
<button id="start" onclick="theGame()"> Press here to start the game</button>
<div id="here">
<form action="/action_page.php" id="here">
The countdown :
<input type="text" name="firstname" value="0" >
The counter :
<input type="text" name="lastname" value="0">
</form>
</div>
<p id="text" style="top:170px"></p>
<div id="gamespace" style="position:absolute"> </div>
You have an error in your javascript :
"message": "Uncaught TypeError: Cannot set property 'innerHTML' of null",
here :
var theCount = document.getElementById("times").innerHTML=time;
You have no element with the id = "times", so if you want the <p> element to contain the count, change the line to :
var theCount = document.getElementById("text").innerHTML=time;
Also, theCounter() function should be like this :
function theCounter() {
time = time + 1 ;
document.getElementById("text").innerHTML=time;
}
var x_position = 0 ;
var theSpace = document.getElementById("gamespace");
var textt=document.getElementById("text");
var theMission = document.createTextNode(" - Press the tree as fast as you can ");
var theTree = document.createElement("img");
var moving ;
var time = 0;
function movingf() {
theSpace.appendChild(theTree);
theTree.style.left=Math.floor(Math.random() * 401) + "px";
theTree.style.right=Math.floor(Math.random() * 401) + "px";
theTree.style.top=Math.floor(Math.random() * 401) + "px";
theTree.style.bottom=Math.floor(Math.random() * 401) + "px";
moving=setTimeout(movingf,500);
theTree.addEventListener("click",theCounter);
}
function theGame() {
textt.style.clear="both";
theTree.setAttribute("src","http://franklinccc.org/wp-content/uploads/2014/03/ccc-tree-logo.jpg");
theTree.style.position="absolute";
theSpace.appendChild(theTree);
textt.appendChild(theMission);
moving=setTimeout(movingf,50);
theTree.onclick = theCounter();
}
function theCounter() {
time = time + 1 ;
document.getElementById("text").innerHTML=time;
}
#gamespace {
border: 2px solid black ;
width: 500px;
height: 500px;
top: 215px;
}
p {
position: absolute;
border: 1px solid black;
}
button {
position: absolute;
top: 60px;
}
#here {
position: absolute;
top: 45px;
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1> PICTURE GAME .. </h1>
<button id="start" onclick="theGame()"> Press here to start the game</button>
<div id="here">
<form action="/action_page.php" id="here">
The countdown :
<input type="text" name="firstname" value="0" >
The counter :
<input type="text" name="lastname" value="0">
</form>
</div>
<p id="text" style="top:170px"></p>
<div id="gamespace" style="position:absolute"> </div>
</body>
You were trying to reset your counter inside the theCounter function each time it was called, also tried to set innerHTML of element with id that was not in your markup. After fixing this this you can use setInterval to implement timer countdown:
var x_position = 0 ;
var theSpace = document.getElementById("gamespace");
var textt=document.getElementById("text");
var theMission = document.createTextNode(" - Press the tree as fast as you can ");
var theTree = document.createElement("img");
var moving;
function movingf() {
theTree.style.left=Math.floor(Math.random() * 401) + "px";
theTree.style.right=Math.floor(Math.random() * 401) + "px";
theTree.style.top=Math.floor(Math.random() * 401) + "px";
theTree.style.bottom=Math.floor(Math.random() * 401) + "px";
}
var clicks = 0, gameTimer, movingfTimer, timeleft;
theSpace.appendChild(theTree);
function theGame() {
clicks = 0;
timeleft = 30;
document.getElementById("times").value = clicks;
document.getElementById("countdown").value = timeleft;
textt.style.clear="both";
theTree.setAttribute("src","http://franklinccc.org/wp-content/uploads/2014/03/ccc-tree-logo.jpg");
theTree.style.position="absolute";
theSpace.appendChild(theTree);
textt.appendChild(theMission);
theTree.addEventListener("click", theCounter);
movingf();
clearInterval(movingfTimer);
clearInterval(gameTimer);
movingfTimer = setInterval(movingf, 500);
gameTimer = setInterval(function(){
timeleft--;
document.getElementById("countdown").value = timeleft;
if(timeleft <= 0){
clearInterval(gameTimer);
clearInterval(movingfTimer);
theTree.removeEventListener("click", theCounter);
}
}, 1000);
}
function theCounter() {
clicks++;
document.getElementById("times").value = clicks;
}
#gamespace {
border:2px solid black ;
width:500px;
height:500px;
top:215px;
}
p {
position:absolute;
border:1px solid black;
}
button {
position:absolute;
top:60px;
}
#here {
position:absolute;
top:45px;
}
<h1> PICTURE GAME .. </h1>
<button id="start" onclick="theGame()"> Press here to start the game</button>
<div id="here">
<form action="/action_page.php" id="here">
The countdown :
<input type="text" name="countdown" id="countdown" />
The counter :
<input type="text" name="times" id="times" value="0" />
</form>
</div>
<p id="text" style="top:170px"></p>
<div id="gamespace" style="position:absolute"> </div>

Why does the script not work?

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' >

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.

audio onprogress in chrome not working

I am having a problem getting onprogress event for the audio tag working on chrome. it seems to work on fire fox.
http://www.scottandrew.com/pub/html5audioplayer/ works on chrome but there is no progress bar update. When I copy the code and change the src to a .wav file and run it on fire fox it works perfectly.
<style type="text/css">
#content
{
clear:both;
width:60%;
}
.player_control
{
float:left;
margin-right:5px;
height: 20px;
}
#player
{
height:22px;
}
#duration
{
width:400px;
height:15px;
border: 2px solid #50b;
}
#duration_background
{
width:400px;
height:15px;
background-color:#ddd;
}
#duration_bar
{
width:0px;
height:13px;
background-color:#bbd;
}
#loader
{
width:0px;
height:2px;
}
.style1
{
height: 35px;
}
</style>
<script type="text/javascript">
var audio_duration;
var audio_player;
function pageLoaded() {
audio_player = $("#aplayer").get(0);
//get the duration
audio_duration = audio_player.duration;
$('#totalTime').text(formatTimeSeconds(audio_player.duration));
//set the volume
}
function update(){
//get the duration of the player
dur = audio_player.duration;
time = audio_player.currentTime;
fraction = time/dur;
percent = (fraction*100);
wrapper = document.getElementById("duration_background");
new_width = wrapper.offsetWidth*fraction;
document.getElementById("duration_bar").style.width = new_width + "px";
$('#currentTime').text(formatTimeSeconds(audio_player.currentTime));
$('#totalTime').text(formatTimeSeconds(audio_player.duration));
}
function formatTimeSeconds(time) {
var minutes = Math.floor(time / 60);
var seconds = "0" + (Math.floor(time) - (minutes * 60)).toString();
if (isNaN(minutes) || isNaN(seconds))
{
return "0:00";
}
var Strseconds = seconds.substr(seconds.length - 2);
return minutes + ":" + Strseconds;
}
function playClicked(element){
//get the state of the player
if(audio_player.paused)
{
audio_player.play();
newdisplay = "||";
}else{
audio_player.pause();
newdisplay = ">";
}
$('#totalTime').text(formatTimeSeconds(audio_player.duration));
element.value = newdisplay;
}
function trackEnded(){
//reset the playControl to 'play'
document.getElementById("playControl").value=">";
}
function durationClicked(event){
//get the position of the event
clientX = event.clientX;
left = event.currentTarget.offsetLeft;
clickoffset = clientX - left;
percent = clickoffset/event.currentTarget.offsetWidth;
duration_seek = percent*audio_duration;
document.getElementById("aplayer").currentTime=duration_seek;
}
function Progress(evt){
$('#progress').val(Math.round(evt.loaded / evt.total * 100));
var width = $('#duration_background').css('width')
$('#loader').css('width', evt.loaded / evt.total * width.replace("px",""));
}
function getPosition(name) {
var obj = document.getElementById(name);
var topValue = 0, leftValue = 0;
while (obj) {
leftValue += obj.offsetLeft;
obj = obj.offsetParent;
}
finalvalue = leftValue;
return finalvalue;
}
function SetValues() {
var xPos = xMousePos;
var divPos = getPosition("duration_background");
var divWidth = xPos - divPos;
var Totalwidth = $('#duration_background').css('width').replace("px","")
audio_player.currentTime = divWidth / Totalwidth * audio_duration;
$('#duration_bar').css('width', divWidth);
}
</script>
</head>
<script type="text/javascript" src="js/MousePosition.js" ></script>
<body onLoad="pageLoaded();">
<table>
<tr>
<td valign="bottom"><input id="playButton" type="button" onClick="playClicked(this);" value=">"/></td>
<td colspan="2" class="style1" valign="bottom">
<div id='player'>
<div id="duration" class='player_control' >
<div id="duration_background" onClick="SetValues();">
<div id="loader" style="background-color: #00FF00; width: 0px;"></div>
<div id="duration_bar" class="duration_bar"></div>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td>
<span id="currentTime">0:00</span>
</td>
<td align="right" >
<span id="totalTime">0:00</span>
</td>
</tr>
</table>
<audio id='aplayer' src='<%=getDownloadLink() %>' type="audio/ogg; codecs=vorbis" onProgress="Progress(event);" onTimeUpdate="update();" onEnded="trackEnded();" >
<b>Your browser does not support the <code>audio</code> element. </b>
</audio>
</body>
Chrome doesn't fire the progress event when it has the media in cache, that might be your problem.
The progress event doesn't fire in Chrome for WAV files but it does for MP3.
There is a known timeupdate bug: http://code.google.com/p/chromium/issues/detail?id=25185.

Categories

Resources