How can I set this slide panel jQuery plugin to default close? - javascript

I've implemented the panel toggle script by DojoGeekRA which is published at JqueryScript.net (demo https://www.jqueryscript.net/demo/Creating-A-Toggable-Bottom-Content-Panel-Using-jQuery-CSS/)
It functions as needed as far as the toggle open / close behavior, however it defaults to open state when the page is loaded and I need it to default to close.
The JS
(function($) {
jQuery(document).ready(function() {
Panel.init();
$(document).on('click', '.tab-controller', function() {
Panel.togglePanel();
});
});
var Panel = {
isVisible : true,
showMessage : null,
hideMessage : null,
animationDuration : 650,
animationEasing : 'linear',
init : function() {},
hidePanel : function() {
$('.panel-wrapper').animate({
bottom : -(Panel.getAnimationOffset())
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = false;
Panel.updateTabMessage();
});
},
showPanel : function() {
$('.panel-wrapper').animate({
bottom : 0
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = true;
Panel.updateTabMessage();
});
},
togglePanel : function() {
((this.isVisible) ? this.hidePanel : this.showPanel)();
},
updateTabMessage : function() {
if (this.isVisible) {
$('.tab-controller .close').show();
$('.tab-controller .show').hide();
} else {
$('.tab-controller .close').hide();
$('.tab-controller .show').show();
}
},
getAnimationOffset : function() {
return $('.panel-content').height();
}
}
})(jQuery);
I tried
setting isVisible to false but nothing changes (yes I refreshed the page)
set the .panel-content css rule to display:none and though it responds to default hidden, the JS is still in open mode so the tab states Close and goes off screen when clicked.
The HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>The Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="plugin.css?v=9">
<script src="jquery-1.11.0.min.js"></script>
<script src="main.js?v=8"></script>
</head>
<body style="background: #ddd;">
<div class="panel-wrapper">
<div class="panel-controller">
<div class="tab-controller">
<span class="close">Close</span>
<span class="show">Open</span>
</div>
</div>
<div class="panel-content">
<div class="content clearfix">
the content here
</div>
</div>
</div>
</body>
</html>
The CSS
.panel-wrapper * {
box-sizing: border-box;
}
.panel-wrapper {
position: fixed;
right: 0;
bottom: 0;
overflow: hidden;
z-index: 99999;
font-family: sans-serif;
}
.panel-controller {
position: relative;
overflow: hidden;
}
.tab-controller {
float: right;
margin-right: 50px;
padding: 5px;
background-color: #ff0000;
border-radius: 5px 5px 0 0;
display: block;
font-size: 16px;
font-weight: bold;
color: white;
cursor: pointer;
}
.tab-controller .show {
display: none;
}
.panel-content {
overflow: hidden;
}
.panel-content .content {
overflow: hidden;
margin: 0 5px 5px 0;
}
.clearfix:before, .clearfix:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.clearfix:after {
clear: both;
}
Update
The answer from #The_Death_Raw did the task (thanks), however I needed to be able to set options dynamically and use multiple instances, so I added a function closure and setting variable. Here is the modified working script if desired.
(function($) {
$.fn.bottomSlidePanel = function(options)
{
var wrap = this;
return this.each(function()
{
var setting = $.extend ({
tab: ".tab-controller",
contentarea: ".panel-content",
defaultState: "close",
animTime: 250
}, options);
$(function() {
if( setting.defaultState === "close" ) {
Panel.init(Panel.hidePanel(Panel.animationDuration = 0));
setTimeout(function() {
Panel.hidePanel(Panel.animationDuration = setting.animTime);
}, 1);
}else{
Panel.init();
}
$(setting.tab).on("click", function() {
Panel.togglePanel();
});
});
var Panel = {
isVisible : true,
showMessage : null,
hideMessage : null,
animationDuration : setting.animTime,
animationEasing : "linear",
init : function() {},
hidePanel : function() {
$(wrap).animate({
bottom : -(Panel.getAnimationOffset())
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = false;
Panel.updateTabMessage();
});
},
showPanel : function() {
$(wrap).animate({
bottom : 0
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = true;
Panel.updateTabMessage();
});
},
togglePanel : function() {
((this.isVisible) ? this.hidePanel : this.showPanel)();
},
updateTabMessage : function() {
if (this.isVisible) {
$(setting.tab+' .tabclose').show();
$(setting.tab+' .tabshow').hide();
} else {
$(setting.tab+' .tabclose').hide();
$(setting.tab+' .tabshow').show();
}
},
getAnimationOffset : function() {
return $(setting.contentarea).height();
}
}
});
}
}(jQuery));
Use
Basic using core defaults
jQuery(function($) {
// attach to the parent wrap element
$(".panel-wrapper").bottomSlidePanel();
});
Use options
jQuery(function($) {
// attach to the parent wrap element
$(".panel-wrapper").bottomSlidePanel({
tab: ".tab-controller", // set tab class or ID
contentarea: ".panel-content", // set element class or ID
defaultState: "open", // omit to allow default close
animTime: 500 // (int) omit to use default value
});
});
If anyone has the ability to make it more efficient, please post it.

Hide the panel and then set AnimationDuration to 0 to hide on page load.
Wait for 1s and then set animation to 650 to make it work
(function($) {
jQuery(document).ready(function() {
Panel.init(Panel.hidePanel(Panel.animationDuration = 0));
setTimeout(function(){ Panel.hidePanel(Panel.animationDuration = 650); }, 1);
$(document).on('click', '.tab-controller', function() {
Panel.togglePanel();
});
});
var Panel = {
isVisible : true,
showMessage : null,
hideMessage : null,
animationDuration : 650,
animationEasing : 'linear',
init : function() {
},
hidePanel : function() {
$('.panel-wrapper').animate({
bottom : -(Panel.getAnimationOffset())
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = false;
Panel.updateTabMessage();
});
},
showPanel : function() {
$('.panel-wrapper').animate({
bottom : 0
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = true;
Panel.updateTabMessage();
});
},
togglePanel : function() {
((this.isVisible) ? this.hidePanel : this.showPanel)();
},
updateTabMessage : function() {
if (this.isVisible) {
$('.tab-controller .close').show();
$('.tab-controller .show').hide();
} else {
$('.tab-controller .close').hide();
$('.tab-controller .show').show();
}
},
getAnimationOffset : function() {
return $('.panel-content').height();
}
}
})(jQuery);
.panel-wrapper * {
box-sizing: border-box;
}
.panel-wrapper {
position: fixed;
right: 0;
bottom: 0;
overflow: hidden;
z-index: 99999;
font-family: sans-serif;
}
.panel-controller {
position: relative;
overflow: hidden;
}
.tab-controller {
float: right;
margin-right: 50px;
padding: 5px;
background-color: #ff0000;
border-radius: 5px 5px 0 0;
display: block;
font-size: 16px;
font-weight: bold;
color: white;
cursor: pointer;
}
.tab-controller .show {
display: none;
}
.panel-content {
overflow: hidden;
}
.panel-content .content {
overflow: hidden;
margin: 0 5px 5px 0;
}
.clearfix:before, .clearfix:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.clearfix:after {
clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body style="background: #ddd;">
<div class="panel-wrapper">
<div class="panel-controller">
<div class="tab-controller">
<span class="close">Close</span>
<span class="show">Open</span>
</div>
</div>
<div class="panel-content">
<div class="content clearfix">
the content here
</div>
</div>
</div>

Related

don't show pop-up again if it closed using javascript

How can I stop showing pop-up after clicking on close button?
This is my pop-up function, it opens after scrolling to 1300px of page.
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 1300) {
$('.popup').fadeIn();
}
});
but when I closed it , it opend again
this is my button fun
function closePopup(){
document.getElementById('popup').style.display = 'none';
}
++ this is my button
<button type="button" class="close" id="close-popup" onclick="closePopup()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
You can add a boolean control when it's clicked
let popupClosed = false;
function closePopup() {
document.getElementById('popup').style.display = 'none';
popupClosed = true;
}
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 1300 && !popupClosed) {
$('.popup').fadeIn();
}
});
You need a way to control when the popup was opened for the first time (or closed).
$(document).scroll(function() {
let y = $(this).scrollTop(),
popup = $('.popup')
if (y > 1300 && ! popup.data('opened')) {
popup.data('opened', true)
popup.fadeIn();
}
});
I replaced your scroll height detection with a button. Just call $('.popup').popupShow() whenever you scroll past 1,300 pixels.
Make sure you call $('.popup').popup(options) with the appropriate close/open callbacks.
Once you close the popup for the first time, a data attribute of doNotOpen will be set to true. Subsequent open attempts will not be allowed, because the open callback checks for the presence of that doNotOpen data value.
function main() {
$('.popup').popup({
title: 'Popup Test',
open: function() {
return !this.data('doNotOpen'); // type boolean
},
close: function() {
this.data('doNotOpen', true);
}
});
$('.show-btn').on('click', function() {
$('.popup').popupShow();
});
}
/**
* #name flex-popup.jquery.js
* #date 2021-03-03
* #author Mr. Polywhirl
*
* Callback when opening a popup.
* #callback openCallback
* #return {boolean} whether to show the popup
*
* Callback when closing a popup.
* #callback closeCallback
*/
(function($) {
var defaultOptions = {
title: null,
content: null
};
var setAndDelete = function($el, prop, props) {
if (props[prop]) {
$el.html(props[prop]);
delete props[prop];
}
};
/**
* #param {string} title
* #param {string} content
* #param {options.openCallback} open
* #param {options.closeCallback} close
*/
$.fn.popup = function(options) {
var opts = $.extend(true, {}, defaultOptions, options);
if (this.is(':empty')) this.popupCreate();
this.find('.popup-close').on('click', function() {
$(this).closest('.popup').popupHide();
});
setAndDelete(this.find('.popup-header-title'), 'title', opts);
setAndDelete(this.find('.popup-content'), 'content', opts);
return this.data(opts).css('display', 'flex').hide();
};
$.fn.popupCreate = function() {
return this
.append($('<div>').addClass('popup-header')
.append($('<div>').addClass('popup-header-title'))
.append($('<div>').addClass('popup-close')))
.append($('<div>').addClass('popup-content'));
};
$.fn.popupShow = function() {
if (this.is(':hidden') && (!this.data('open') || this.data('open').call(this))) {
if (this.data('open')) this.data('open').call(this);
return this.fadeIn();
} else {
if (this.is(':hidden')) {
console.log('Not allowed!');
}
}
};
$.fn.popupHide = function() {
if (!this.is(':hidden')) {
if (this.data('close')) this.data('close').call(this);
return this.fadeOut();
}
};
})(jQuery);
main();
:root {
--popup-background: #AAA;
--popup-header-background: #777;
--popup-content-background: #AAA;
--popup-border-color: #555;
--popup-close-color: #BBB;
--popup-close-hover-color: #DDD;
}
body {
background: #222;
}
.popup {
display: flex;
flex-direction: column;
position: absolute;
top: 25vh;
left: 25vw;
width: 50vw;
height: 50vh;
z-index: 1000;
background: var(--popup-background);
border: thin solid var(--popup-border-color);
}
.popup>.popup-header {
display: flex;
flex-direction: row;
align-items: center;
background: var(--popup-header-background);
padding: 0.25em 0.5em;
}
.popup .popup-header-title {
flex: 1;
text-align: center;
font-weight: bold;
}
.popup .popup-close {
font-size: 2em;
line-height: 1em;
font-weight: bold;
color: var(--popup-close-color);
}
.popup .popup-close:hover {
color: var(--popup-close-hover-color);
cursor: pointer;
}
.popup .popup-close::after {
content: '\00D7';
}
.popup>.popup-content {
background: var(--popup-content-background);
flex: 1;
padding: 0.25em 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="popup">
<div class="popup-header">
<div class="popup-header-title">Replace this</div>
<div class="popup-close"></div>
</div>
<div class="popup-content">
<h1>Content heading</h1>
<p>Content description here.</p>
</div>
</div>
<button class="show-btn">Show Popup</button>
Note: Here is a mirror on JSFiddle.

How do I change the placeholder like as the elements replace each other place?

How do I change the placeholder like as the elements replace each other place.
Please see the example
https://jsfiddle.net/98h31o9v/11/
JavaScript
indexOfCell = 0;
add boxes to #div element
$('#add_box').on('click', function() {
var cell = $("<div></div>");
var elementObj = cell.get(0);
$('#div').append(elementObj);
cell.addClass('content-box').attr('id', 'box_' + indexOfCell);
cell.text(indexOfCell);
indexOfCell += 1;
console.log(elementObj);
$(cell).draggable({
helper: 'original',
zIndex: 10001,
start: function(event, ui) {
if ($(this).data('placeholder') === undefined) {
$(this).data('placeholder', createPlaceholder($(this)));
}
setPlaceHolder($(this).data('placeholder'), $(this));
$(this).after($(this).data('placeholder'));
},
stop: function(event, ui) {
$(this).css('left', $(this).data('placeholder').css('left'));
$(this).css('top', $(this).data('placeholder').css('top'));
$(this).data('placeholder').after($(this));
$(this).data('placeholder').detach();
}
});
$(cell).droppable({
tolerance: 'intersect',
greedy: true,
over: function(event, ui) {
replaceTwoItem(ui.draggable.data('placeholder'), $(this));
}
});
create placeholder
function createPlaceholder(that) {
var className = that.attr('class');
var placeholder = $(document.createElement(that.get(0).nodeName))
.addClass(className || className + " ui-sortable-placeholder")
.removeClass("ui-sortable-helper").css({
background: 'yellow',
border: '1px solid grey'
});
return placeholder;
}
set the placeholder to cell
function setPlaceHolder(placeholder, cell) {
placeholder.css('width', cell.width());
placeholder.css('height', cell.height());
placeholder.css("display", 'block');
placeholder.css('position', 'absolute');
placeholder.css('top', cell.css('top'));
placeholder.css('left', cell.css('left'));
}
replace two item when drag
function replaceTwoItem(itemFrom, itemTo) {
var itemToInsert;
var action;
if (itemFrom.index() === 0) {
itemToInsert = itemFrom.parent();
action = "prepend";
} else {
itemToInsert = itemFrom.prev();
action = "after";
}
itemTo.before(itemFrom);
if (itemTo.get(0) != itemToInsert.get(0)) {
if (action == 'prepend') {
itemToInsert.prepend(itemTo);
} else if (action == 'after') {
itemToInsert.after(itemTo);
}
}
}
});
HTML
<button id="add_box">AddBox</button>
<div id="div">
</div>
CSS
.content-box {
width: 100px;
height: 100px;
background: green;
margin: 5px;
float: left;
}
After the brief discussion in the comments about your requirements I think you can get rid of most of the code you're currently using. The example on the jquery
ui website can be tweaked slightly to get what you want.
Fiddle Example
HTML:
<button id="add_box">AddBox</button>
<div id="sortable" class="ui-sortable">
</div>
JQuery:
$('#add_box').on('click', function() {
//Determine the existing child count.
var boxCount = $('#sortable').children().length;
//Create a new "box" and add it to the end of the list.
var newBox = $('<div class="ui-state-default">' + boxCount + '</div>');
$('#sortable').append(newBox);
//Invoke the sortable function to ensure the appropriate events are bound.
$("#sortable").sortable({
placeholder: "ui-state-highlight"
});
});
CSS:
The below can be cleaned up somewhat.
#sortable {
margin: 0;
padding: 0;
}
.ui-state-highlight {
background: yellow;
margin: 0 5px 5px 5px;
color: black;
float: left;
width: 100px;
height: 100px;
}
.ui-state-default {
background: green;
margin: 0 5px 5px 5px;
color: black;
float: left;
width: 100px;
height: 100px;
}
Update .ui-state-default to change the initial colour and update .ui-state-highlight to change the placeholder colour.

Generate Excel file thumbnail preview in Javascript

I have a project handling a library of excel files. To make it easilier for the users to visually scan them, I would like to generate preview thumbnail images of their content. Google drive does this (screenshot below) but I have no idea how.
Any ideas/suggestions on how this could be done (without using the drive API) ?
I guess this is what you need
http://github.com/lonekorean/mini-preview
DEMO
/*
* MiniPreview v0.9
*
* #author Will Boyd
* #github http://github.com/lonekorean/mini-preview
*/
(function($) {
var PREFIX = 'mini-preview';
// implemented as a jQuery plugin
$.fn.miniPreview = function(options) {
return this.each(function() {
var $this = $(this);
var miniPreview = $this.data(PREFIX);
if (miniPreview) {
miniPreview.destroy();
}
miniPreview = new MiniPreview($this, options);
miniPreview.generate();
$this.data(PREFIX, miniPreview);
});
};
var MiniPreview = function($el, options) {
this.$el = $el;
this.$el.addClass(PREFIX + '-anchor');
this.options = $.extend({}, this.defaultOptions, options);
this.counter = MiniPreview.prototype.sharedCounter++;
};
MiniPreview.prototype = {
sharedCounter: 0,
defaultOptions: {
width: 256,
height: 144,
scale: .25,
prefetch: 'pageload'
},
generate: function() {
this.createElements();
this.setPrefetch();
},
createElements: function() {
var $wrapper = $('<div>', { class: PREFIX + '-wrapper' });
var $loading = $('<div>', { class: PREFIX + '-loading' });
var $frame = $('<iframe>', { class: PREFIX + '-frame' });
var $cover = $('<div>', { class: PREFIX + '-cover' });
$wrapper.appendTo(this.$el).append($loading, $frame, $cover);
// sizing
$wrapper.css({
width: this.options.width + 'px',
height: this.options.height + 'px'
});
// scaling
var inversePercent = 100 / this.options.scale;
$frame.css({
width: inversePercent + '%',
height: inversePercent + '%',
transform: 'scale(' + this.options.scale + ')'
});
// positioning
var fontSize = parseInt(this.$el.css('font-size').replace('px', ''), 10)
var top = (this.$el.height() + fontSize) / 2;
var left = (this.$el.width() - $wrapper.outerWidth()) / 2;
$wrapper.css({
top: top + 'px',
left: left + 'px'
});
},
setPrefetch: function() {
switch (this.options.prefetch) {
case 'pageload':
this.loadPreview();
break;
case 'parenthover':
this.$el.parent().one(this.getNamespacedEvent('mouseenter'),
this.loadPreview.bind(this));
break;
case 'none':
this.$el.one(this.getNamespacedEvent('mouseenter'),
this.loadPreview.bind(this));
break;
default:
throw 'Prefetch setting not recognized: ' + this.options.prefetch;
break;
}
},
loadPreview: function() {
this.$el.find('.' + PREFIX + '-frame')
.attr('src', this.$el.attr('href'))
.on('load', function() {
// some sites don't set their background color
$(this).css('background-color', '#fff');
});
},
getNamespacedEvent: function(event) {
return event + '.' + PREFIX + '_' + this.counter;
},
destroy: function() {
this.$el.removeClass(PREFIX + '-anchor');
this.$el.parent().off(this.getNamespacedEvent('mouseenter'));
this.$el.off(this.getNamespacedEvent('mouseenter'));
this.$el.find('.' + PREFIX + '-wrapper').remove();
}
};
})(jQuery);
.mini-preview-anchor {
display: inline-block;
position: relative;
white-space: nowrap;
}
.mini-preview-wrapper {
-moz-box-sizing: content-box;
box-sizing: content-box;
position: absolute;
overflow: hidden;
z-index: -1;
opacity: 0;
margin-top: -4px;
border: solid 1px #000;
box-shadow: 4px 4px 6px rgba(0, 0, 0, .3);
transition: z-index steps(1) .3s, opacity .3s, margin-top .3s;
}
.mini-preview-anchor:hover .mini-preview-wrapper {
z-index: 2;
opacity: 1;
margin-top: 6px;
transition: opacity .3s, margin-top .3s;
}
.mini-preview-loading, .mini-preview-cover {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
.mini-preview-loading {
display: table;
height: 100%;
width: 100%;
font-size: 1.25rem;
text-align: center;
color: #f5ead4;
background-color: #59513f;
}
.mini-preview-loading::before {
content: 'Loading...';
display: table-cell;
text-align: center;
vertical-align: middle;
}
.mini-preview-cover {
background-color: rgba(0, 0, 0, 0); /* IE fix */
}
.mini-preview-frame {
border: none;
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MiniPreview Demo</title>
<link href="http://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<style>
body {
height: 100%;
margin: 0;
padding: 0 10% 40px;
font-size: 2rem;
line-height: 1.5;
font-family: 'Roboto Slab', sans-serif;
text-align: justify;
color: #59513f;
background-color: #f5ead4;
}
a {
color: #537f7c;
}
.break {
text-align: center;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- MiniPreview stuff here -->
<link href="./jquery.minipreview.css" rel="stylesheet">
<script src="./jquery.minipreview.js"></script>
<script>
$(function() {
$('#p1 a').miniPreview({ prefetch: 'pageload' });
$('#p2 a').miniPreview({ prefetch: 'parenthover' });
$('#p3 a').miniPreview({ prefetch: 'none' });
});
</script>
</head>
<body>
<p id="p1">
This demo shows how to add live mini-previews to links on hover. Check out these links to SitePoint and A List Apart. Hover over them to see a small preview of what they point to.
</p>
<p class="break">• • •</p>
<p id="p2">
Those previews were fetched as soon as this page loaded. This is great for having the previews ready ahead of time, but can eat up extra bandwidth. As an alternative, check out these links to Abduzeedo and Smashing Magazine. These previews aren't fetched until you hover over this paragraph.
</p>
<p class="break">• • •</p>
<p id="p3">
Finally, check out these links to Daniel's blog, Joni's blog, and my blog. These previews are only fetched when needed. This saves the most bandwidth, but there will be a delay before the previews can be shown.
</p>
</body>
</html>
ORIGINAL SOURCE:
http://codepen.io/kanakiyajay/pen/NqgZjo
I just use a library to generate a PNG preview of the excel file and show it.
I use Free Spire.XLS for .NET because I'm in the .net world, but you can look at Wijmo Workbook Viewer for your Node.js needs.

jQuery Custom Lightbox issue

I have been writing my own Lightbox script (to learn more about jQuery).
My code for the captions are as follows (the problem is that the captions are the same on every image):
close.click(function(c) {
c.preventDefault();
if (hideScrollbars == "1") {
$('body').css({'overflow' : 'auto'});
}
overlay.add(container).fadeOut('normal');
$('#caption').animate({
opacity: 0.0
}, "5000", function() {
$('div').remove('#caption');
});
});
$(prev.add(next)).click(function(c) {
c.preventDefault();
$('div').remove('#caption')
areThereAlts = "";
var current = parseInt(links.filter('.selected').attr('lb-position'),10);
var to = $(this).is('.prev') ? links.eq(current - 1) : links.eq(current + 1);
if(!to.size()) {
to = $(this).is('.prev') ? links.eq(links.size() - 1) : links.eq(0);
}
if(to.size()) {
to.click();
}
});
So, I found out what was wrong (Cheers Deng!), further down the code I had the following function (I had to add "link" into the remove caption code):
links.each(function(index) {
var link = $(this);
link.click(function(c) {
c.preventDefault();
if (hideScrollbars == "1") {
$('body').css({'overflow' : 'hidden'});
}
open(link.attr('href'));
links.filter('.selected').removeClass('selected');
link.addClass('selected');
var areThereAlts = $(".thumb", link).attr("alt"); //"link" needed to be added here
//alert(areThereAlts);
if (areThereAlts !== "") {
container.append('<div id="caption" style="display: block; font-family: Verdana; background-color: white; padding: 4px 5px 10px 5px; top -10px; width: 100%; height: 25px; vertical-align: middle; -moz-border-radius-topleft: 10px; -moz-border-radius-topright: 10px; color: #3f3f3f;"><font color="#3f3f3f">'+areThereAlts+'</font></div>') //caption
}
});
link.attr({'lb-position': index});
});

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