Aftershow in fancybox jQuery - javascript

I had the same problem this person: ShareThis plugin not working in FancyBox title But now I have gotten it work, except the
afterShow: function(){
stButtons.locateElements();
}
Where in this code should I put it? I've tried many places, but it just says error. It say's I am placing it wrong. Where should I place it in the script below?
<script type="text/javascript">
$(document).ready(function(){
$(".fancybox").fancybox({
beforeShow: function() {
var caption = $(this.element).data("caption") ? $(this.element).data("caption") : "";
this.title = this.title ? this.title + buildShareThis(this.href) + caption : buildShareThis(this.href) + caption;
if (this.title) { ''
// New line
this.title += '<br />';
}
},
nextEffect : 'fade',
prevEffect : 'fade',
padding : 0,
margin : [15, 15, 50, 15],
afterLoad : addLinks,
beforeClose : removeLinks
});
function buildShareThis(url){
var customShareThis = "<div class='share'>"; // class for styling maybe
customShareThis += "<span class='st_facebook_hcount' displayText='Facebook' st_url='"+url+"'></span> ";
customShareThis += "<span class='st_twitter_hcount' displayText='Tweet' st_url='"+url+"'></span>";
customShareThis += "<span class='st_pinterest_hcount' displayText='Pinterest' st_url='"+url+"' st_img='"+url+"' ></span>";
customShareThis += "<span class='st_tumblr_hcount' displayText='Tumblr' st_url='"+url+"'></span>";
customShareThis += "</div>";
return customShareThis;
}
function addLinks() {
var list = $("#links");
if (!list.length) {
list = $('<ul id="links">');
for (var i = 0; i < this.group.length; i++) {
$('<li data-index="' + i + '"><label></label></li>').click(function() { $.fancybox.jumpto( $(this).data('index'));}).appendTo( list );
}
list.appendTo( 'body' );
}
list.find('li').removeClass('active').eq( this.index ).addClass('active');
}
function removeLinks() {
$("#links").remove();
}
});
</script>

You can set all fancybox API options, including fancybox callbacks (afterLoad, afterShow, beforeClose, etc.) like :
$(".fancybox").fancybox({
nextEffect: 'fade',
prevEffect: 'fade',
padding: 0,
margin: [15, 15, 50, 15],
afterLoad: addLinks,
afterShow: function () {
stButtons.locateElements();
},
beforeClose: removeLinks
});
Assuming you have properly defined your addLinks and removeLinks functions somewhere else in your script.

Related

Dynamically generated lightslder and lightgallery

I have a news feed page where different posts show their images in a combination of lightslider and lightgallery. So far I have made it work for hardcoded posts, but failing to do the same for posts that are
dynamically generated.
Here is the code I'm using for combining lightgallery and lightslider
$('.lightSlider').each(function (index) {
$(this).lightSlider({
gallery: true,
item: 1,
loop: true,
slideMargin: 0,
thumbItem: 9,
onBeforeSlide: function (el) {
$('#counter' + index).text(el.getCurrentSlideCount());
},
onSliderLoad: function(el) {
el.lightGallery({
selector: '.lightgallery .lslide'
});
}
});
});
Here is the code I am playing with for combining lightslider and lightgallery in dynamically generated posts
HTML:
<button type="button" id="appendnewcontainer">Click me To create new slider</button>
<div id="fotoappendarea">
JavaScript:
$(document).ready(function(){
var imagesarray = [
"http://www.planwallpaper.com/static/images/Winter-Tiger-Wild-Cat-Images.jpg",
"http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg",
"http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg",
"http://i765.photobucket.com/albums/xx291/just-meller/national%20geografic/Birds-national-geographic-6873734-1600-1200.jpg",
"http://www.gettyimages.com/gi-resources/images/CreativeImages/Hero-527920799.jpg"
];
var hiddenimages = "",
albumcover;
$("#appendnewcontainer").click(function() {
$("<span />", {
class : "container",
appendTo : $("#fotoappendarea"),
append : $("<span />", {
class : "imagecontiner",
html : "<a class='dfed' href=" + imagesarray[1] + "><img src='" + imagesarray[1] + "' class='_34'/></a>"
}).lightGallery()
});
});
});
Solved! Here is how I did it
HTML:
<button type="button" class="btn btn-danger" id="appendnewcontainer">Click me To create new slider</button>
<div id="fotoappendarea">
JavaScript:
$(document).ready(function(){
getPost(0);
var imagesarray = [
"https://www.elastic.co/assets/bltada7771f270d08f6/enhanced-buzz-1492-1379411828-15.jpg",
"https://images.pexels.com/photos/236047/pexels-photo-236047.jpeg?auto=compress&cs=tinysrgb&h=350"
];
var hiddenimages = "",
albumcover;
$("#appendnewcontainer").click(function() {
$("#fotoappendarea").append("<div class='lightgallery my-5'><ul class= 'lightSlider'><li data-thumb=" + imagesarray[0] + " data-src=" + imagesarray[0] + "><img src='" + imagesarray[0] + "' class='_34'/></li><li data-thumb=" + imagesarray[1] + " data-src=" + imagesarray[1] + "><img src='" + imagesarray[1] + "' class='_34'/></li></ul></div>");
$('.lightSlider:last').lightSlider({
gallery: true,
item: 1,
loop: true,
slideMargin: 0,
thumbItem: 9,
onBeforeSlide: function (el) {
$('#counter' + index).text(el.getCurrentSlideCount());
},
onSliderLoad: function(el) {
el.lightGallery({
selector: '.lightgallery .lslide'
});
}
});
});
})
Will add the jsfiddle later

Make Javascript tooltip only display when I've specified the content

I'm using a small javascript to display a question mark icon with a explanatory tooltip next to product options on our ecommerce (bigcommerce) site. As it is, the script shows the icon for every product option, whether I've specified the content or not.
The content of the tooltip is set by using the following in the description section on the page:
<span id="[name of option]" style="display:none">[content of tooltip]</span>
If the content for the tooltip is not set, it displays "Description not available yet"
Here's an example of a page where the content is set:
http://www.www-savvyboater-com.mybigcommerce.com/carver-pontoon-bimini-top-sunbrella-a9sq4893ub
And here's an example of how it looks without the content set:
http://www.www-savvyboater-com.mybigcommerce.com/carver-bimini-top-double-duck-d5457ub
What I'd like is for the question mark icon to only show for the options where I've specified content for the tooltip. I don't know enough about javascript to figure it out on my own.
Here's the script in question:
$(document).ready(function() {
$(".productAttributeValue").each(function() {
var optionLabel = $(this).siblings('div');
var optionLabelText = optionLabel.children("label").children("span.name").text();
if ($("img", this).length < 1) {
$(this).siblings('div')
.children("label")
.children("span.name")
.append(" <div class='help_div' style='display: inline;'><img src='/product_images/uploaded_images/help.gif' alt='" + optionLabelText + "'/></div>");
}
});
$('.help_div').each(function() {
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (!html) html = "Description not available yet."
$(this).qtip({
content: titleq + html,
position: {
corner: {
tooltip: 'topRight',
target: 'bottomLeft'
}
},
style: {
tip: {
corner: 'rightTop',
color: '#6699CC',
size: {
x: 15,
y: 9
}
},
background: '#6699CC',
color: '#FFFFFF',
border: {
color: '#6699CC',
}
}
});
});
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/^\s+|\s+$/g, "");
text = text.replace(/\s/gi, "-");
text = text.toLowerCase();
return text;
}
});
The best way to do this is to not create the HTML for the ? in the first place.
$(document).ready(function() {
$(".productAttributeValue").each(function() {
var optionLabel = $(this).siblings('div');
var optionLabelText = optionLabel.children("label").children("span.name").text();
// check that optionLabelText is not an empty string
if ($("img", this).length < 1 && slugify(optionLabelText).trim().length) {
$(this).siblings('div')
.children("label")
.children("span.name")
.append(" <div class='help_div' style='display: inline;'><img src='/product_images/uploaded_images/help.gif' alt='" + optionLabelText + "'/></div>");
}
});
$('.help_div').each(function() {
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (!html) html = "Description not available yet."
$(this).qtip({
content: titleq + html,
position: {
corner: {
tooltip: 'topRight',
target: 'bottomLeft'
}
},
style: {
tip: {
corner: 'rightTop',
color: '#6699CC',
size: {
x: 15,
y: 9
}
},
background: '#6699CC',
color: '#FFFFFF',
border: {
color: '#6699CC',
}
}
});
});
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/^\s+|\s+$/g, "");
text = text.replace(/\s/gi, "-");
text = text.toLowerCase();
return text;
}
});
If that is not possible then there are two ways to handle this:
Hide the ? in CSS by default and then show them using javascript if data exists
.help_div {
display:none;
}
And in your javascript:
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (html) {
$(this).show();
}
Have the ? visible by default but destroy them if no data is found:
In your javascript:
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (!html) {
$(this).remove();
}
Option 1 has less chance of causing issues/being jarring but it's up to you how you would like to implement this.

multiple instances of my jQuery plugin on one page

I'm writing my first jQuery plugin using the jQuery UI template and I'm trying to instantiate two instances of the same plugin - but with different options.
I could do with some help please!
Javascript:
(function ($) {
// **********************************
// ***** Start: Private Members *****
var pluginName = 'onFancyLinks',
version = '1.0';
// ***** Fin: Private Members *****
// ********************************
// *********************************
// ***** Start: Public Methods *****
var methods = {
init: function (options) {
//"this" is a jquery object on which this plugin has been invoked.
return this.each(function (index) {
var $this = $(this);
var data = $this.data(pluginName);
// If the plugin hasn't been initialized yet
if (!data) {
var settings = {
lineColor: '#fff',
lineWidth: 1,
wrapperClass: 'fancy-link',
linesClass: 'line',
transDuration: '0.7s'
};
if (options) {
$.extend(true, settings, options);
}
$this.data(pluginName, {
target: $this,
settings: settings
});
}
});
},
wrap: function () {
return this.each(function () {
var $this = $(this),
data = $this.data(pluginName),
opts = data.settings,
//wrapping div
wrapper = '<div class="' + opts.wrapperClass + '"></div>',
lines = {
top: '<div class="' + opts.linesClass + ' line-top"> </div>',
right: '<div class="' + opts.linesClass + ' line-right"> </div>',
bottom: '<div class="' + opts.linesClass + ' line-bottom"> </div>',
left: '<div class="' + opts.linesClass + ' line-left"> </div>'
};
$this.wrap(wrapper);
$('.' + opts.wrapperClass).append(lines.top, lines.right, lines.bottom, lines.left);
//setup transition duration of lines animation
$('.' + opts.wrapperClass + ' .' + opts.linesClass).css({
'transition-duration': opts.transDuration,
backgroundColor: opts.lineColor,
borderWidth: opts.lineWidth
});
});
}
};
// ***** Fin: Public Methods *****
// *******************************
// *****************************
// ***** Start: Supervisor *****
$.fn[pluginName] = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist in jQuery.' + pluginName);
}
};
// ***** Fin: Supervisor *****
// ***************************
})(jQuery);
$(function() {
var v1 = $('#flink2').onFancyLinks({
lineColor: '#f00',
lineWidth: 2,
transDuration: '.4s'
});
var v2 = $('#flink').onFancyLinks({
lineColor: '#ff0',
lineWidth: 1,
transDuration: '.7s'
});
v1.onFancyLinks('wrap');
v2.onFancyLinks('wrap');
});
HTML:
<a id="flink2" href="http://www.google.co.uk">View Google</a>
<a id="flink" href="http://www.visarc.co.uk">View Visarc Site</a>
Here's my fiddle: http://jsfiddle.net/owennicol/xhuxk/14/
I'm sure it's something simple that I'm missing...
Very nice plugin, but there's a subtle logical error in it. Here's the critical part of the patched version:
var $wrapper = $this.wrap(wrapper).parent();
$wrapper.append(lines.top, lines.right, lines.bottom, lines.left);
//setup transition duration of lines animation
$wrapper.find('.' + opts.linesClass).css({
'transition-duration': opts.transDuration,
backgroundColor: opts.lineColor,
borderWidth: opts.lineWidth
});
See? You no longer look through the whole DOM for $('.' + opts.wrapperClass) and $('.' + opts.wrapperClass + ' .' + opts.linesClass) respectively - but instead scan only within the wrapper created for a specific jQuery element (processed by the plugin).
And that's exactly what was wrong in the original version: even though options were set up correctly (that's easy to check - just add console.log(options) into wrap method), the css was applied throughout the whole DOM for these line elements.

Jquery plugin using second instance's options

I have written a Jquery Pagination plugin that works great with just one instance of the plugin. When I try to use two instances, the first instance ignores its given options and uses the second instance's options. I know this because the two sections both start out with the defined items per page, but when you navigate to another 'page' in the pagination, it reverts to the second instance's itemsPerPage - 2.
My guess is the second time this plugin is called, it is overwriting $.pagination's options, so when either pagination goes to a new page, it uses the overwritten options.
Here's the plugin:
/* Jquery Pagination */
(function($){
$.pagination = {
defaultOptions : {
itemsPerPage : 5,
startPage : 1,
showNextPrev : true,
navigationPosition : 'before',
paginationClass : 'pagination',
paginationItemClass : 'paginationItem',
paginationItemActiveClass : 'active',
nextClass : 'next',
nextText : 'Next',
prevClass : 'prev',
prevText : 'Prev',
}
}
$.fn.extend({
pagination : function(newOptions){
var options = $.extend($.pagination.defaultOptions, newOptions),
itemsToPaginate = $(this),
itemsToPaginateContainer = itemsToPaginate.eq(0).parent(),
paginationWrapper = "<div class='" + options.paginationClass + "'></div>",
paginationControls = '',
pagination,
numberOfPages,
showPage = function(goToPage){
var page = (typeof goToPage === 'number') ? goToPage : goToPage.attr('href').replace('#page', ''),
itemRangeEnd = page * options.itemsPerPage
itemRangeStart = itemRangeEnd - options.itemsPerPage;
$( '.' + options.paginationItemClass, pagination).removeClass(options.paginationItemActiveClass);
if (typeof goToPage === 'number')
pagination.find('.' + options.paginationItemClass).eq(goToPage-1).addClass(options.paginationItemActiveClass);
else
goToPage.addClass(options.paginationItemActiveClass);
itemsToPaginate.hide().slice(itemRangeStart, itemRangeEnd).show();
},
createPagination = (function(){
// Add pagination element to DOM
switch(options.navigationPosition.toLowerCase()){
/*
// TODO: Create ability to insert pagination after or before & after
case 'both':
itemsToPaginateContainer.before(paginationWrapper);
itemsToPaginateContainer.after(paginationWrapper);
break;
case 'after':
itemsToPaginateContainer.after(paginationWrapper);
break;
*/
default:
itemsToPaginateContainer.before(paginationWrapper);
break;
}
// Selecting pagination element
pagination = itemsToPaginateContainer.siblings('.' + options.paginationClass);
// Count how many pages to make
numberOfPages = Math.ceil( itemsToPaginate.length / options.itemsPerPage );
// Insert controls into pagination element
if(options.showNextPrev) paginationControls += "<a href='#' class='" + options.prevClass + "'>" + options.prevText + "</a>";
for (var i = 1; i <= numberOfPages; i++) {
paginationControls += "<a href='#page" + i + "' class='" + options.paginationItemClass + "'>" + i + "</a>";
}
if(options.showNextPrev) paginationControls += "<a href='#' class='" + options.nextClass + "'>" + options.nextText + "</a>";
(numberOfPages !== 1) ? pagination.html(paginationControls) : pagination.remove() ;
}()),
bindUIEvents = (function(){
pagination.find('.' + options.paginationItemClass + ':not(.' + options.nextClass + '):not(.' + options.prevClass + ')').on('click', function(e){
e.preventDefault();
showPage( $(this) );
});
pagination.find('.' + options.prevClass).on('click', function(){
var prevPageIdx = pagination.find('.' + options.paginationItemActiveClass).index() - 1;
// console.log(prevPageIdx);
if(prevPageIdx < 1)
showPage(numberOfPages);
else
showPage(prevPageIdx);
});
pagination.find('.' + options.nextClass).on('click', function(){
var nextPageIdx = pagination.find('.' + options.paginationItemActiveClass).index() + 1;
if(nextPageIdx > numberOfPages)
showPage(1);
else
showPage(nextPageIdx);
});
}());
showPage(options.startPage);
return this;
}
});
})(jQuery);
JSFiddle
Any idea why each instance of this plugin doesn't just use its own options? How would I need to structure a plugin to encapsulate and protect their own options? Thanks!
Change
var options = $.extend($.pagination.defaultOptions, newOptions),
To
var options = $.extend({}, $.pagination.defaultOptions, newOptions),
Demo
Reason is you are providing the target as defaultOption while using the syntax jQuery.extend( target [, object1 ] [, objectN ]

anchor is not working after callback append in jquery

t I have been trying to resolve this issue for two days, and I'm getting crazy, plea a little help.
I'm trying to append a new div (insert html code), within an anchor, it seems ok, but the link does not work. I'm trying to use a class='delete', to call another jquery function to deleted the new div element. The idea is a shopping cart, I add a producto, and after added, I want to delete, but it's not working. Here is my code:
$("#dialog-form").dialog({
autoOpen: false,
height: 320,
width: 320,
modal: true,
show: 'slide',
buttons: {
"Agregar Tour": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(adl, "Adultos", 1, 5);
bValid = bValid && checkLength(chls, "NiƱos", 0, 5);
bValid = bValid && checkLength(fecha, "Fecha", 1, 16);
var id = $(this).val("id");
var string = 'tourid=' + tourid;
//var tourid = '<?php echo $moneda ?>';
//alert(tourid);
if (bValid) {
$.ajax({
url: "add_item.php",
data: "tourid=" + tourid + "&adl=" + adl.val() + "&chl=" + chls.val() + "&fecha=" + fecha + "",
dataType: 'json',
type: "GET",
cache: false,
success: function (data) {
var regis = data[0];
var titulo = data[6];
var desc = data[7];
var total = data[12];
var foto = data[15];
var items = data[21];
var ruta = "images/hoteles/" + foto + "";
$("#containerx").append("<div id='containerx' class='koko' ><b><font color='#3399CC'>" + titulo + "</font></b><br>" + desc + "<br>" + "<b><font color='#ff0099'>Sub-total </font></b><image src='images/arrow.gif'> $" + total + " MXP " + "<a href='#' id=" + regis + " class='delele'>" + "<image src='images/delete.gif'></a></div><div style='clear:both;'></div>");
$("#containerx.koko").fadeTo(1000, 0.7);
$("#dialog-message").dialog({
modal: true,
show: 'slide',
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
$("#items").html("<div id='items'>[" + items + "]</div>");
$('#load').fadeOut();
}
});
$(this).dialog("close");
}
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
allFields.val("").removeClass("ui-state-error");
}
});
$(".add-item").button().click(function () {
tourid = $(this).attr("id");
$("#dialog-form").dialog("open");
});
On this "delete" event etc you need to use "live" jquery live http://api.jquery.com/live/ or attach the events again after you add content.
Simply once content is rendered all events are attached, if you are dynamically adding new content you need to attach events again if they are not "live" events.
jquery "Live" event will try to attach to dynamically added content also :). Read the doc i added and you will know all.

Categories