jCarousel initializing/refreshing/reloading each time clicked on image - php

I am making a picture preview with jCarousel (http://sorgalla.com/projects/jcarousel/), but faced with one problem: I do not know how could I reload/refresh jCarousel dynamic list.
I have few categories of images. When I click on a picture in one of that, I need that the list would be created and preview start with that element. I have some code, but do not know how to make it re-create all list after clicking on other image that preview start with other image.
Here are my code:
$(document).ready(function(){
$("ul#stage li").live('click', function() {
var ul = $(this).parent();
var index = +(ul.children().index(this))+1;
var mycarousel_itemList = [ ];
$('li[data-id]').each(function () {
var $this = $(this);
mycarousel_itemList.push({
url : $this.attr("data-img"),
title : $this.attr("data-title")
});
});
function mycarousel_itemLoadCallback(carousel, state) {
for (var i = carousel.first; i <= carousel.last; i++) {
if (carousel.has(i)) {
continue;
}
if (i > mycarousel_itemList.length) {
break;
}
carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i-1]));
}
};
function mycarousel_getItemHTML(item) {
return '<img src="' + item.url + '" width="800" height="600" alt="' + item.url + '" />';
};
alert(index);
jQuery('#mycarousel').jcarousel({
itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback},
size: mycarousel_itemList.length,
scroll: 1,
start: index,
wrap: 'last',
animation: 'fast',
visible: 1
});
document.getElementById('popup-content').style.background='url('+$(this).attr("data-img")+') no-repeat center';
document.getElementById('fades').style.display='block';
document.getElementById("light").style.display = "block";
$("#light").fadeTo("slow", 1);
});
});
Everything is like that: there are images > I click on one of those > popup shows with jCarousel and one visible image and then I could scroll through all other images.
It is working good, but just a first time. When I click on other image (after closing popup), the view starts with that image which was opened last.
If something are not clear enough - please, ask. I will try to make it more precisely.
Thanks for your help!

You can recreate jCarousel, first use $('#mycarousel').remove(); and next init jCarousel again. I didn't really understand what you're trying to do, but this can help in most cases, of course jCarousel should have Destroy method but it hasn't.
And why you don't use jquery selectors in some cases?

Related

Edit DIVs after .append()

My algorithm:
I get the DIV text from php/SQL ($.get( "read.php"...)
APPEND contenteditable div with loaded text by jQuery
check the div value, if there is errors in text I make div red (assign class, $(this).addClass("fill_red");)
on every change of text - check and assign/remove class if needed.
Problem is: with preloaded text - everything is working.
But when I append div using JS - check function don't works.
I searched the web, maybe on() method helps me.
But what event?
It should be something like onload, onchange..?
(yes, I could make div generated by php and solve the problem, but I dont want full refresh)
Thank you!
part of code:
//texts load
$(function() {
$.get( "read.php", function( data ) {
var ionka = data.split(' ');
ionka.forEach(function(item, i, arr) {
var app_text = "<div id=\"segm" + i + "\" contenteditable role=\"textbox\">" + item + "</div>";
$("#textarea").append(app_text);
});
});
//checks
var intRegex = new RegExp('^[0-9/\]{5}$');
$('#textarea div').each(function(i,elem) {
if(!intRegex.test($(this).text())) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
});
// edit on change. Blur because of contenteditable
var segm_array = [];
$('#textarea div').each(function(i,elem) {
$(this).blur(function() {
if (segm_array[i]!=$(this).text()){
segm_array[i] = $(this).text();
if(!intRegex.test(segm_array[i])) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
}
});
});
You dont show much code here, but my guess is that you are trying to add class before new data is loaded into dom
$.get( "read.php" ).done(function( data ) {
// addClass etc
});

Jquery selector not working after append

I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.

Plot coordinates on PDF displayed in iFrame

Firstly I appreciate my request is quite "ambitious", but any help is greatly appreciated as I'm not sure the best way to proceed.
On my site (built with PHP/MySQL) after a user has uploaded a PDF I would like to display the PDF inline on the page (I'm assuming in an iFrame). I then need them to be able to drag out a number of "boxes" on top of the PDF (I'm assuming with jQuery). I then need to record the co-ordinates of this box so then later I can re-create the PDF injecting new text into the defined "boxes".
Does this sound feasible? If not what else would you suggest? (please don't say imagemagick!)
I know how to recreate a PDF injecting new text, but my issue is with how to allow the user to record those coordinates.
You could use PDF.js to render the PDF on the page. PDF.js will display it as part of the page so you can attach events and interact with it in ways you could not if it was being displayed by the Acrobat plugin.
I couldn't find a preexisting library for getting the coordinates so I whipped up this code to implement it.
Live demo of selection code
$(function () {
"use strict";
var startX,
startY,
selectedBoxes = [],
$selectionMarquee = $('#selectionMarquee'),
positionBox = function ($box, coordinates) {
$box.css(
'top', coordinates.top
).css(
'left', coordinates.left
).css(
'height', coordinates.bottom - coordinates.top
).css(
'width', coordinates.right - coordinates.left
);
},
compareNumbers = function (a, b) {
return a - b;
},
getBoxCoordinates = function (startX, startY, endX, endY) {
var x = [startX, endX].sort(compareNumbers),
y = [startY, endY].sort(compareNumbers);
return {
top: y[0],
left: x[0],
right: x[1],
bottom: y[1]
};
},
trackMouse = function (event) {
var position = getBoxCoordinates(startX, startY,
event.pageX, event.pageY);
positionBox($selectionMarquee, position);
};
$(document).on('mousedown', function (event) {
startX = event.pageX;
startY = event.pageY;
positionBox($selectionMarquee,
getBoxCoordinates(startX, startY, startX, startY));
$selectionMarquee.show();
$(this).on('mousemove', trackMouse);
}).on('mouseup', function (event) {
var position,
$selectedBox;
$selectionMarquee.hide();
position = getBoxCoordinates(startX, startY,
event.pageX, event.pageY);
if (position.left !== position.right &&
position.top !== position.bottom) {
$selectedBox = $('<div class="selected-box"></div>');
$selectedBox.hide();
$('body').append($selectedBox);
positionBox($selectedBox, position);
$selectedBox.show();
selectedBoxes.push(position);
$(this).off('mousemove', trackMouse);
}
});
});
You will have to tweak it to get coordinates that are relative to the PDF once you display it, but this should get you on the right track.

Jquery overlay from checking php variable

I have this script from JQuery.
<script>
// create custom animation algorithm for jQuery called "drop"
$.easing.drop = function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
};
// loading animation
$.tools.overlay.addEffect("drop", function(css, done) {
// use Overlay API to gain access to crucial elements
var conf = this.getConf(),
overlay = this.getOverlay();
// determine initial position for the overlay
if (conf.fixed) {
css.position = 'fixed';
} else {
css.top += $(window).scrollTop();
css.left += $(window).scrollLeft();
css.position = 'absolute';
}
// position the overlay and show it
overlay.css(css).show();
// begin animating with our custom easing
overlay.animate({ top: '+=55', opacity: 1, width: '+=20'}, 400, 'drop', done);
/* closing animation */
}, function(done) {
this.getOverlay().animate({top:'-=55', opacity:0, width:'-=20'}, 300, 'drop', function() {
$(this).hide();
done.call();
});
}
);
$("img[rel]").overlay({
effect: 'drop',
mask: '#789'
});
</script>
Right now it works by me clicking on an image. Then the overlay comes up with whatever is in the div. However I want to take out clicking the image and just have the overlay come up with an if statement in PHP. any ideas...im not very good at js.
EDIT:
yes im using the JQuery plugin Easing. However the overlay works great...and the overlay works by clicking on an image with the rel attribute like this
<img src="http://farm4.static.flickr.com/3651/3445879840_7ca4b491e9_m.jpg" rel="#mies1"/>
However I don't want to click on the images I want it to come up automatically.
<?php if ($whatever) { ?>
$(document).ready(function() {
$("img[rel]").click();
});
<?php } ?>

Integrating a javascript object with jquery

I have this js object which I got from php through jason_encode(). This object has 2 objects, Name and Video. Then through a for loop I distribute the names into divs. My problem is I need to create a link in each div that would create a dialog that displays the video.
I'm basing this idea from the jquery UI example: http://jqueryui.com/demos/droppable/#photo-manager
Specifically the view larger icon which I intend to have the same dialog except embedding a youtube video.
Here is the code that gets the values from the jscript object and puts them in divs.
for ( var i in BodyWeight )
{
if(BodyWeight[i]['Color'] == 'Red')
{
$('#redboxes').append('<div class="ui-widget-content dragred"><p>' + BodyWeight[i]["ExerciseTitle"] + '</p> </div>');
}
else if(BodyWeight[i]['Color'] == 'Blue')
{
$('#blueboxes').append('<div class="ui-widget-content dragblue"><p>' + BodyWeight[i]["ExerciseTitle"] + '</p> </div>');
}
}
Then basically I would have a icons in each that should just have in it the data from ExerciseVideo. I just can't figure out how to connect both objects together. In the jquery example they image url is embedded in a href unfortunately I can't do the same for a video.
This hasn't been tested, but it might work. Edit: It actually is tested and does work now. Note that this assumes that Video is a YouTube video ID, not a YouTube video URL. (ie. we're assuming Video is the part after the ?v= in the YouTube URL)
for(var i=0;i<BodyWeight.length;i++) {
var exercise=BodyWeight[i];
var elem=$('<div class="ui-widget-content"><p>'+exercise["ExerciseTitle"]+'</p></div>');
elem.addClass("drag"+exercise['Color'].toLowerCase());
elem.appendTo("#"+exercise['Color'].toLowerCase()+"boxes");
elem.data("exercise", exercise);
elem.click(function() {
var exercise=$(this).data("exercise");
var div=$("<div>");
var obj=$("<object>");
obj.attr("type", "application/x-shockwave-flash");
obj.attr("data", "http://www.youtube.com/v/"+exercise["Video"]);
obj.attr("width", "400").attr("height", "300");
obj.appendTo(div);
div.hide().appendTo("body");
setTimeout(function() {
div.dialog({
title: exercise["ExerciseTitle"],
width: 435,
modal: true,
close: function(event, ui) {
div.remove();
}
});
}, 1);
return false;
});
}
I do not really know if this is what you need, I hope it will be usefull
for ( var i in BodyWeight ) {
var mydiv = $('<div class="ui-widget-content"></div>'),
myp = $('<p>'+BodyWeight[i]["ExerciseTitle"]+'</p>'),
mylink = $('<a>View video</a>'),
linkVideo = BodyWeight['linkToVideo'] ;
mylink
.attr('href','#')
.click(function(ev){
ev.stopPropagation();
//acction for linkVideo
alert(linkVideo);
});
mydiv
.append(myp)
.append(mylink);
if(BodyWeight[i]['Color'] == 'Red') {
mydiv.addClass("dragred").appendTo($('#redboxes'));
}
else if(BodyWeight[i]['Color'] == 'Blue') {
mydiv.addClass("dragblue").appendTo($('#blueboxes'));
}
}
Just a comment to andres and to mike (I prefer to put it here so that codes below are readable).
This block of codes:
if(BodyWeight[i]['Color'] == 'Red') {
mydiv.addClass("dragred").appendTo($('#redboxes'));
}
else if(BodyWeight[i]['Color'] == 'Blue') {
mydiv.addClass("dragblue").appendTo($('#blueboxes'));
}
why not make it:
var color = BodyWeight[i]['Color'].toLowerCase();
mydiv.addClass("drag"+color).appendTo($('#'+color+'boxes'));
much better I think.

Categories