prettyPhoto change title on hover over thumbnail - javascript

I use prettyPhoto version: 3.1.6 to display simple lightbox with thumbnail.
Normally title attribute appear inside the lightbox for the active/selected image.
My client ask for this change
http://i.stack.imgur.com/7932x.jpg
How I can accomplish this?
Here is a part of my code
<a rel="prettyPhoto[pp_gal]"href="1.jpg" title="Staring at the sun"><img src="2.jpg"></a>

try this jquery function. You may have to style it a little.
(function($)
{
$.fn.avia_activate_lightbox = function(variables)
{
var defaults =
{
autolinkElements: 'a[rel^="prettyPhoto"], a[rel^="lightbox"], a[href$=jpg], a[href$=png], a[href$=gif], a[href$=jpeg], a[href$=".mov"] , a[href$=".swf"], a[href$=".flv"] , a[href*="vimeo.com"] , a[href*="youtube.com"]'
};
var options = $.extend(defaults, variables);
var imagedefaults =
{
autolinkImages: 'img[title!=""]'
};
return this.each(function()
{
var elements = $(options.autolinkElements, this),
lastParent = "",
counter = 0;
var images = $(imagedefaults.autolinkImages, this),
imgcounter = 0;
var alltitlesalt = new Array();
var alltitles = new Array();
images.each(function()
{
if($(this).attr('alt') != undefined && $(this).attr('alt') !="")
{
alltitlesalt.push($(this).attr('alt'));
}
else
{
alltitlesalt.push("");
};
alltitles.push($(this).attr('title'));
});
elements.each(function()
{
var el = $(this),
parentPost = el.parents('.post-entry:eq(0)'),
group = 'auto_group';
if(parentPost.get(0) != lastParent)
{
lastParent = parentPost.get(0);
counter ++;
}
if((el.attr('rel') == undefined || el.attr('rel') == '') && !el.hasClass('noLightbox'))
{
el.attr('rel','lightbox');
el.attr('title',alltitles[imgcounter]);
el.attr('alt',alltitlesalt[imgcounter]);
imgcounter ++;
}
});
if($.fn.prettyPhoto)
elements.prettyPhoto({ "theme": 'premium_photo', 'slideshow': 5000 }); /* facebook /light_rounded / dark_rounded / light_square / dark_square */
});
};
})(jQuery);
Reference

Related

ISOTOPE - 2 grids on one page

I am trying to implement 2 different isotope grids filter + pagination on one page and have issues setting up the second one.
As you can see on my pen, the first one is working and not the second one. I used the same id and class for both grid and think the issue is there but I couldn't manage to update my javascript to make it work!
Could someone help me with that?
Thanks
https://codepen.io/tcosteur/pen/oNWoNWP
here is my js:
function cbChange(obj) {
var cbs = document.getElementsByClassName("filter-item");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
$(document).ready(function() {
// filter items on button click
$('.filter-button-group').on('click', 'li', function() {
var filterValue = $(this).attr('data-filter');
$('.grid').isotope({
filter: filterValue
});
$('.filter-button-group li').removeClass('active');
$(this).addClass('active');
});
})
var itemSelector = ".item";
var $checkboxes = $('.filter-item');
var $container = $('#products').isotope({
itemSelector: itemSelector
});
//Ascending order
var responsiveIsotope = [
[480, 4],
[720, 6]
];
var itemsPerPageDefault = 8;
var itemsPerPage = defineItemsPerPage();
var currentNumberPages = 1;
var currentPage = 1;
var currentFilter = '*';
var filterAttribute = 'data-filter';
var filterValue = "";
var pageAttribute = 'data-page';
var pagerClass = 'isotope-pager';
// update items based on current filters
function changeFilter(selector) {
$container.isotope({
filter: selector
});
}
//grab all checked filters and goto page on fresh isotope output
function goToPage(n) {
currentPage = n;
var selector = itemSelector;
var exclusives = [];
// for each box checked, add its value and push to array
$checkboxes.each(function(i, elem) {
if (elem.checked) {
selector += (currentFilter != '*') ? '.' + elem.value : '';
exclusives.push(selector);
}
});
// smash all values back together for 'and' filtering
filterValue = exclusives.length ? exclusives.join('') : '*';
// add page number to the string of filters
var wordPage = currentPage.toString();
filterValue += ('.' + wordPage);
changeFilter(filterValue);
}
// determine page breaks based on window width and preset values
function defineItemsPerPage() {
var pages = itemsPerPageDefault;
for (var i = 0; i < responsiveIsotope.length; i++) {
if ($(window).width() <= responsiveIsotope[i][0]) {
pages = responsiveIsotope[i][1];
break;
}
}
return pages;
}
function setPagination() {
var SettingsPagesOnItems = function() {
var itemsLength = $container.children(itemSelector).length;
var pages = Math.ceil(itemsLength / itemsPerPage);
var item = 1;
var page = 1;
var selector = itemSelector;
var exclusives = [];
// for each box checked, add its value and push to array
$checkboxes.each(function(i, elem) {
if (elem.checked) {
selector += (currentFilter != '*') ? '.' + elem.value : '';
exclusives.push(selector);
}
});
// smash all values back together for 'and' filtering
filterValue = exclusives.length ? exclusives.join('') : '*';
// find each child element with current filter values
$container.children(filterValue).each(function() {
// increment page if a new one is needed
if (item > itemsPerPage) {
page++;
item = 1;
}
// add page number to element as a class
wordPage = page.toString();
var classes = $(this).attr('class').split(' ');
var lastClass = classes[classes.length - 1];
// last class shorter than 4 will be a page number, if so, grab and replace
if (lastClass.length < 4) {
$(this).removeClass();
classes.pop();
classes.push(wordPage);
classes = classes.join(' ');
$(this).addClass(classes);
} else {
// if there was no page number, add it
$(this).addClass(wordPage);
}
item++;
});
currentNumberPages = page;
}();
// create page number navigation
var CreatePagers = function() {
var $isotopePager = ($('.' + pagerClass).length == 0) ? $('<div class="' + pagerClass + '"></div>') : $('.' + pagerClass);
$isotopePager.html('');
if (currentNumberPages > 1) {
for (var i = 0; i < currentNumberPages; i++) {
var $pager = $('');
$pager.html(i + 1);
$pager.click(function() {
var page = $(this).eq(0).attr(pageAttribute);
goToPage(page);
});
$pager.appendTo($isotopePager);
}
}
$container.after($isotopePager);
}();
}
// remove checks from all boxes and refilter
function clearAll() {
$checkboxes.each(function(i, elem) {
if (elem.checked) {
elem.checked = null;
}
});
currentFilter = '*';
setPagination();
goToPage(1);
}
setPagination();
goToPage(1);
//event handlers
$checkboxes.change(function() {
var filter = $(this).attr(filterAttribute);
currentFilter = filter;
setPagination();
goToPage(1);
});
$('#clear-filters').click(function() {
clearAll()
});
$(window).resize(function() {
itemsPerPage = defineItemsPerPage();
setPagination();
goToPage(1);
});

Why searchbox become lagging when typing word to search data in CSV?

I developed the store locator using open street map and leaflet. The problem is when I want to type in searchbox it will become lagging to finish the word. That store locator read from the CSV file that has 300++ data. Below is the code for the searchbox:
var locationLat = [];
var locationLng = [];
var locMarker;
var infoDiv = document.getElementById('storeinfo');
var infoDivInner = document.getElementById('infoDivInner');
var toggleSearch = document.getElementById('searchIcon');
var hasCircle = 0;
var circle = [];
//close store infor when x is clicked
var userLocation;
$("#infoClose").click(function() {
$("#storeinfo").hide();
if (map.hasLayer(circle)) {
map.removeLayer(circle);
}
});
var listings = document.getElementById('listingDiv');
var stores = L.geoJson().addTo(map);
var storesData = omnivore.csv('assets/data/table_1.csv');
function setActive(el) {
var siblings = listings.getElementsByTagName('div');
for (var i = 0; i < siblings.length; i++) {
siblings[i].className = siblings[i].className
.replace(/active/, '').replace(/\s\s*$/, '');
}
el.className += ' active';
}
function sortGeojson(a,b,prop) {
return (a.properties.name.toUpperCase() < b.properties.name.toUpperCase()) ? -1 : ((a.properties.name.toUpperCase() > b.properties.name.toUpperCase()) ? 1 : 0);
}
storesData.on('ready', function() {
var storesSorted = storesData.toGeoJSON();
//console.log(storesSorted);
var sorted = (storesSorted.features).sort(sortGeojson)
//console.log(sorted);
storesSorted.features = sorted;
//console.log(storesSorted)
stores.addData(storesSorted);
map.fitBounds(stores.getBounds());
toggleSearch.onclick = function() {
//var s = document.getElementById('searchbox');
//if (s.style.display != 'none') {
//s.style.display = 'yes';
//toggleSearch.innerHTML = '<i class="fa fa-search"></i>';
//$("#search-input").val("");
//search.collapse();
//document.getElementById('storeinfo').style.display = 'none';
//$('.item').show();
//} else {
//toggleSearch.innerHTML = '<i class="fa fa-times"></i>';
//s.style.display = 'block';
//attempt to autofocus search input field when opened
//$('#search-input').focus();
//}
};
stores.eachLayer(function(layer) {
//New jquery search
$('#searchbox').on('change paste keyup', function() {
var txt = $('#search-input').val();
$('.item').each(function() {
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
I dont know what is the cause of the lag in the search box. It is something wrong in code or the csv file? Thank you
Every iteration of $('.item').each is causing a layout change because $(this).hide() or $(this).show() causes the item to removed/added to the DOM as the style is set to display:none back and forth. DOM manipulations and the corresponding layout changes are expensive.
You can consider accumulating the changes and doing one batch update to the DOM using a function like appendChild

jquery html(array) doesn't insert all items in array

When I run the javascript code below, it load specified amount of images from Flickr.
By var photos = photoGroup.getPhotos(10) code, I get 10 images from cache.
Then, I can see the object has exactly 10 items by checking console.log(photos);
But actual image appeared on the page is less than 10 items...
I have no idea why this work this way..
Thank you in advance.
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
var PhotoGroup = function(nativePhotos, callback) {
var _cache = new Array();
var numberOfPhotosLoaded = 0;
var containerWidth = $("#contents").css('max-width');
var containerHeight = $("#contents").css('max-height');
$(nativePhotos).each(function(key, photo) {
$("<img src='"+"http://farm" + photo["farm"] + ".staticflickr.com/" + photo["server"] + "/" + photo["id"] + "_" + photo["secret"] + "_b.jpg"+"'/>")
.attr("alt", photo['title'])
.attr("data-cycle-title", photo['ownername'])
.load(function() {
if(this.naturalWidth >= this.naturalHeight) {
$(this).attr("width", containerWidth);
} else {
$(this).attr("height", containerHeight);
}
_cache.push(this);
if(nativePhotos.length == ++numberOfPhotosLoaded)
callback();
})
});
var getRandom = function(max) {
return Math.floor((Math.random()*max)+1);
}
this.getPhotos = function(numberOfPhotos) {
var photoPool = new Array();
var maxRandomNumber = _cache.length-1;
while(photoPool.length != numberOfPhotos) {
var index = getRandom(maxRandomNumber);
if($.inArray(_cache[index], photoPool))
photoPool.push(_cache[index]);
}
return photoPool;
}
}
var Contents = function() {
var self = this;
var contentTypes = ["#slideShowWrapper", "#video"];
var switchTo = function(nameOfContent) {
$(contentTypes).each(function(contentType) {
$(contentType).hide();
});
switch(nameOfContent) {
case("EHTV") :
$("#video").show();
break;
case("slideShow") :
$("#slideShowWrapper").show();
break;
default :
break;
}
}
this.startEHTV = function() {
switchTo("EHTV");
document._video = document.getElementById("video");
document._video.addEventListener("loadstart", function() {
document._video.playbackRate = 0.3;
}, false);
document._video.addEventListener("ended", startSlideShow, false);
document._video.play();
}
this.startSlideShow = function() {
switchTo("slideShow");
var photos = photoGroup.getPhotos(10)
console.log(photos);
$('#slideShow').html(photos);
}
var api_key = '6242dcd053cd0ad8d791edd975217606';
var group_id = '2359176#N25';
var flickerAPI = 'http://api.flickr.com/services/rest/?jsoncallback=?';
var photoGroup;
$.getJSON(flickerAPI, {
api_key: api_key,
group_id: group_id,
format: "json",
method: "flickr.groups.pools.getPhotos",
}).done(function(data) {
photoGroup = new PhotoGroup(data['photos']['photo'], self.startSlideShow);
});
}
var contents = new Contents();
</script>
</head>
<body>
<div id="slideShow"></div>
</body>
</html>
I fix your method getRandom() according to this article, and completely re-write method getPhotos():
this.getPhotos = function(numberOfPhotos) {
var available = _cache.length;
if (numberOfPhotos >= available) {
// just clone existing array
return _cache.slice(0);
}
var result = [];
var indices = [];
while (result.length != numberOfPhotos) {
var r = getRandom(available);
if ($.inArray(r, indices) == -1) {
indices.push(r);
result.push(_cache[r]);
}
}
return result;
}
Check full solution here: http://jsfiddle.net/JtDzZ/
But this method still slow, because loop may be quite long to execute due to same random numbers occurred.
If you care about performance, you need to create other stable solution. For ex., randomize only first index of your images sequence.

Triggering Prototype change event with jQuery

I don't have all that much experience with Prototype and I've been working with jQuery to get things working properly on our site found here. Today I've added a jQuery based script for session handling. The problem I'm having is that even though I've gotten so far today in terms of functionality, I can't seem to get the change event fired via jQuery.
I'm using the following code currently, but it isn't working properly (you can test it on the site.. as soon as you change the year using your mouse, the AJAX is triggered and a Make can be selected)...
var yearSelected = jQuery.jStorage.get("yearSelected");
console.log(yearSelected);
// Set the vars...
if ((jQuery("div.amfinder-horizontal td:nth-child(1) select").val() == "0")) {
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
jQuery("div.amfinder-horizontal td:nth-child(1) select").trigger('change');
console.log('Set the year!');
}
The following code is the Prototype script controlling this and I need to fire off the change event, and would love to do it via jQuery if at all possible.
var amFinder = new Class.create();
amFinder.prototype = {
initialize: function(containerId, ajaxUrl, loadingText, isNeedLast, autoSubmit)
{
this.containerId = containerId;
this.ajaxUrl = ajaxUrl;
this.autoSubmit = Number(autoSubmit);
this.loadingText = loadingText;
this.isNeedLast = Number(isNeedLast);
this.selects = new Array();
//possible bug if select order in the HTML will be different
$$('#' + this.containerId + ' select').each(function(select){
select.observe('change', this.onChange.bindAsEventListener(this));
this.selects[this.selects.length] = select;
}.bind(this));
},
onChange: function(event)
{
var select = Event.element(event);
var parentId = select.value;
var dropdownId = 0;
/* should load next element's options only if current is not the last one */
for (var i = 0; i < this.selects.length; i++){
if (this.selects[i].id == select.id && i != this.selects.length-1){
var selectToReload = this.selects[i + 1];
if (selectToReload){
dropdownId = selectToReload.id.substr(selectToReload.id.search('--') + 2);
}
break;
}
}
this.clearAllBelow(select);
if (0 != parentId && dropdownId){
var postData = 'dropdown_id=' + dropdownId + '&parent_id=' + parentId;
new Ajax.Request(this.ajaxUrl, {
method: 'post',
postBody : postData,
evalJSON : 'force',
onLoading: function(){
this.showLoading(selectToReload);
}.bind(this),
onSuccess: function(transport) {
if (transport.responseJSON){
this.clearSelectOptions(selectToReload);
var itemsFound = false;
transport.responseJSON.each(function(item){
itemsFound = true;
var option = document.createElement('option');
option.value = item.value;
option.text = item.label;
option.label = item.label;
$(selectToReload).appendChild(option);
});
if (itemsFound){
$(selectToReload).disabled = false;
}
}
}.bind(this)
});
}
},
isLast: function(select)
{
return (this.selects[this.selects.length-1].id == select.id);
},
isFirst: function(select)
{
return (this.selects[0].id == select.id);
},
clearSelectOptions: function(select)
{
$(select).descendants().each(function(option){
option.remove();
});
},
clearAllBelow: function(select)
{
var startClearing = false;
for (var i = 0; i < this.selects.length; i++){
if (startClearing){
this.clearSelectOptions(this.selects[i]);
$(this.selects[i]).disabled = true;
}
if (this.selects[i].id == select.id){
startClearing = true;
}
}
var type = (((this.isLast(select) && !this.isNeedLast) && select.value > 0) || ((this.isNeedLast) && ((select.value > 0) || (!this.isFirst(select))))) ? 'block' : 'none';
if ('block' == type && this.autoSubmit && this.isLast(select))
{
$$('#' + this.containerId + ' .amfinder-buttons button')[0].form.submit();
} else {
$$('#' + this.containerId + ' .amfinder-buttons')[0].style.display = type;
}
},
showLoading: function(selectToReload)
{
var option = document.createElement('option');
option.value = 0;
option.text = this.loadingText;
option.label = this.loadingText;
$(selectToReload).appendChild(option);
},
};
I had the same problem. Here is solution. When you create : amfinder-horizontal the html goes something like this
<div class="amfinder-horizontal" id="amfinder_5333ffb212b09Container">
...
</div>
Look at id element : amfinder_5333ffb212b09 Container, bold part is also the name of variable that is amfinder object (created from prototype). It's a random name. This is from the extension source :
<?php $finderId = 'amfinder_' . uniqid(); ?>
...
<script type="text/javascript">
var <?php echo $finderId ?> = new amFinder(
'<?php echo $finderId ?>Container',
'<?php echo $this->getAjaxUrl() ?>',
'<?php echo $this->__('Loading...')?>',
'<?php echo Mage::getStoreConfig('amfinder/general/partial_search')?>',
<?php echo intval(Mage::getStoreConfig('amfinder/general/auto_submit')) ?>
);
</script>
So on every page refresh there is different name. var <?php echo $finderId ?>
Steps :
// Find the name for amfinder object.
var objName = jQuery("div.amfinder-horizontal").attr('id').replace('Container','');
// set Value to that select - copied from your code
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
// call the change event of that object
var targetObj = {
target : jQuery("div.amfinder-horizontal td:nth-child(1) select")[0]
};
window[objName].onChange(targetObj);

jQuery Plugin development help

This is my first attempt at a plugin but I think I'm missing the whole "How to" on this.
Ok here goes:
Trying to write an error popup box for form validation.
I like the look and functionality on this JavaScript code on this page, See demo here and source here.
It's basically what I want to do if the user enters invalid data.
Now I have tried to create a jQuery plugin with this code but it's not working, any help would be great :-)
(function($){
/* Might use the fadein fadeout functions */
var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;
var errorBox = function(target, string, autohide, options)
{
var ebox = $(ebox);
var eboxcontent = $(eboxcontent);
var target = $(target);
var string = $(string);
var autohide = $(autohide);
var obj = this;
if (!document.getElementById('ebox')) {
ebox = document.createElement('div');
ebox.id = 'ebox';
eboxcontent = document.createElement('div');
eboxcontent.id = 'eboxcontent';
document.body.appendChild(ebox);
ebox.appendChild(eboxcontent);
ebox.style.filter = 'alpha(opacity=0)';
ebox.style.opacity = 0;
ebox.alpha = 0;
}
else {
ebox = document.getElementById('ebox');
eboxcontent = document.getElementById('eboxcontent');
}
eboxcontent.innerHTML = string;
ebox.style.display = 'block';
var msgheight = ebox.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
ebox.style.top = topposition + 'px';
ebox.style.left = leftposition + 'px';
clearInterval(ebox.timer);
ebox.timer = setInterval("fadeMsg(1)", MSGTIMER);
if (!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
// hide the form alert //
this.hideMsg(msg) = function (){
var msg = document.getElementById('msg');
if (!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
};
// face the message box //
this.fadeMsg(flag) = function() {
if (flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if (flag == 1) {
value = msg.alpha + MSGSPEED;
}
else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if (value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
}
else
if (value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
};
// calculate the position of the element in relation to the left of the browser //
this.leftPosition(target) = function() {
var left = 0;
if (target.offsetParent) {
while (1) {
left += target.offsetLeft;
if (!target.offsetParent) {
break;
}
target = target.offsetParent;
}
}
else
if (target.x) {
left += target.x;
}
return left;
};
// calculate the position of the element in relation to the top of the browser window //
this.topPosition(target) = function() {
var top = 0;
if (target.offsetParent) {
while (1) {
top += target.offsetTop;
if (!target.offsetParent) {
break;
}
target = target.offsetParent;
}
}
else
if (target.y) {
top += target.y;
}
return top;
};
// preload the arrow //
if (document.images) {
arrow = new Image(7, 80);
arrow.src = "images/msg_arrow.gif";
}
};
$.fn.errorbox = function(options)
{
this.each(function()
{
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('errorbox')) return;
// pass options to plugin constructor
var errorbox = new errorBox(this, options);
// Store plugin object in this element's data
element.data('errorbox', errorbox);
});
};
})(jQuery);
How Im calling it
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery Plugin - Error ToolTip</title>
<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript" src="js/jquery.errorbox.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var name = document.getElementById('name');
if(name == "") {
$('#name','You must enter your name.',2).errorbox();
alert("Blank");
}
});
</script>
<link rel="stylesheet" type="text/css" href="css/errorbox.css" />
</head>
<body>
<div>
Name: <input type="text" id="name" width="30"></input>
</div>
</body>
Any help on my first plugin would be great, thanks in advance.
--Phill
The var errorBox = function(... needs to change to:
$.errorBox = function(...
then you can call it on the jquery object.
Secondly, for clarity you may want to use $('#eboxcontent') instead of document.getElementById('eboxcontent') . It wont be any faster, but it is "clearer" to other jquery developers.
Lastly, jQuery has many built in functions for fading things over a specified time period, and it appears that you have built your own. I know that jQuery's fading is cross-browser compatible. just use:
$('#someDivId').fadeOut(timeInMilliseconds);
var name = document.getElementById('name');
if(name == "") {
//...
}
should be
var name = document.getElementById('name');
if(name.value == "") {
//...
}
or
var name = $('#name').val();
if(name == "") {
//...
}

Categories