How to reload a function(event) - javascript

I have a div having position: fixed; otherwise at a certain time on scroll down it's having position: absolute;.
My issue is that the position: fixed; of my div depends on the top of my footer. However the top of my footer changes but not the limit of the part where my div should be 'fixed'. Maybe the code would be more clear :
html :
<div id="header" style="height:500px; width:800px; border: 5px solid green; " >
header
</div>
<div id="top" style="height:3000px; width:800px; border: 5px solid yellow; " >
<button onclick="ReduceSize()"> Reduce size </button>
<div id="comment" style="padding-bottom:30px; height:700px; width : 300px; margin-left:30px; border: 5px solid orange;" >
</div>
</div>
<div id="bottom" style="height:3000px; width:800px; border: 5px solid green; " >
footer
</div>
js :
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'>
</script>
<script>
function ReduceSize() {
var obj = document.getElementById('top');
obj.style.height = "750px";
}
$(document).ready(function () {
var haut = $('#comment').offset().top;
var hautBottom = $('#bottom').offset().top - parseFloat( $('#comment').css('height').replace(/auto/, 0) ) ;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if( (y >= (haut-20) ) && (y < hautBottom ) ) {
$('#comment').css({ position: 'fixed', top:20 });
}else{
if(y >= haut){
$('#comment').css({ position: 'absolute', top:hautBottom });
}
if(y < hautBottom ){
$('#comment').css({ position: 'absolute', top:parseFloat( $('#top').offset().top) });
};
};
});
});
</script>
Thanks in advance.

It is not 100% clear for me, what you want to achieve, but I think this is it:
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
<script>
function ReduceSize() {
$(content).css('height', '600px');
set_comment_position();
}
function set_comment_position(){
var header = $('#header');
var comment = $('#comment');
var footer = $('#footer');
var scroll = $(window).scrollTop();
var header_height = header.outerHeight();
var comment_height = comment.outerHeight();
var comment_distance_top = header_height - scroll;
var footer_offset_top = footer.offset().top;
var footer_distance_top = footer_offset_top - scroll;
var comment_distance_footer = footer_distance_top - comment_height;
if (comment_distance_top <= 0) {
if (comment_distance_footer > 0) {
comment.css({
position: 'fixed',
top: '0px',
bottom : 'auto'
});
} else {
comment.css({
position: 'absolute',
top: 'auto',
bottom: '0px'
});
}
} else {
comment.css({
position: 'absolute',
top: '0px',
bottom : 'auto'
});
}
}
$(document).ready(function(){
set_comment_position()
});
$(window).scroll(function(){
set_comment_position();
});
</script>
</head>
<body>
<div id="header" style="height:100px; width:800px; background-color: lightgreen; " >
header
</div>
<div id="content" style="height:800px; width:800px; background-color: lightgrey; position: relative;" >
<div id="comment" style="height:400px; width : 300px; background-color: orange; position: absolute; top: 0px;" >
comment
<button onclick="ReduceSize()"> Reduce size </button>
</div>
</div>
<div id="footer" style="height:800px; width:800px; background-color: lightgreen; " >
footer
</div>
</body>
</html>
The point is to wrap the positioning logic into one separate function and call this function on docready, scroll and resize.

Related

How to move parent div when child div touches parent div boundaries

I have three div's in the following code.
<div id="wrap">
<div id="outer">
<div id="inner">
</div>
</div>
</div>
Here "inner" div is moving with mouseMove event. How can I move "outer" div along with "inner" div when "inner" div touches the top and left of "outer" div but "outer" div should not move when "inner" div inside or don't touch "outer" div?
var innerDiv = $('#inner');
var outerDiv = $('#outer');
var outDim = outerDiv.offset();
outDim.right = (outDim.left + outerDiv.width());
outDim.bottom = (outDim.top + outerDiv.height());
$(document).on('mousemove', function(e) {
var x = (e.clientX) - 15;
var y = (e.clientY) - 15;
var x_allowed = x >= outDim.left && x <= (outDim.right - innerDiv.width());
var y_allowed = y >= outDim.top && y <= (outDim.bottom - innerDiv.height());
if (y_allowed) {
innerDiv.css({
top: y + 'px',
});
} else {
//fine tune tweaks
if (y >= outDim.top) {
innerDiv.css({
top: (outDim.bottom - innerDiv.height()) + 'px',
});
}
if (y <= (outDim.bottom - innerDiv.height())) {
innerDiv.css({
top: outDim.top + 'px',
});
}
}
if (x_allowed) {
innerDiv.css({
left: x + 'px'
});
} else {
//fine tune tweaks
if (x >= outDim.left) {
innerDiv.css({
left: outDim.right - innerDiv.width() + 'px',
});
}
if (x <= (outDim.right - innerDiv.width())) {
innerDiv.css({
left: outDim.left + 'px',
});
}
}
});
#wrap {
height: 200px;
width: 200px;
border: 2px solid black;
}
#outer {
height: 100px;
width: 100px;
border: 2px solid blue;
margin: 0 auto;
}
#inner {
height: 40px;
width: 40px;
border: 2px solid red;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<div id="outer">
<div id="inner">
</div>
</div>
</div>
Fiddle link

Need the image to be in the same position in both divs

I need the image in the both divs below to be in the same position even if the other div changes height or width. I have tried calculating top and left to % from px but still it is not working. I have also tried calculating the % of how big or small other div is and adding or removing the top and left to the image in other div and still no luck.
To check the issue, drag the image around inside the first div and click on submit. Now the image inside the bottom div should be in the same position as the above div, same top and left distance.
Please help. Thanks.
Here is the fiddle : https://jsfiddle.net/kashyap_s/gLdt62nh
var zoomLevel = 1;
$("#myimage").draggable({
start: function() {
},
stop: function() {
}
});
$('#save').click(function() {
var topcss = $('#myimage').css('top');
var leftcss = $('#myimage').css('left');
var transformcss = zoomLevel;
topcss = topcss.replace('px', '');
leftcss = leftcss.replace('px', '');
topcss = parseInt(topcss);
leftcss = parseInt(leftcss);
var parentWidth = $('#dragDiv').outerWidth()
var parentHeight = $('#dragDiv').outerHeight()
console.log('leftcss', leftcss, 'width', parentWidth)
console.log('topcss', topcss, 'height', parentHeight)
var percentLeft = leftcss / parentWidth * 100;
var percentTop = topcss / parentHeight * 100;
console.log('percentLeft', percentLeft, 'percentTop', percentTop)
transformcss = parseFloat(transformcss).toFixed(2);
var result = {
"top": topcss,
"left": leftcss,
'percentTop': percentTop,
'percentLeft': percentLeft,
'parentWidth': parentWidth,
'parentHeight': parentHeight,
"transform": "scale(" + transformcss + ")"
};
var output = JSON.stringify(result);
console.log('output', output)
$("#newimg").css({
'left': leftcss
});
$("#newimg").css({
'top': topcss
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="agent.png">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="agent.png" />
</div>
$(function() {
$("#logo1").draggable({
containment: "parent",
drag: function() {
}
});
});
function setpos() {
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w - image1_w;
var div2_aw = div2_w - image2_w;
var div1_ah = div1_h - image1_h;
var div2_ah = div2_h - image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw) / parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah) / parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos) / ratio_w;
var div2_nh = parseFloat(yPos) / ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({
'left': div2_nw,
'top': div2_nh
});
}
.div1 {
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2 {
width: 651px;
height: 431px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX">
</div>
<div id="posA">
</div>
<div id="posz">
</div>
<div id="posZ1">
</div>
Solved! check this out
HTML
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX"></div>
<div id="posA"></div>
JS CODE
$( function() {
$( "#logo1" ).draggable(
{
containment: "parent",
drag: function() {
}
}
);
} );
function setpos()
{
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w-image1_w;
var div2_aw = div2_w-image2_w;
var div1_ah = div1_h-image1_h;
var div2_ah = div2_h-image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw)/parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah)/parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos)/ratio_w;
var div2_nh = parseFloat(yPos)/ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({ 'left' : div2_nw, 'top' : div2_nh});
}
CSS
.div1{
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2{
width: 651px;
height: 431px;
border: 1px solid black;
}
For your newimg, the parent must have a position that is relative. This way, the absolute positioning will be relative to the parent and not the body.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
Consider the following code.
$(function() {
var zoomLevel = parseFloat(1 - ($("#dragDiv").outerWidth() / $("#bigimg").outerWidth()).toFixed(2));
function log(str) {
if ($(".log").length) {
$(".log").html(str);
} else {
$("<div>", {
class: "log"
}).html(str).appendTo("body");
}
}
function getPos(el) {
var par = $(el).parent();
var pos = {
top: parseInt($(el).css("top")),
left: parseInt($(el).css("left")),
zoom: "scale(" + (1 + zoomLevel) + ")",
parWidth: par.outerWidth(),
parHeight: par.outerHeight()
};
pos['perLeft'] = parseFloat((pos.left / pos.parWidth).toFixed(2)) * 100;
pos['perTop'] = parseFloat((pos.top / pos.parHeight).toFixed(2)) * 100;
return pos;
}
$("#myimage").draggable({
containment: "parent",
drag: function(e, ui) {
log("Left: " + ui.position.left + ", Top: " + ui.position.top);
},
start: function() {
// coordinates('#myimage');
},
stop: function() {
// coordinates('#myimage');
var p = getPos(this);
$(this).attr("title", JSON.stringify(p));
}
});
$('#save').click(function() {
var result = getPos($("#myimage"));
var output = JSON.stringify(result);
var nLeft = Math.round(result.perLeft * (1 + zoomLevel)) + "%";
var nTop = Math.round(result.perTop * (1 + zoomLevel)) + "%"
console.log(output, nLeft, nTop);
$("#newimg").css({
left: nLeft,
top: nTop
});
var p = getPos($("#newimg"));
$("#newimg").attr("title", JSON.stringify(p));
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
/* max-width: 100%; */
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
.log {
font-size: 11px;
font-family: "Arial";
position: absolute;
top: 3px;
left: 3px
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="https://i.imgur.com/4ILisqH.jpg">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="https://i.imgur.com/4ILisqH.jpg" />
</div>
See More: https://www.w3schools.com/css/css_positioning.asp
Updated
Looking at it further, I am guessing that you might be trying to reposition the bigimg in relationship to myimage position. This requires scaling the percentage.
For example, if we move myimage to the far left, it will be at left: 247, and this is roughly 49% of 499px. 49% of 653 is around 319, and this would not place the image where we want it. We want it at 401.
bigimg is about 24% larger than dragDiv, so we need to scale our percentage. 49 * 1.24 = 60.74, round up to 61. 653 * .61 = 398.33 so better yet not perfect.

JavaScript moving text animation doesn't work. FULL CODE

JS: My problem is in running the following JS script, it's supposed to be very easy ,i think, but i can't understand why won't it run. I've just started coding and i'm already stuck in this problem. I want the text to go up (by increasing the bottom in CSS) for 5px until it reaches pos=6 ; then clearInterval should do its job.
CSS: I've put the position of div's to RELATIVE as i've read in some tutorials but didn't put the " container's " position to ABSOLUTE, may it be the problem?
<html>
<head>
<style>
html {
height: 100%;
}
body {
height: ;
width: 100%;
background-color: ;
margin: 0px;
padding: 0px;
}
#generale {
height: 100%;
width: 100%;
}
#intestazione {
height: 7%;
width: 100%;
float: left;
background-image: url(immagini/sfumatura.png);
position: static;
}
#profilo {
position: static;
float: right;
width: 12%;
height: 100%;
}
.testo_rialzato {
position: relative;
float: right;
width: auto;
height: 100%;
padding-left: 20px;
padding-right: 20px;
background-color: transparent;
}
</style>
</head>
<body>
<div id="generale">
<div id="intestazione">
<div id="profilo"></div>
<div class="testo_rialzato sumba">
<p>Sp</p>
</div>
<div class="testo_rialzato ap">
<p>App</p>
</div>
<div class="testo_rialzato te">
<p>Te</p>
</div>
<div class="testo_rialzato do">
<p>Dom</p>
</div>
<div class="testo_rialzato big">
<p style="line-height:70%; margin-top:8px; text-align:center;">Big</p>
</div>
</div>
<script>
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
ez.onmouseover = alza();
var intervallo = setInterval(alza, 100);
function alza() {
var pos = 0;
if (pos = 6) {
clearInterval(intervallo);
} else {
ez.style.bottom = pos + "px";
}
}
</script>
</div>
</body>
</html>
First thing is , why declaring you are using event on an array of dome node (result of querySelectorAll will return array of domenodes ) so in order to attach mouseover and also apply some style you have to loop around those nodes .
Seconde thing while declaring set interval, its usless to use mousemovehere ?
Also the condition if is wrong you're using assignment , so you have to use == or === in order to make comaparison .
See below snippet :
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
var pos = 0;
var intervallo = setInterval(alza, 100);
ez.forEach(function(el){
el.addEventListener("mouseover", alza);
})
function alza() {
if (pos == 25) {
clearInterval(intervallo);
} else {
ez.forEach(function(el){
el.style.bottom = pos + "px";
});
pos++;
}
}
.sumba, .ap {
position:absolute;
}
.ap {
color:red;
left:40px
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="sumba">Text</div>
<div class="ap">Text 2</div>
try this
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
}
</style>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate">ggg</div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>

Developing image slider using jQuery and javascript

Below is my code in that i have developed three functions to get desired image by scrolling and i am having "prev" and "next" divs to move images.It looks good for me but there must be something wrong which is not letting it works.
<!DOCTYPE html>
<html>
<head><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" >
var imageArr = document.getElementsByClassName('slide');
var offset = imageArr.length-1;
var currentImage, prevImage, nextImage;
function getCurrentImage() {
currentImage = imageArr[offset];
}
function getPrevImage() {
if(offset == 0)
offset = imageArr.length-1;
else
offset = offset-1;
prevImage = imageArr[offset];
}
function getNextImage() {
if(offset == imageArr.length-1)
offset = 0;
else
offset = offset+1;
nextImage = imageArr[offset];
}
$("document").ready(function(){
$(".prev").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getPrevImage();
});
$(currentImage).css({right:0px});
$(prevImage).css({left:0px});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0'});
$(prevImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
$(".next").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getNextImage();
});
$(currentImage).css({right:0});
$(nextImage).css({left:0px});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0%'});
$(nextImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
});
</script>
<style>
.container {
width : 90%;
margin-left: 5%;
margin-right: 5%;
height : 400px;
border : 2px solid black;
position: relative;
}
img {
width:100%;
height:400px;
position: absolute;
}
.prev, .next {
position :relative;
cursor : pointer;
width : 4%;
height: 70px;
border : 1px solid black;
margin-top: -250px;
font-size: 40px;
color:#fff;
padding-left:10px;
background: #000;
opacity: .5;
}
.next {
float:right;
margin-right: 0px;
}
.prev{
float:left;
margin-left: 0px;
}
.prev:hover, .next:hover{
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
<img src="slide1.jpg" class="slide" />
<img src="slide2.jpg" class="slide" />
<img src="slide3.jpg" class="slide" />
<img src="slide4.jpg" class="slide" />
</div>
<div class="prev" >❮</div>
<div class="next" >❯</div>
</body>
</html>
You have syntax errors
in $().css({right: 0px}); should by $().css({right: '0px'});
Getting html elements also must be after $("document").ready, because your html elements do not exist before.
It works for me:
$("document").ready(function(){
var imageArr = document.getElementsByClassName('slide');
var offset = imageArr.length-1;
var currentImage, prevImage, nextImage;
function getCurrentImage() {
currentImage = imageArr[offset];
}
function getPrevImage() {
if(offset == 0)
offset = imageArr.length-1;
else
offset = offset-1;
prevImage = imageArr[offset];
}
function getNextImage() {
if(offset == imageArr.length-1)
offset = 0;
else
offset = offset+1;
nextImage = imageArr[offset];
}
$(".prev").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getPrevImage();
});
$(currentImage).css({right: '0px'});
$(prevImage).css({left: '0px'});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0'});
$(prevImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
$(".next").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getNextImage();
});
$(currentImage).css({right: '0px'});
$(nextImage).css({left: '0px'});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0%'});
$(nextImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
});

jQuery: Div elements are not showing up

I am adapting the Coverflow technique to work with a div. Following is the html:
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body,html {
margin: 0;
padding: 0;
background: #000;
height: 100%;
color: #eee;
font-family: Arial;
font-size: 10px;
}
div.magnifyme {
height: 80px;
padding: 80px;
position: absolute;
top: 0px;
left: 0px;
width: 2000px;
}
div.wrapper {
margin: 0px;
height: 470px;
/*border: 2px solid #999;*/
overflow: hidden;
padding-left: 40px;
right: 1px;
width: 824px;
position: relative;
}
div.container {position: relative; width: 854px; height: 480px; background: #000; margin: auto;}
div.nav {position: absolute; top: 10px; width: 20%; height: 10%; right: 1px; }
div.magnifyme div {
position: absolute;
width: 300px;
height: 280px;
float: left;
margin: 5px;
position: relative;
border: 2px solid #999;
background: #500;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="ui.coverflow.js"></script>
<script type="text/javascript" src="ui.core.js"></script>
<script type="text/javascript">
$(function() {
$("div.magnifyme").coverflow();
$("#add").click(function() {
$(".magnifyme").append("<div id=\"div5\">hello world</div>");
$("div.magnifyme").coverflow();
});
});
</script>
</head>
<body>
<div class="container">
<div class="wrapper">
<div class="magnifyme">
<div id="div0">This is div 0</div>
<div id="div1">This is div 1</div>
<div id="div2">This is div 2</div>
<div id="div3">This is div 3</div>
<div id="div4">This is div 4</div>
</div>
</div>
<div class="nav">
<button type="button" id="add">Add to Deck</button>
</div>
</div>
</body>
</html>
The coverflow function (included as a js file in the head section) is here. When I click the button, I was expecting it to add a DIV to the already present deck. For some reason, it doesn't show the newly added DIV. I tried calling the coverflow() function after I added the new element but that didn't work either. The modified coverflow function is given here:
;(function($){
$.widget("ui.coverflow", {
init: function() {
var self = this;
this.items = $(this.options.items, this.element).bind("click", function() {
self.moveTo(this);
//$("div.slider").slider("moveTo", self.current, null, true);
});
this.itemWidth = this.items.outerWidth(true);
this.current = 0; //Start item
this.refresh(1, 0, this.current);
this.element.css("left",
(-this.current * this.itemWidth/2)
+ (this.element.parent()[0].offsetWidth/2 - this.itemWidth/2) //Center the items container
- (parseInt(this.element.css("paddingLeft")) || 0) //Subtract the padding of the items container
);
},
moveTo: function(item) {
this.previous = this.current;
this.current = !isNaN(parseInt(item)) ? parseInt(item) : this.items.index(item);
if(this.previous == this.current) return false; //Don't animate when clicking on the same item
var self = this, to = Math.abs(self.previous-self.current) <=1 ? self.previous : self.current+(self.previous < self.current ? -1 : 1);
$.fx.step.coverflow = function(fx) {
self.refresh(fx.now, to, self.current);
};
this.element.stop().animate({
coverflow: 1,
left: (
(-this.current * this.itemWidth/2)
+ (this.element.parent()[0].offsetWidth/2 - this.itemWidth/2) //Center the items container
- (parseInt(this.element.css("paddingLeft")) || 0) //Subtract the padding of the items container
)
}, {
duration: 1000,
easing: "easeOutQuint"
});
/*current = this.current;
$("[id^=div]").each(function() {
if(this.id != "div"+current) {
console.info(this.id + " Current: " + current);
$(this).fadeTo( 'slow', 0.1);
}
});*/
},
refresh: function(state,from,to) {
var self = this, offset = null;
this.items.each(function(i) {
var side = (i == to && from-to < 0 ) || i-to > 0 ? "left" : "right";
var mod = i == to ? (1-state) : ( i == from ? state : 1 );
var before = (i > from && i != to);
$(this).css({
webkitTransform: "matrix(1,"+(mod * (side == "right" ? -0.5 : 0.5))+",0,1,0,0) scale("+(1+((1-mod)*0.5))+")",
left: (
(-i * (self.itemWidth/2))
+ (side == "right"? -self.itemWidth/2 : self.itemWidth/2) * mod //For the space in the middle
),
zIndex: self.items.length + (side == "left" ? to-i : i-to)
});
if(!$.browser.msie)
$(this).css("opacity", 1 - Math.abs((side == "left" ? to-i : i-to))/2);
});
}
});
$.extend($.ui.coverflow, {
defaults: {
items: "> *"
}
});
})(jQuery);
One thing I did notice is that after clicking the button for about 5-10 times, the elements show up but not along with the already present divs but rather below them. I am guessing that this has something to do with the CSS of the magnifyme class (2000px), but I am not sure what it is. Is there any way I can make this work?
You need to write an additional function for the coverflow widget:
add: function(el) {
var self = this;
this.element.append(el)
this.options.items = $('> *', this.element);
this.items = $(this.options.items, this.element).bind("click", function() {
self.moveTo(this);
});
this.itemWidth = this.items.outerWidth(true);
this.moveTo(this.items.length-1);
},
and then call it like so:
$("#add").click(function() {
$("div.magnifyme").coverflow('add', "<div></div>");
});
First, you need to add a references to the jQuery UI core, and it also appears that it requires the jQuery slider plugin.
Second, in your click event you're doing a location.reload, which is refreshing the page from the server, resetting any changes you had made to the page. (if you make the DIVs much smaller you can see one flash in before the page is reloaded).
You are getting a js error on the page -- "$.widget is not a function" because you didn't include the jqueryUI library. http://jqueryui.com/
Also if you remove the location.reload line, your code will work, however, I would rewrite that script block like this, so that everything clearly runs when the document is ready:
<script type="text/javascript">
$(document).ready(function() {
$("div.magnifyme").coverflow();
$("#add").click(function() {
$(".magnifyme").append("<div id=\"div5\">hello world</div>");
$("div.magnifyme").coverflow();
});
});
</script>

Categories