zoom in zoom out image on scrolling in javascript - 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

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>

Connecting images with lines

I tried to make match two pairs with lines quiz. I have couple of images on left, and couple of images on right, and I need to connect it with lines when you click on pair of images. It should work for any combinantion, so if I click for example on image 1 on left and image 3 on right, they should be connected with line. Then if I click again on image 1 on right, and image 2 on left, previous line should be deleted, and the new one between those two images need to be made.
Html snippet:
function lineDistance(x, y, x0, y0){
return Math.sqrt((x -= x0) * x + (y -= y0) * y);
};
function drawLine(a, b, line) {
var pointA = $(a ).offset();
var pointB = $(b).offset();
var pointAcenterX = $(a).width() / 2;
var pointAcenterY = $(a).height() / 2;
var pointBcenterX = $(b).width() / 2;
var pointBcenterY = $(b).height() / 2;
var angle = Math.atan2(pointB.top - pointA.top, pointB.left - pointA.left) * 180 / Math.PI;
var distance = lineDistance(pointA.left, pointA.top, pointB.left, pointB.top);
// Set Angle
$(line).css('transform', 'rotate(' + angle + 'deg)');
// Set Width
$(line).css('width', distance + 'px');
// Set Position
$(line).css('position', 'absolute');
if(pointB.left < pointA.left) {
$(line).offset({top: pointA.top + pointAcenterY, left: pointB.left + pointBcenterX});
} else {
$(line).offset({top: pointA.top + pointAcenterY, left: pointA.left + pointAcenterX});
}
}
new drawLine('.a', '.b', '.line');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question">
<div id="old" class="left_side one_half svg left">
<img class="a" src="assets/svg/Kerze.svg">
<img src="assets/svg/Telefon.svg">
<img src="assets/svg/Schreibmaschine.svg">
<img src="assets/svg/TV_old.svg">
<img src="assets/svg/Zeitstopper.svg">
<img src="assets/svg/Besen.svg">
<img src="assets/svg/Waschen.svg">
</div>
<div class="left_side one_half svg right">
<img src="assets/svg/Iwatch.svg">
<img src="assets/svg/Laptop.svg">
<img src="assets/svg/Staubsauger.svg">
<img src="assets/svg/Waschmaschine.svg">
<img src="assets/svg/TV_new.svg">
<img src="assets/svg/Gluehbirne.svg">
<img class="b" src="assets/svg/Iphone.svg">
<div class="line"></div>
</div>
</div>
I manage to make a line between two images (from class a to class b), and it is always calculated to be exactly on right angle, but I can not make it appear to work as I described above. Any ideas? Thanks.
var setLeft = false, setRight = false;
$('.leftSide img').click(function(){
$('.leftSide img').removeClass('a');
$(this).addClass('a');
setLeft = true;
new drawLine('.a', '.b', '.line');
});
$('.rightSide img').click(function(){
$('.rightSide img').removeClass('b');
$(this).addClass('b');
setRight = true;
new drawLine('.a', '.b', '.line');
});
You can use a flag variables and when click on an image from the right, set the right flag variable to be true and do the same with the other.
Then inside your function drawLine just check if the two flags are true then draw the line between a and b and set the two flag variables to false.
function lineDistance(x, y, x0, y0){
return Math.sqrt((x -= x0) * x + (y -= y0) * y);
};
function drawLine(a, b, line) {
if(setLeft && setRight){
setLeft = false;
setRight = false;
var pointA = $(a).offset();
var pointB = $(b).offset();
console.log(pointA);
console.log(pointB);
var pointAcenterX = $(a).width() / 2;
var pointAcenterY = $(a).height() / 2;
var pointBcenterX = $(b).width() / 2;
var pointBcenterY = $(b).height() / 2;
var angle = Math.atan2(pointB.top - pointA.top, pointB.left - pointA.left) * 180 / Math.PI;
var distance = lineDistance(pointA.left, pointA.top, pointB.left, pointB.top);
// Set Angle
$(line).css('transform', 'rotate(' + angle + 'deg)');
// Set Width
$(line).css('width', distance + 'px');
// Set Position
$(line).css('position', 'absolute');
if(pointB.left < pointA.left) {
$(line).offset({top: pointA.top + pointAcenterY, left: pointB.left + pointBcenterX});
} else {
$(line).offset({top: pointA.top + pointAcenterY, left: pointA.left + pointAcenterX});
}
}
}
//new drawLine('.a', '.b', '.line');
var setLeft = false, setRight = false;
$('.leftSide img').click(function(){
$('.leftSide img').removeClass('a');
$(this).addClass('a');
setLeft = true;
new drawLine('.a', '.b', '.line');
});
$('.rightSide img').click(function(){
$('.rightSide img').removeClass('b');
$(this).addClass('b');
setRight = true;
new drawLine('.a', '.b', '.line');
});
.left{
float:left;
}
.right{
float:right;
}
.one_half{
width:40%;
}
img{
max-width:100%;
}
.line{
background: red;
height:1px;
}
.question{
position: relative;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question">
<div id="old" class="left_side one_half svg left leftSide">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
</div>
<div class="left_side one_half svg right rightSide">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<div class="line"></div>
</div>
</div>

Movement Not Being Stopped

I am trying to prevent a character from crossing objects w/ a blue border. I have included some debugging comments so I can track how the code is being executed, and it seems to be fine logically. However, they way I am trying to prevent movement is not working. And I'm wondering why. Here is my code:
//My HTML Code
<div id="title">
<link rel="stylesheet" type="text/css" href="PM-style.css" media="screen" />
<script src="Pac-Man.js">
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="Pac-Man.js">
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="Grid.js">
</script>
<title> Pac-Man Game </title>
</div>
<body>
<div class="mazeboard">
<hl> WELCOME!!!</hl>
</div>
<p id="buttons">
<script src="Pac-Man.js">
</script>
<button onclick="myMove()" id="beginButton"> Begin Game </button>
<button onclick="increment()" id="pause"> &nbsp Pause &nbsp </button>
<button onclick="reset()" id="reset"> &nbsp Start Over &nbsp </button>
<button onclick="nextStage1()"> &nbsp Next &nbsp </button>
</p>
<div class='status-window'>
<h2> SCORE: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp <span> TIME: </span> <span id="output"> </span> </h2>
<script>
</script>
</div>
</div>
<div class="realm">
<canvas width="800" height="450" style="border: 2px solid blue; background-color: black; border-radius: 20px; margin: 0 auto; position: relative; align-content: center;" id="myCanvas"> </canvas>
<!-- Comment This is where the walls go! -->
<div id='game-window'>
<div id="outerwall" class="game-window" data-index="1"> </div>
<div id="left-wall" class="game-window" data-index="2"></div>
<div id="left-wallTop" class="game-window" data-index="3"></div>
<div id="left-wallMiddle" class="game-window" data-index="4"></div>
<div id="left-wallBottom1" class="game-window" data-index="5"></div>
<div id="left-wallBottom2" class="game-window" data-index="6"></div>
<div id="top-wall" class="game-window" data-index="7"></div>
<div id="middle-wall1" class="game-window" data-index="8"></div>
<div id="middle-wall2" class="game-window" data-index="9"></div>
<div id="right-wall" class="game-window" data-index="10"></div>
<div id="center-block" class="game-window" data-index="11"> </div>
<div id="bottom-block1" class="game-window" data-index="12"></div>
<div id="bottom-block2" class="game-window" data-index="13"></div>
<div id="bottom-block3" class="game-window" data-index="14"></div>
<div id="bottom-block4" class="game-window" data-index="15"></div>
<div id="right-bottom1" class="game-window" data-index="16"></div>
<div id="right-bottom2" class="game-window" data-index="17"></div>
<div id="right-bottom" class="game-window" data-index="18"></div>
<div id="center2" class="game-window" data-index="19"></div>
<div id="opencenter" class="game-window" data-index="20"></div>
<div id="center3" class="game-window" data-index="21"></div>
<div id="hole1" class="game-window" data-index="22"></div>
<div id="hole2" class="game-window" data-index="23"></div>
<div id="hole3" class="game-window" data-index="24"></div>
<div id="hole4" class="game-window" data-index="25"></div>
<div></div>
</div>
<script type="text/javascript" src="Pac-man.js"></script>
<script type="text/javascript" src="Ghost.js"></script>
<script type="text/javascript" src="Grid.js"></script>
<script type="text/javascript" src="Game.js"></script>
<script>
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
}
</script>
<div id='pacman' class='realm'> <img src="https://cdn.pixabay.com/photo/2012/04/14/17/12/pacman-34643_960_720.png" id="pacman"> </div>
<div id='ghost' class='realm'> <img src="https://cdn.pixabay.com/photo/2013/07/12/12/31/pacman-145852_960_720.png" id="ghost"> </div>
</div>
</body>
<footer>
</footer>
</html>
//Moving the Pacman Character (JAVASCRIPT)
$(document).ready(function() {
console.log('jQuery has loaded!');
console.log("Ready!");
$pacman = $(document.getElementById('pacman'));
pacman = $pacman;
STEP_SIZE = 15;
var keys = {};
document.getElementById("beginButton").onclick = function() {
gameStart()
};
function gameStart() {
start();
pacManPositions = {
'left': parseInt(pacman.css('left')),
'right': parseInt(pacman.css('left')) + pacman.width(),
'top': parseInt(pacman.css('top')),
'bottom': parseInt(pacman.css('top')) + pacman.height()
};
//Setting up conditions to determine movement or not
collision2 = false;
collisions = true;
function collision() {
$(".game-window").each(function() {
var walls = document.getElementsByTagName("div");
walls = $(this);
for (var i = 0; i < walls.length; i++) {
var name = walls[i].getAttribute('id');
var border = $(this).css('border-color');
var position = $(this).position();
if (border == 'rgb(0, 0, 255)') {
wallPositions = {
'left': position.left,
'right': position.left + $(this).width(),
'top': position.top,
'bottom': position.top + pacman.height()
};
pacManPositions = {
'left': parseInt(pacman.css('left')),
'right': parseInt(pacman.css('left')) +
pacman.width(),
'top': parseInt(pacman.css('top')),
'bottom': parseInt(pacman.css('top')) +
pacman.height()
};
if ((pacManPositions.left <= wallPositions.left && pacManPositions.right >= wallPositions.left) ||
(pacManPositions.left <= wallPositions.right && pacManPositions.right >= wallPositions.right) ||
(pacManPositions.left <= wallPositions.right && pacManPositions.right >= wallPositions.left)) {
if ((pacManPositions.top >= wallPositions.top && pacManPositions.top <= wallPositions.bottom) ||
(pacManPositions.top <= wallPositions.top && pacManPositions.top >= wallPositions.bottom - 33) ||
(pacManPositions.top >= wallPositions.top && pacManPositions.bottom <= wallPositions.bottom)) {
collisions = false;
return true;
collision2 = true;
}
}
}
}
});
}
//Moving Pac Man w/ Keys
$(document).on('keydown', movePacman);
function movePacman(event) {
console.log(event.which);
switch (event.which) {
//moving right
case 39:
console.log('right');
// pacman.css("left", (pacman.position().left + 10) + "px");
// var leftVal = pacman.css("left", (pacman.position().left + 10) + "px");
var leftVal = parseInt(pacman.css('left')) + STEP_SIZE;
if (leftVal > ($('#outerwall').width() - pacman.width())) {
leftVal = ($('#outerwall').width() - pacman.width()) - 0;
}
collision();
if (collision() == true) {
var leftVal = 0;
$('#pacman').css('left', leftVal);
} else {
$('#pacman').css('left', leftVal);
break;
}
break;
//moving down
case 40:
console.log('down');
var downVal = parseInt(pacman.css('top')) + STEP_SIZE;
if (downVal > ($('#outerwall').height() + pacman.height()) - 70) {
downVal = ($('#outerwall').height()) - pacman.height() + 1;
}
collision();
if (collision() == true) {
} else {
$('#pacman').css('top', downVal);
break;
}
break;
//moving left
case 37:
console.log('left');
var leftVal = parseInt(pacman.css('left')) - STEP_SIZE;
if (leftVal < 0) {
leftVal = ($('#outerwall').width()) - 780;
//parseInt(pacman.css('left'));
}
collision();
if (collision() == true) {
} else {
$('#pacman').css('left', leftVal);
break;
}
// break;
//moving up
case 38:
console.log('up');
var topVal = parseInt(pacman.css('top')) - STEP_SIZE;
if (topVal < 0) {
topVal = ($('#outerwall').height()) - 430;
}
collision();
if (collision() == true) {
} else {
$('#pacman').css('top', topVal);
break;
}
break;
// break;
//breaking
case 32:
console.log('break');
break;
}
}
}
})

How to set total height on Jinvert Scroll

I've created a horizontal scrolling website with parallax using Jquery Plugin called Jinvertscroll. However, the scrolling stops before reaching the end of the page. Demo at https://dl.dropboxusercontent.com/u/246684898/VipSitaraman.com/examples/index.htm. Please tell me how to change the total scroll length on the plug in.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vip Sitaraman</title>
<link rel="stylesheet" href="css/example.css" />
<body style="background-color:#383938">
<div id="main">
<div class="suit scroll">
<img id="animation" src="images/1.png" alt="" />
</div>
<div class="plane scroll">
<img class="plane" src="images/plane.png" alt="" />
</div>
<div class="pinned scroll">
<a id="navv">< </a><a id="nav"> ></a>
</div>
<div class="bg scroll">
<img src="images/bg.jpg" alt="" />
</div>
<div class="horizon scroll">
<img src="images/horizon_01.png" alt="" />
</div>
<div class="middle scroll">
<img src="images/middle_01.png" alt="" />
</div>
<div class="front scroll">
<img src="images/front_01.png" alt="" />
</div>
<div class="research scroll" id="research">
</div>
<div class="music scroll" id="music">
</div>
</div>
</div>
</div>
<script type="text/javascript" src="../libs/jquery.min.js"></script>
<script type="text/javascript" src="../dist/js/jquery.jInvertScroll.js"></script>
<script type="text/javascript">
(function($) {
$.jInvertScroll(['.scroll'], // an array containing the selector(s) for the elements you want to animate
{
height: 3000, // optional: define the height the user can scroll, otherwise the overall length will be taken as scrollable height
onScroll: function(percent) { //optional: callback function that will be called when the user scrolls down, useful for animating other things on the page
console.log(percent);
}
});
}(jQuery));
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var b = 300
var bodyHeight = $("body").height()-$(window).height();
window.onscroll = function() {
if($('#animation').attr('src') != 'images/suit.gif'){
$('#animation').attr('src','images/suit.gif');
};
};
});//]]>
</script>
<script type='text/javascript'>//<![CDATA[
$(function (){
var sdegree = 0;
var orig = 0;
var z = 1 + Math.random() * 20
$(window).scroll(function () {
if (sdegree > -10 && sdegree < 10 && sdegree - orig >= 0) {
orig = sdegree;
sdegree = sdegree + 1;
} else if (sdegree > -10 && sdegree < 10 && sdegree - orig < 0) {
orig = sdegree;
sdegree = sdegree - 1;
} else if (sdegree <= -10) {
orig = sdegree;
sdegree = sdegree + 1;
} else if (sdegree >= 10) {
orig = sdegree;
sdegree = sdegree - 1;
} else {
orig = sdegree;
}
var srotate = "rotate(" + sdegree + "deg)";
$('.plane').css('z-index','z');
$(".plane").css({
transform: srotate
});
});
});
//]]>
</script>
<script type="text/javascript">
$(function() {
$("#nav").click(function() {
$('html,body').animate({
scrollTop: $(document).scrollTop()+800
}, 1000);
if($('#animation').attr('src') != 'images/suit.gif'){
$('#animation').attr('src','images/suit.gif');
}
});
});
</script>
<script type="text/javascript">
$(function() {
$("#navv").click(function() {
$('html,body').animate({
scrollTop: $(document).scrollTop()-800
}, 1000);
});
});
</script>
</body>
</html>
If all you need is to define size, here's what you are looking for:
$.jInvertScroll(['.myScrollableElements'], {
width: 'auto', // Page width (auto or int value)
height: 'auto', // Page height (the shorter, the faster the scroll)
onScroll: function(percent) {
// Callback function that will be called each time the user
// scrolls up or down, useful for animating other parts
// on the page depending on how far the user has scrolled down
// values go from 0.0 to 1.0 (with 4 decimals precision)
}
});
SOURCE

Sticky box jQuery

I have this code:
http://jsfiddle.net/k56yR/1/
but when the browser scrollbar is down and begin to top #sticky trembles, anyone know how to fix this?
This is jQuery code:
$(function(){ // document ready
if (!!$('#sticky').length) { // make sure "#sticky" element exists
var el = $('#sticky');
var stickyTop = $('#sticky').offset().top; // returns number
var footerTop = $('#footer').offset().top; // returns number
var stickyHeight = $('#sticky').height();
var limit = footerTop - stickyHeight - 20;
$(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});​
<div class="wrapper">
<div class="results">
</div>
<header>
Header
<span></span>
</header>
<div class="left">
<span class="top"></span>
<div class="nosticky">Nosticky</div>
<div class="sticky">
<span class="top"></span>
<div class="bloc bloc1">
Bloc 1<br>
<span></span>
</div>
<div class="bloc bloc2">
Bloc 2
</div>
<span class="bottom"></span>
</div>
<span class="bottom"></span>
</div>
<div class="right">
Content
<span></span>
</div>
<div class="footer">
Footer
</div>
</div>
<script>
var sticky_offsettop = $('.sticky').offset().top;
var sticky_height = $('.sticky').height();
var sidebar_height = $('.left').height();
var empty_space_left = sidebar_height - sticky_height;
var sidebar_offsettop = $('.left').offset().top;
var sidebar_bottom_offsettop = (sidebar_offsettop+sidebar_height);
var margintotop = 20;
$(window).scroll(function() {
var window_scrolltop = $(window).scrollTop();
var window_scrolltop_margin = (window_scrolltop+margintotop);
var realtime_sidebar_bottom_offsettop = (sidebar_bottom_offsettop - window_scrolltop);
var sticky_height_realtime = $('.sticky').height();
if(window_scrolltop_margin >= sticky_offsettop ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'sticky').css('top', '20px').css('bottom', 'initial');
}
if(sticky_offsettop > window_scrolltop_margin ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'relative').css('top', 'initial').css('bottom', 'initial');
}
if(sticky_height_realtime >= realtime_sidebar_bottom_offsettop ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'absolute').css('top', 'initial').css('position', 'absolute').css('bottom', '0');
}
});
<script>
here is an example i've done to achieve it : https://jsfiddle.net/cuopyL51/

Categories

Resources