Reload this javascript file after an ajax page load (YITH Infinite Scroll) - javascript

I have a woocommerce shop that has an ajax page load navigation. So a user clicks next page and more products are loaded via ajax.
However, I have a javascript file that manipulates the colors on each product on a page load. But since I have introduced this ajax page load, the script no longer loads after a next page is requested.
I am using YITH Infinite Page scroll. They have a trigger yith_infs_added_elem that I can use to do some code after the ajax has been loaded.
So I currently have:
jQuery(document).on('yith_infs_added_elem', function() {
});
This is the YITH trigger I have to use to run my script after the ajax has loaded.
But I am stuck. I have read many other solutions for other people, but I cannot seem to figure out how to reload my javascript file - /js/javascript/colors/dominant-color-shop.js.
My javascript file that normally runs on page load is:
jQuery( document ).ready( function( $ ) {
var image = new Image;
var colorThief = new ColorThief();
var bg;
var vibrant_color;
var vibrantText;
$('.post-image-hidden-container').each(function() {
bg = $(this).text();
var rgbs_text = [];
image.onload = function() {
$('.shop-page-item-thumb').each(function() {
var thumb = $(this);
var rgbs = [];
thumb.find('img').each(function() {
var vibrant = new Vibrant(this);
var swatches = vibrant.swatches();
var dominantColor = colorThief.getColor(this);
var productColorPalette = colorThief.getPalette(this, 12);
var productLightestColor = productColorPalette.reduce(function(previousValue, currentValue) {
var currLightNess = (0.2126*currentValue[0] + 0.7152*currentValue[1] + 0.0722*currentValue[2]);
var prevLightNess = (0.2126*previousValue[0] + 0.7152*previousValue[1] + 0.0722*previousValue[2]);
return (prevLightNess < currLightNess) ? currentValue : previousValue;
});
/* Create Shades and Tints of Lightest Color */
var lightShadeRGB = productLightestColor.join();
lightShadeRGB = lightShadeRGB.split(',');
var r = lightShadeRGB[0],
g = lightShadeRGB[1],
b = lightShadeRGB[2];
var rpt = lightShadeRGB[0] - 35,
gpt = lightShadeRGB[1] - 35,
bpt = lightShadeRGB[2] - 35;
var tintDk = 'rgb('+rpt+', '+gpt+', '+bpt+')';
for (var swatch in swatches) {
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
rgbs.push(swatches[swatch].getHex());
rgbs_text.push(swatches[swatch].getTitleTextColor());
}
}
vibrant_color = rgbs[0];
vibrant_color_2 = rgbs[1];
darkVibrant = rgbs[2];
darkMuted = rgbs[3];
lightVibrant = rgbs[4];
vibrantText = rgbs_text[0];
vibrantText_2 = rgbs_text[1];
darkVibrantText = rgbs_text[2];
darkMutedText = rgbs_text[3];
lightVibrantText = rgbs_text[4];
thumb.parent().find('.product-bottom-info-container').css({
borderTop: '4px solid ' + vibrant_color
});
thumb.parent().find('.hot-badge').css({
backgroundColor: darkMuted,
color: darkMutedText
});
thumb.parent().find('.mp3-badge').css({
backgroundColor: vibrant_color,
color: vibrantText
});
thumb.parent().find('.mp3-badge-link').css({
color: vibrantText
});
thumb.parent().find('.wav-badge').css({
backgroundColor: vibrant_color_2,
color: vibrantText_2
});
thumb.parent().find('.wav-badge-link').css({
color: vibrantText_2
});
thumb.parent().find('.hot-post-bookmark').css({
color: vibrant_color
});
thumb.parent().find('.the-rating-stars-icons').css({
color: vibrant_color
});
thumb.parent().find('.progress-bar').css({
backgroundColor: vibrant_color
});
});
});
}
image.src = bg;
});
$('#player-toggler-id').css({
backgroundColor: '#181f24'
});
});
It works fine until I request the next page. The javscript no longer works. How exactly can I call this script all over again, once the yith ajax has loaded with this trigger - yith_infs_added_elem.
I have read up on .on() .live() (which is deprecated), etc. Can anyone help?

Your function only runs on page load...
To trigger it again later, you should make it a named function.
So the script stays exactly the same, but wrapped with function arrangeColors(){ (You can name it as you wish) and }.
Then, in the ajax success callback, call this function again.
jQuery( document ).ready( function( $ ) {
function arrangeColors(){ // Make the script a named function
var image = new Image;
var colorThief = new ColorThief();
var bg;
var vibrant_color;
var vibrantText;
$('.post-image-hidden-container').each(function() {
bg = $(this).text();
var rgbs_text = [];
image.onload = function() {
$('.shop-page-item-thumb').each(function() {
var thumb = $(this);
var rgbs = [];
thumb.find('img').each(function() {
var vibrant = new Vibrant(this);
var swatches = vibrant.swatches();
var dominantColor = colorThief.getColor(this);
var productColorPalette = colorThief.getPalette(this, 12);
var productLightestColor = productColorPalette.reduce(function(previousValue, currentValue) {
var currLightNess = (0.2126*currentValue[0] + 0.7152*currentValue[1] + 0.0722*currentValue[2]);
var prevLightNess = (0.2126*previousValue[0] + 0.7152*previousValue[1] + 0.0722*previousValue[2]);
return (prevLightNess < currLightNess) ? currentValue : previousValue;
});
/* Create Shades and Tints of Lightest Color */
var lightShadeRGB = productLightestColor.join();
lightShadeRGB = lightShadeRGB.split(',');
var r = lightShadeRGB[0],
g = lightShadeRGB[1],
b = lightShadeRGB[2];
var rpt = lightShadeRGB[0] - 35,
gpt = lightShadeRGB[1] - 35,
bpt = lightShadeRGB[2] - 35;
var tintDk = 'rgb('+rpt+', '+gpt+', '+bpt+')';
for (var swatch in swatches) {
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
rgbs.push(swatches[swatch].getHex());
rgbs_text.push(swatches[swatch].getTitleTextColor());
}
}
vibrant_color = rgbs[0];
vibrant_color_2 = rgbs[1];
darkVibrant = rgbs[2];
darkMuted = rgbs[3];
lightVibrant = rgbs[4];
vibrantText = rgbs_text[0];
vibrantText_2 = rgbs_text[1];
darkVibrantText = rgbs_text[2];
darkMutedText = rgbs_text[3];
lightVibrantText = rgbs_text[4];
thumb.parent().find('.product-bottom-info-container').css({
borderTop: '4px solid ' + vibrant_color
});
thumb.parent().find('.hot-badge').css({
backgroundColor: darkMuted,
color: darkMutedText
});
thumb.parent().find('.mp3-badge').css({
backgroundColor: vibrant_color,
color: vibrantText
});
thumb.parent().find('.mp3-badge-link').css({
color: vibrantText
});
thumb.parent().find('.wav-badge').css({
backgroundColor: vibrant_color_2,
color: vibrantText_2
});
thumb.parent().find('.wav-badge-link').css({
color: vibrantText_2
});
thumb.parent().find('.hot-post-bookmark').css({
color: vibrant_color
});
thumb.parent().find('.the-rating-stars-icons').css({
color: vibrant_color
});
thumb.parent().find('.progress-bar').css({
backgroundColor: vibrant_color
});
});
});
}
image.src = bg;
});
$('#player-toggler-id').css({
backgroundColor: '#181f24'
});
} // Add this closing bracket
// Call the function on load
arrangeColors();
});

I make it work now like this:
<script type="text/javascript">
jQuery(document).ready(function ($) {
loadAnimation();
jQuery(document).on("yith_infs_added_elem", function () {
loadAnimation();
});
function loadAnimation() {
//here put your code for something to doin my case .add-to-cart trigger
}
//here other functions for example flyToElement
});
</script>

Related

prettyPhoto change title on hover over thumbnail

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

Modifying Titanium Widgets without using global variables

I am trying to modify the following titanium Widget.
https://github.com/pablorr18/TiFlexiGrid
It is a photo gallery, where you can fetch remote images and store it in a gallery. See this question for a background to what the problem is:
Modifying widgets in an alloy project
The trouble I am having is that, like the poster in that thread said, I am unable to get the variable passed (in this case image URL) to my controller using callback functions. In Widget.JS, at the bottom of the file, I added the following code:
Widget.xml
<Alloy>
<View id="fgMain">
<Button title="Click me!" onTouchend="buttonClicked"/>
<View id="fgWrapper">
<ScrollView id="fgScrollView"/>
</View>
</View>
</Alloy>
Widget.js
// This will hold our callback
var onClickCallback;
// The button has been clicked, call callback
function buttonClicked(e) {
if(typeof(onClickCallback) === 'function') {
onClickCallback({ type:'clicked!' }); }
}
// Assign our callback
function onClick(callback) {
onClickCallback = callback;
};
// Make the onClick function public
exports.onClick = onClick;
I was then hoping to go into my main app and get the values from the callback function like this:
photoGallery.xml
<Alloy>
<Window>
<Widget id="myWidget" src="myWidget" />
</Window>
</Alloy>
photoGallery.js
// Now we can intercept the click within the widget
// and use the values passed
$.myWidget.onClick(function(e) {
alert(e.type);
});
The trouble is, as the onTouchend event did not fire, I was unable to pass the variable to the controller which inherits the widget as the callback functions are not set.
The original widget.js code is as follows:
exports.createGrid = function(args){
var params = args || {};
//Ti.API.info('Params es ---> '+ JSON.stringify(params));
var columns = params.columns || 4;
var space = params.space || 5;
var data = params.data || {};
var options = params.params || {};
var layout = params.layout || 'gallery';
var screenWidth = params.width || Ti.Platform.displayCaps.getPlatformWidth();
if (OS_ANDROID) {
screenWidth /= Ti.Platform.displayCaps.logicalDensityFactor;
}
var newWidth = screenWidth - space;
var columnWidth = (newWidth / columns) - space;
var frameBGcolor = options.backgroundColor || '#fff';
//ADJUST THE SCROLLVIEW
$.fgScrollView.left = space;
$.fgScrollView.top = space;
$.fgScrollView.right = -1;
$.fgMain.backgroundColor = frameBGcolor;
for (var x=0;x < data.length; x++){
var frame = Ti.UI.createView({
width:columnWidth,
height:columnWidth,
backgroundColor:options.gridColor || '#eee',
top:0,
left:0,
right:space,
bottom:space
});
var overlay = Ti.UI.createView({
width:Ti.UI.FILL,
height:Ti.UI.FILL,
backgroundColor:'transparent',
zIndex:1,
strImage:data[x].image
});
var gridElement;
//TYPE OF LAYOUT
switch(layout){
case('gallery'):
gridElement = Widget.createController('gallery',{
image:data[x].image,
title:data[x].title,
width:columnWidth,
padding:options.padding || 10,
showTitle:options.showTitle || false
}).getView();
overlay.addEventListener('click',function(e){
exports.openModal(e.source.strImage);
});
break;
case('customView'):
gridElement = data[x];
break;
}
frame.add(gridElement);
// This condition makes the overlay not be added if it's not gallery layout.
// It's used to make the custom view, caputre the click method. If not,
// The overlay is on top of it and captures the click.
if(layout == 'gallery')
frame.add(overlay);
$.fgScrollView.add(frame);
};
};
exports.openModal = function(url){
var overlay = Ti.UI.createView({
width:Ti.UI.FILL,
height: Ti.UI.FILL,
backgroundColor:'#000',
opacity:0,
zIndex:100
});
var topView = Ti.UI.createView({
width:Ti.UI.FILL,
height: Ti.UI.FILL,
zIndex:1200,
visible:false
});
//this gets image , adds it to top view
var imgView = Ti.UI.createImageView({
image: url,
width:Ti.UI.SIZE,
height: Ti.UI.SIZE
});
//add it
topView.add(imgView);
$.fgMain.add(overlay);
if (OS_IOS){
//ANIMATION OF OVERLAY
overlay.animate({opacity:0.7,duration:200});
//ANIMATION FOR POP EFFECT
var t = Titanium.UI.create2DMatrix();
t = t.scale(0);
var a = Titanium.UI.createAnimation();
a.transform = t;
a.duration = 200;
$.fgMain.add(topView);
topView.animate(a);
a.addEventListener('complete', function(){
topView.visible = true;
var t2 = Titanium.UI.create2DMatrix();
t2 = t2.scale(1.2);
topView.animate({transform:t2, duration:200},function(e){
var t4 = Titanium.UI.create2DMatrix();
t4 = t4.scale(1.0);
topView.animate({transform:t4, duration:200});
//alert('animation complete');
//hide cancel button
});
});
}
else{
//ANIMATION OF OVERLAY
overlay.animate({opacity:0.7,duration:200},function(e){
topView.visible = true;
$.fgMain.add(topView);
});
}
topView.addEventListener('click',function(e){
if (OS_IOS){
var t3 = Titanium.UI.create2DMatrix();
t3 = t3.scale(1.2);
var a2 = Titanium.UI.createAnimation();
a2.transform = t3;
a2.duration = 200;
topView.animate(a2);
a2.addEventListener('complete', function(){
var t5 = Titanium.UI.create2DMatrix();
t5 = t5.scale(0);
topView.animate({transform:t5, duration:200},function(e){
$.fgMain.remove(topView);
overlay.animate({opacity:0,duration:200},function(e){
$.fgMain.remove(overlay);
});
});
});
}
else{
$.fgMain.remove(topView);
overlay.animate({opacity:0,duration:200},function(e){
$.fgMain.remove(overlay);
});
}
});
};
exports.clearGrid = function(){
$.fgScrollView.removeAllChildren();
};
From looking at it, the only way it seems to get an event handler to register is to put it one of the functions (createGrid) and call it like this:
exports.createGrid in widget.xml
var button = Titanium.UI.createButton({
title : 'Use Picture',
top : 10,
width : 100,
height : 50
});
button.addEventListener('click',function(e)
{
Titanium.API.info(url);
//do not want to store in global variable
Alloy.Globals.urlFromGal = url;
});
//add it
topView.add(imgView);
topView.add(button);
$.fgMain.add(overlay);
However I am not sure how to adapt that code to this:
// This will hold our callback
var onClickCallback;
// The button has been clicked, call callback
function buttonClicked(e) {
if(typeof(onClickCallback) === 'function') {
onClickCallback({ type:'clicked!' }); }
}
// Assign our callback
function onClick(callback) {
onClickCallback = callback;
};
// Make the onClick function public
exports.onClick = onClick;
So that I am able to access the url variable outside of the widget.js scope. I could use GLOBAL Variables - by that store the variable in one instead for this task, however I want to avoid doing things this way.
UPDATE:
Unable to get it working, but I have added the callback into an event handler. Got the event handler to fire, but not sure how to pass the callback data to onClick function:
var onClickCallback;
exports.createGrid = function(args){
var params = args || {};
//Ti.API.info('Params es ---> '+ JSON.stringify(params));
var columns = params.columns || 4;
var space = params.space || 5;
var data = params.data || {};
var options = params.params || {};
var layout = params.layout || 'gallery';
var screenWidth = params.width || Ti.Platform.displayCaps.getPlatformWidth();
if (OS_ANDROID) {
screenWidth /= Ti.Platform.displayCaps.logicalDensityFactor;
}
var newWidth = screenWidth - space;
var columnWidth = (newWidth / columns) - space;
var frameBGcolor = options.backgroundColor || '#fff';
//ADJUST THE SCROLLVIEW
$.fgScrollView.left = space;
$.fgScrollView.top = space;
$.fgScrollView.right = -1;
$.fgMain.backgroundColor = frameBGcolor;
for (var x=0;x < data.length; x++){
var frame = Ti.UI.createView({
width:columnWidth,
height:columnWidth,
backgroundColor:options.gridColor || '#eee',
top:0,
left:0,
right:space,
bottom:space
});
var overlay = Ti.UI.createView({
width:Ti.UI.FILL,
height:Ti.UI.FILL,
backgroundColor:'transparent',
zIndex:1,
strImage:data[x].image
});
var gridElement;
//TYPE OF LAYOUT
switch(layout){
case('gallery'):
gridElement = Widget.createController('gallery',{
image:data[x].image,
title:data[x].title,
width:columnWidth,
padding:options.padding || 10,
showTitle:options.showTitle || false
}).getView();
overlay.addEventListener('click',function(e){
exports.openModal(e.source.strImage);
});
break;
case('customView'):
gridElement = data[x];
break;
}
frame.add(gridElement);
// This condition makes the overlay not be added if it's not gallery layout.
// It's used to make the custom view, caputre the click method. If not,
// The overlay is on top of it and captures the click.
if(layout == 'gallery')
frame.add(overlay);
$.fgScrollView.add(frame);
};
};
exports.openModal = function(url){
var overlay = Ti.UI.createView({
width:Ti.UI.FILL,
height: Ti.UI.FILL,
backgroundColor:'#000',
opacity:0,
zIndex:100
});
var topView = Ti.UI.createView({
width:Ti.UI.FILL,
height: Ti.UI.FILL,
zIndex:1200,
visible:false
});
//this gets image , adds it to top view
var imgView = Ti.UI.createImageView({
image: url,
width:Ti.UI.SIZE,
height: Ti.UI.SIZE
});
var button = Titanium.UI.createButton({
title : 'Use Picture',
top : 10,
width : 100,
height : 50
});
button.addEventListener('touchend',function(e)
{
//Titanium.API.info(url);
if(typeof(onClickCallback) === 'function') {
onClickCallback({ type:'clicked!' }); }
});
//pass callback, not working
onClick();
//add it
topView.add(imgView);
topView.add(button);
$.fgMain.add(overlay);
if (OS_IOS){
//ANIMATION OF OVERLAY
overlay.animate({opacity:0.7,duration:200});
//ANIMATION FOR POP EFFECT
var t = Titanium.UI.create2DMatrix();
t = t.scale(0);
var a = Titanium.UI.createAnimation();
a.transform = t;
a.duration = 200;
$.fgMain.add(topView);
topView.animate(a);
a.addEventListener('complete', function(){
topView.visible = true;
var t2 = Titanium.UI.create2DMatrix();
t2 = t2.scale(1.2);
topView.animate({transform:t2, duration:200},function(e){
var t4 = Titanium.UI.create2DMatrix();
t4 = t4.scale(1.0);
topView.animate({transform:t4, duration:200});
//alert('animation complete');
//hide cancel button
});
});
}
else{
//ANIMATION OF OVERLAY
overlay.animate({opacity:0.7,duration:200},function(e){
topView.visible = true;
$.fgMain.add(topView);
});
}
topView.addEventListener('click',function(e){
if (OS_IOS){
var t3 = Titanium.UI.create2DMatrix();
t3 = t3.scale(1.2);
var a2 = Titanium.UI.createAnimation();
a2.transform = t3;
a2.duration = 200;
topView.animate(a2);
a2.addEventListener('complete', function(){
var t5 = Titanium.UI.create2DMatrix();
t5 = t5.scale(0);
topView.animate({transform:t5, duration:200},function(e){
$.fgMain.remove(topView);
overlay.animate({opacity:0,duration:200},function(e){
$.fgMain.remove(overlay);
});
});
});
}
else{
$.fgMain.remove(topView);
overlay.animate({opacity:0,duration:200},function(e){
$.fgMain.remove(overlay);
});
}
});
};
exports.clearGrid = function(){
$.fgScrollView.removeAllChildren();
};
// Assign our callback
function onClick(callback) {
onClickCallback = callback;
alert(onClickCallback);
};
// Make the onClick function public
exports.onClick = onClick;

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.

Is it possible to write legend to a separate division with jqPlot

I want to write the legend to a separate div, is this possible with jqPlot
legend: {
show: true,
placement: 'outside',
fontSize: '11px',
location: 'n'
}
Here our the two function which you can use:
function graphLegendCreation(cnt){
var parentNode = _g("dmGraphLegend")//trying to get the div element with id dmGraphLegend
, newLegendItemNode = Util.ce("span") //creating an span element
, newLegendItemSelect = Util.cep("input", { //creating an input element
"type":"checkbox",
"name":"graphLegend",
"checked":true,
"value":cnt
})
, newLegendItemIconNode = Util.cep("canvas", {
"id":"series_icon_"+cnt,
"className":"series_icons"
});
newLegendItemIconNode.style.display = "inline-block";
newLegendItemIconNode.style.position = "relative";
if(parentNode) {
newLegendItemNode.innerHTML = graphPlot.series[cnt].label;
newLegendItemSelect = Util.ac(newLegendItemSelect,parentNode);
newLegendItemSelect.checked = true;
Util.addEvent(newLegendItemSelect,"click", function(e) {
graphPlot.series[this.value].show = newLegendItemSelect.checked;
graphPlot.redraw(false);
})
newLegendItemIconNode = Util.ac(newLegendItemIconNode,parentNode);
newLegendItemNode = Util.ac(newLegendItemNode,parentNode);
Util.ac(Util.ce("br"),parentNode);
}
}
function showlegend() {
var cntr = 0
,len = 0
,iconNodes
,legendItemIconNode
,seriesSequence = 0
,context
,bMarker;
iconNodes = Util.Style.g("series_icons");
len = iconNodes.length;
for(cntr = 0; cntr < len; cntr++) {
legendItemIconNode = iconNodes[cntr];
if ($.browser.msie) {
G_vmlCanvasManager.initElement(legendItemIconNode);
}
context = legendItemIconNode.getContext('2d');
bMarker = new nMarkerRenderer({
size:8,
color:graphPlot.series[cntr].color,
style:graphPlot.series[cntr].markerOptions.style
});
bMarker.draw(12,12,context, {});
}
}
CSS:
.series_icons{width:20px;height:20px;}
GraphLegendCreation function you have to call that each time you create a entry inside legend.
ShowLegend is just going to create that legend icons.
The "nMarkrenderer" is already a defined function. Get that function from jsfiddle file
Let me know you want more help with this. It works for sure on IE. tried and tested

Run native JavaScript function on page load

With the help of you fantastic JavaScript wizards I've got a native JavaScript function that beefs up the size of an HTML5 video when clicking a button and then re-runs whenever the window is resized.
I'd like to remove the button from the equation instead launching it on page load, remove the class name dependencies (if they're still in after button removal), while maintaining the window resize trigger.
Thanks for your help! Couldn't do it without you. A demo can be seen at http://kzmnt.com/test/
JavaScript:
var clicked = document.getElementById("buttonImportant")
var videoContainer = document.getElementById('video_container');
var video = videoContainer.getElementsByTagName('video')[0];
video.style.height="auto";
video.style.width="1280px";
clicked.addEventListener('click',function(){
if( videoContainer.className.lastIndexOf("fullScreen")>=0 ){
videoContainer.className="video-js-box";
video.style.height = "";
video.style.width="";
}
else
{
videoContainer.className="video-js-box fullScreen";
video.style.height = "";
video.style.width="";
}
myResizerObject.prevWidth = video.offsetWidth;
myResizerObject.prevHeight = video.offsetHeight;
myResizerObject.Init();
},false);
var RESIZER = function(){
this.prevWidth = video.offsetWidth;
this.prevHeight = video.offsetHeight;
this.videoContainer = document.getElementById('video_container');
this.video = videoContainer.getElementsByTagName('video')[0];
this.videoStyle = this.video.style;
var ratio = this.video.offsetHeight/this.video.offsetWidth;
var that = this;
this.Init = function(){
if( that.videoContainer.className.lastIndexOf("fullScreen")>=0 )
{
var videoContOffsetWidth = that.videoContainer.offsetWidth;
var videoOffsetWidth = that.video.offsetWidth;
var videoContOffsetHeight = that.videoContainer.offsetHeight;
var videoOffsetHeight = that.video.offsetHeight;
if(that.prevWidth!= videoContOffsetWidth)
{
that.prevWidth = videoContOffsetWidth;
var desired = videoContainer.offsetHeight/videoContainer.offsetWidth;
if(desired>ratio){
that.videoStyle.width=videoContOffsetWidth*desired+videoContOffsetWidth*desired+"px";
that.videoStyle.left = -1*(videoOffsetWidth-videoContOffsetWidth)/2+'px';
}
else{
that.videoStyle.cssText="height:auto;width:100%;left:0px;top:0px;";
}
}
if(that.prevHeight!=videoContOffsetHeight)
{
that.prevHeight = videoContOffsetHeight;
var desired = videoContOffsetHeight/videoContOffsetWidth;
if(desired>ratio){ console.log(ratio);
that.videoStyle.top = '0px';
that.videoStyle.left = -1*(videoOffsetWidth-videoContOffsetWidth)/2+'px';
that.videoStyle.width = videoContOffsetHeight*desired+videoContOffsetHeight/desired+'px';
}
else
{
that.videoStyle.top = -1*(videoOffsetHeight-videoContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
Are you looking for something like...
window.onload = mySuperCoolFunction;
And why do you need jQuery? Maybe you could explicitly state your goals/questions at the bottom in bold so that we can help you :)
If you're only looking to init another function, why not just add the call to your superCoolFunction while you're calling your other pre-written jQuery function. For example:
$(document).ready(function() {
center();
mySuperCoolFunction(); // not necessary to init in another file...
});
$(window).load(function(){
center();
mySuperCoolFunction();
});
$(window).resize(function(){
center();
mySuperCoolFunction();
});
Rewritten in jQuery:
$(function() {
$('video').eq(0).css({
height: "auto",
width: "1280px"
});
if ($('#video_container').hasClass('fullScreen')) {
$('#video_container').attr('class', 'video-js-box');
$('video').eq(0).css({
height: "auto",
width: "1280px"
});
}
else {
$('#video_container').attr('class', 'video-js-box fullscreen');
$('video').eq(0).css({
height: "auto",
width: "1280px"
});
}
myResizerObject.prevWidth = video.offsetWidth;
myResizerObject.prevHeight = video.offsetHeight;
myResizerObject.Init();
});

Categories