How to get zoom working with turn.js - javascript

I am trying to make a flipbook using turn.js that has the same functionality as the example on the website http://www.turnjs.com/samples/magazine/
When looking at how to achieve this I came across these pages
http://www.turnjs.com/docs/Method:_zoom
http://turnjs.com/docs/How_to_add_zoom_to_turn.js
But after following these instructions on the pages my flipbook works nothing like the sample one.
I tried using the sample provided and breaking it down into sections to get mine working but I have not gotten any closer to solving this problem and the sample contains a bunch of other scripts and I am not sure if they are required for the zoom or are used for other things.
Not sure if I am missing something really simple or if my code is really off but my html looks something like this.
Right now all I get when clicking the zoom button is that the book scales up 150%
Was wondering if anyone could tell me what I am missing to get that zoom?
<div class="row">
<div id="zoom-viewport">
<div id="flipbook">
// wordpress loop
<div class="page">
// page contents
</div>
// end loop
</div>
</div>
</div>
and jQuery
//----------------------------
// Initialize
var _width = $('#flipbook-wrap').width(),
_height = Math.round(70.909090909/100*_width),
_winWidth = $window.width(),
_winHeight = $window.height();
$("#flipbook").turn({
width: _width,
height: _height,
autoCenter: true
});
//----------------------------
// Zoom in button
$('.fullscreen').click(function(e){
e.preventDefault();
$("#flipbook").turn("zoom", 1.5);
});

Your code isn't showing everything (e.g. where ".fullscreen" or the "zoom button" is in your HTML), so my answer may not be precise.
Looking at the sample, you should find the code:
$('.magazine-viewport').zoom('zoomIn', pos);
This seems to differ from turn('zoom', ...), and appears to be undocumented. This is a function that will zoom in the element defined as a turn object. I believe, for you, this is your "#flipbook" element, instead of ".magazine-viewport".
The parameters are "zoomIn" and pos, which may be a different functionality that what you're using currently. The "pos" appears to be a JS object that contains "x" and "y" properties, meant to define where you clicked on the magazine. These coordinates are relative to the magazine, not the whole screen, so keep that in mind.
So, I think you need something like this (at least try it at a starting point):
$('#flipbook').click(function(e) {
var pos = {
x: e.pageX - $(this).offset().left,
y: e.pageY - $(this).offset().top
};
$('#flipbook').zoom('zoomIn', pos);
});
Hope this helps!

To get zoom to work with turn.js, there are three things you need to do:
Setup the proper dom structure, zoom won't work without the "container" div to wrap the flipbook.
<div class="magazine-viewport">
<div class="container">
<div class='magazine'>
<div id='p1'><img src='book_1.jpg'></div>
<div id='p2'><img src='book_2.jpg'></div>
</div>
</div>
</div>
Setup the js events
$( document ).ready(function() {
//Initialize the turn.js flipbook
$('.magazine').turn({
width: 1136,
height:734,
pages:100,
autoCenter: false,
when:{
missing: function (e, pages) {
for (var i = 0; i < pages.length; i++) {
$('.magazine').turn('addPage',page[pages[i]],pages[i]);
}
}
}
});
//Initialize the zoom viewport
$('.magazine-viewport').zoom({
flipbook: $('.magazine')
});
//Binds the single tap event to the zoom function
$('.magazine-viewport').bind('zoom.tap', zoomTo);
//Optional, calls the resize function when the window changes, useful when viewing on tablet or mobile phones
$(window).resize(function() {
resizeViewport();
}).bind('orientationchange', function() {
resizeViewport();
});
//Must be called initially to setup the size
resizeViewport();
}
function page(num){
var elem = $('<div />',{}).html('<div><img src="book_'+num+'.jpg></div>');
return elem;
}
function zoomTo(event) {
setTimeout(function() {
if ($('.magazine-viewport').data().regionClicked) {
$('.magazine-viewport').data().regionClicked = false;
} else {
if ($('.magazine-viewport').zoom('value')==1) {
$('.magazine-viewport').zoom('zoomIn', event);
} else {
$('.magazine-viewport').zoom('zoomOut');
}
}
}, 1);
}
function resizeViewport() {
var width = $(window).width(),
height = $(window).height(),
options = $('.magazine').turn('options');
$('.magazine-viewport').css({
width: width,
height: height
}).zoom('resize');
}
Define proper css styles for the elements, the trick here is that the negative coordinates of the magazine class is compensated by the top & left offsets of the container class.
.magazine-viewport .container{
position:absolute;
top:367px;
left:568px;
width:1136px;
height:734px;
margin:auto;
}
.magazine-viewport .magazine{
width:1136px;
height:734px;
left:-568px;
top:-367px;
}
/* Important: the image size must be set to 100%.
* Otherwise the position of the images would be messed up upon zooming.
*/
.magazine img{
width:100%;
height:100%;
}
That should get it to work, if you want to load a larger version of the image upon zooming, take a look at the loadSmallPage() & loadLargePage() functions in the magazine example.

I had the same problem, but I decided to just use a third party zoom plugin (Jack Moore's jQuery zoom). It turns out the example in the site is a lot more complicated, with a json to create diferent regions and images for each paragraph.
It really depends on what you're using turn.js for, but I think the documentation isn't right, or the software itself is missing something. Either way, I do suggest you look into using some other solution for the problem.

turn.js provides an example with zoom. The difficulty to make it work is to gather all the required files. But if you watch the code, it is possible. Say the root is magazine, it goes two folders up to get lib and extras folders where java scripts are laying. In addition, you have to add the "default" and large pages in the pages folder. When you get the sample, there are only the thumbnails in. Say for 1-thumb.jpg, you have to add 1.jpg and 1-large.jpg
There is a very usefull Firefox plugin to get them : CacheViewer.
I have managed to do it with my book, and reorganize the paths in the code to have something cleaner: put lib and extras at the same level than pages. A recursive grep for "/../../" will give you all the locations in html and js code.

Related

Make scrollspy spy on other tags than headers

Just learning html, css and javascript and got this crazy idea of using the <abbr> tag in my code along with a scrollspy.js (from bootstrap) setup that spy on the viewed paragraphs and displays the definition of the abbreviations/acronym.
As I just learned the fundamental of javascript I want to know if that that possible by the script itself or does it need some modification (if so please post a code example, thx!)
If you look at the source of scrollspy.js you actually don't see any reference to headers. It works by looking at the navigation links and corresponding elements for clues about the relationship between content elements and that navigation. Here is how it looks in the documentation
For nav
#fat
For the section
<h4 id="fat">#fat</h4>
Now one thing to consider, <h4> elements are block level so they take up an entire row. Inline elements can be on the same line, so it might be impossible to see which definition should be highlighted based on the visible section. For what you are trying to do I think you need to create your own bit of JavaScript.
Here is one approach (though it will need some tweaking to work for your exact needs it supports inline abbr elements and even more than one definition per line per line) (and here is a working demo)
Here is the JavaScript:
var mapTerms = function () {
/*grab all of the <abbr>s with terms associated with them, they can move anytime the browser is resized*/
var terms = [];
$('abbr[data-term]').each(function () {
var term = $(this);
terms.push({
term: term.data('term'),
height: term.offset().top,
visible: false,
element: term
});
});
return terms;
},
terms = [],
/*Keep a globally accessible list*/
$body = $('body'); /*need a reference to the body for performance*/
$(window).on('scroll', function () {
/*listen to the scroll event*/
var height = $(document).scrollTop(),
i;
for (i = 0; i < terms.length; i++) {
if (terms[i].visible) {
if (terms[i].height < height || terms[i].height > (height + 50)) {
terms[i].visible = false;
terms[i].element.removeClass('defined');
$('div[data-term=' + terms[i].term + ']').hide();
}
} else {
if (terms[i].height > height && terms[i].height < (height + 50)) {
terms[i].visible = true;
terms[i].element.addClass('defined');
$('div[data-term=' + terms[i].term + ']').show();
}
}
}
}).on('resize', function () {
/*listen to the resize event*/
console.log('mapping...');
terms = mapTerms();
}).trigger('resize').trigger('scroll');
And here is some CSS that hides and highlights the terms and their definitions (as well as keeps the definitions visible):
abbr.defined {
background: red;
}
.definition {
display: none;
}
#definitions {
position: fixed;
}
The way it works is by looking for <abbr> that have a data element that points to a full definition like this:
<abbr data-term='blog' title='Webblog'>blog</abbr>
Each of these points to a div that holds a definition (stuffed in the sidebar at the bottom in the example)
<div class='definition' data-term='blog'>
<h4>Blog</h4>
<p>A blog (a truncation of the expression weblog) is a discussion or informational site published on the World Wide Web and consisting of discrete entries ("posts") typically displayed in reverse chronological order (the most recent post appears first).</p>
<p><i>source <a href='http://en.wikipedia.org/wiki/Blog'>Wikipedia</a></i></p>
</div>
Then as you resize the browser the onResize code builds a map of all of the <abbr> elements are, and as you scroll the onScroll code looks are your current position and tries to figure out if each term is visible (it is using a very simple definition of visible which is within the top 50 pixels of your browser). In production you would probably want to test if it is between the scroll top and the window height, or account for things like the user scrolling down to read more of the definition but pushing the term off the screen. It's a tricky thing to get 100% right, but this should get you further.

Find height of class and apply to another class

I've been looking around the web for an answer for a couple of hours and cannot find anything so I'm hoping someone can help me.
I want to take the height of a wrapper div who's class is movie and apply it to an inner div who's class is movie-center. How can I do this using JS or jQuery?
I am a newbie when it comes to JS, so I would really appreciate if you could lay everything out for me (including any HTML needed).
Thank you!
EDIT 1: Maybe if I am explaining what I am doing people will have a better understanding. I am making a responsive WordPress theme. As the width of the browser is smaller, the movie widths are smaller. I want the overlay title and graphic to stay in the center. I tried doing this with CSS and it cannot be done fully unless I know the exact height (which I won't because of resizing).
EDIT 2: here is the browser's rendered html code:
<article id="movie-97" class="post-97 movie type-movie status-publish hentry"><a href="http://localhost:8888/movies/hard-truth-levity-hope">
<div class="movie-center">
<div class="movie-overlay">
<div class="movie-play"></div>
<h2 class="movie-title">Hard Truth, Levity and Hope</h2>
</div> <!-- end .movie-overlay -->
</div> <!-- end .movie-center -->
<div class="movie-thumb"><img width="480" height="270" src="http://localhost:8888/wp-content/uploads/2014/03/truth-levity-hope.jpg" class="attachment-movie-thumb wp-post-image" alt="Hard Truth, Levity and Hope" /></div>
EDIT 3: Here's a Pastebin for my website. Note: it has been stripped down to only show the essential parts of the site.
What you've done is the correct way. Make sure you've loaded jQuery properly and try to wrap your code inside DOM ready handler $(document).ready(function() {...}); or shorter form $(function() {...});
$(function() {
$('.movie').each(function() {
var h = $(this).height();
$(this).find('.movie-center').height(h);
});
});
Edit: Since you're using Wordpress, there's probably a conflict happen here, try to use:
jQuery(document).ready(function($) {
$('window').resize(function() {
$('.movie').each(function() {
var h = $(this).height();
$(this).find('.movie-center').height(h);
});
}).resize();
});
Please try this :
/* Get height of .movie thumb preview */
jQuery(document).ready(function($) {
$('.movie').each(function() {
var h = $(this).height();
console.log(h);
$(this).find('.movie-center').first().css('height',h);
console.log($(this).find('.movie-center').first().height())
});
});
Connor,
This will get you what you're looking for:
jQuery(document).ready(function($) {
$('.movie').each(function() {
var h = $(this).height();
$(this).find('.movie-center').height(h);
});
});
A quick explanation. You'll notice that jQuery's .height() function is called twice. First, without any params and then with h passed in.
Pull up your JS console (cmd+opt+j if you're using Chrome) to see how this actually works.
The question at the top of this page has an id of #question-header, so if you enter this in the console $('#question-header').height() you'll see that it returns 36. That's because that element is 36 pixels tall.
So, calling .height without any params will return the height of the selected element. But, we can set the height by passing in a number. Try this by pasting this in to the JS console:
$('#question-header').height(1000)
The header is now 1000px tall!
The third line of the code basically says, "Hey, within this particular instance of the .movie article, find the .movie-center element and set the height.
So, there you go. Some working code and hopefully an explanation as to exactly why/how to use it in the future.

enlarge image and move it with the pointer on mouse over

Sorry if this might seem trivial for me to ask but..
I have some images and I need them to enlarge when I hover my mouse over them. But.. I want for the enlarged image to stick next to the pointer as I move it across the image. I don't know what to call it. I'm pretty sure it's only done with javascript, just css won't work here.
Something like this http://www.dynamicdrive.com/style/csslibrary/item/css-popup-image-viewer/ , but you know, it has to move with the pointer in motion.
What's the most effective way to do this?
The previous answers may be exactly what you're looking for, and you may already have this solved. But I note that you didn't mention jquery anywhere in your post and all of those answers dealt with that. So for a pure JS solution...
I'll assume from the way the question was phrased that you already know how to pop the image up? This can be done by coding an absolutely positioned hidden img tag in the html or generated on the fly with JS. The former may be easier if you are a JS novice. In my examples I'll assume you did something similar to the following:
<img src="" id="bigImg" style="position:absolute; display:none; visibility:hidden;">
Then you need an onMouseOver function for your thumbnail. This function must do three things:
1) Load the actual image file into the hidden image
//I'll leave it up to you to get the right image in there.
document.getElementById('bigImg').src = xxxxxxxx;
2) Position the hidden image
//See below for what to put in place of the xxxx's here.
document.getElementById('bigImg').style.top = xxxxxxxx;
document.getElementById('bigImg').style.left = xxxxxxxx;
3) Make the hidden image appear
document.getElementById('bigImg').style.display = 'block';
document.getElementById('bigImg').style.visibility = 'visible';
Then you'll need to capture the onMouseMove event and update the now un-hidden image's position accordingly using the same code you would have used in (2) above to position the image. This would be something like the following:
//Get the mouse position on IE and standards compliant browsers.
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
var curCursorX = e.pageX;
var curCursorY = e.pageY;
} else {
var curCursorX = e.clientX + document.body.scrollLeft;
var curCursorY = e.clientY + document.body.scrollTop;
}
document.getElementById('bigImg').style.top = curCursorY + 1;
document.getElementById('bigImg').style.left = curCursorX + 1;
And that should just about do it. Just add an onMouseOut event to hide the bigImg image again. You can change the "+1" in the last two lines to whatever you like to place the image correctly in relation to the cursor.
Note that all of the code above was for demonstration purposes only; I haven't tested any of it, but it should get you on the right track. You may want to expand upon this idea further by preLoading the larger images. You could also forgoe capturing mousemove events by using setTimeout to update the position every 20 ms or so, though I think that approach is more complicated and less desirable. I only mention it because some developers (including me when I started) have an aversion to JS event handling.
I did something similar to this with a custom ColdFusion tag I wrote that would generate a floating div users could click and drag around the screen. Same principle. If you need me to I can dig that out to answer any additional questions in more depth.
Good luck!
Liece's solution is close, but won't achieve the desired effect of the large image following the cursor.
Here's a solution in jQuery:
$(document).ready(function() {
$("img.small").hover (function () {
$("img.large").show();
}, function () {
$("img.large").hide();
});
$("img.small").mousemove(function(e) {
$("img.large").css("top",e.pageY + 5);
$("img.large").css("left",e.pageX + 5);
});
});
The HTML is:
<img class="small" src="fu.jpg">
<img class="large" src="bar.jpg">
CSS:
img { position: absolute; }
Try this links [jquery with auto positioning]
1.Simple
http://jquery.bassistance.de/tooltip/demo/
2.Good with forum
http://flowplayer.org/tools/tooltip/index.html
if I understood you correctly you want to position your big image relatively to the cursor. One solution in jquery (i'm not 100% sure of the code here but the logic is there):
$('.thumb').hover(function(e){
var relativeX = e.pageX - 100;
var relativeY = e.pageY - 100;
$(.image).css("top", relativeY);
$(.image).css("left", relativeX);
$(.image).show();
}, function(){
$(.image).hide();
})
Jquery is the easiest route. position absolute is key.
^ In addition to the above, here is a working JS Fiddle. Visit: jsfiddle.net/hdwZ8/1/
It has been roughly edited so it isnt using just overall IMG css tags, easy for anyone to use with this now.
I am using this script instead of a Lightbox in my Wordpress client site, a quick zoomed in image with mouse over is much nicer IMO. It is very easy to make efficient galleries especially with AdvancedCustomFields plug-in & in the WP PHP repeater loops!

Flot graph does not render when parent container is hidden

I was having an issue where a flot graph would not render in a tabbed interface because the placeholder divs were children of divs with 'display: none'. The axes would be displayed, but no graph content.
I wrote the javascript function below as a wrapper for the plot function in order to solve this issue. It might be useful for others doing something similar.
function safePlot(placeholderDiv, data, options){
// Move the graph place holder to the hidden loader
// div to render
var parentContainer = placeholderDiv.parent();
$('#graphLoaderDiv').append(placeholderDiv);
// Render the graph
$.plot(placeholderDiv, data, options);
// Move the graph back to it's original parent
// container
parentContainer.append(placeholderDiv);
}
Here is the CSS for the graph loader div which can be placed
anywhere on the page.
#graphLoaderDiv{
visibility: hidden;
position: absolute;
top: 0px;
left: 0px;
width: 500px;
height: 150px;
}
Perhaps this is better solution. It can be used as a drop in replacement for $.plot():
var fplot = function(e,data,options){
var jqParent, jqHidden;
if (e.offsetWidth <=0 || e.offetHeight <=0){
// lets attempt to compensate for an ancestor with display:none
jqParent = $(e).parent();
jqHidden = $("<div style='visibility:hidden'></div>");
$('body').append(jqHidden);
jqHidden.append(e);
}
var plot=$.plot(e,data,options);
// if we moved it above, lets put it back
if (jqParent){
jqParent.append(e);
jqHidden.remove();
}
return plot;
};
Then just take your call to $.plot() and change it to fplot()
The only thing that works without any CSS trick is to load the plot 1 second after like this:
$('#myTab a[href="#tabname"]').on("click", function() {
setTimeout(function() {
$.plot($(divChartArea), data, options);
}, 1000);
});
or for older jquery
$('#myTab a[href="#tabname"]').click (function() {
setTimeout(function() {
$.plot($(divChartArea), data, options);
}, 1000);
});
The above example is applied to Bootstrap tags for Click funtion. But should work for any hidden div or object.
Working example: http://topg.org/server-desteria-factions-levels-classes-tokens-id388539
Just click the "Players" tab and you'll see the above example in action.
This one is a FAQ:
Your #graphLoaderDiv must have a width and height, and unfortunately, invisible divs do not have them. Instead, make it visible, but set its left to -10000px. Then once you are ready to show it, just set it's left to 0px (or whatever).
OK, I understand better now what you're actually saying... I still think your answer is too complicated though. I just tried this out using a tabbed interface where the graph is in a hidden tab when it's loaded. It seems to work fine for me.
http://jsfiddle.net/ryleyb/dB8UZ/
I didn't have the visibility:hidden bit in there, but it didn't seem necessary...
You could also have visibility:hidden set and then change the tabs code to something like this:
$('#tabs').tabs({
show: function(e,ui){
if (ui.index != 2) { return; }
$('#graphLoaderDiv').css('visibility','visible');
}
});
But given the information provided, none of that seems particularly necessary.
I know this is a bit old but you can also try using the Resize plugin for Flot.
http://benalman.com/projects/jquery-resize-plugin/
It is not perfect because you'll sometimes get a flash of the non-sized graph which may be shrunk. Also some formatting and positioning may be off depending on the type of graph that you are using.

Swfobject and MooTools: Dynamic movie height

Greetings.
I am developing an animated homepage for a Flash-HTML hybrid website, and for the sake of standards, my solution is proving difficult. I am not a Javascript pro, so any help is appreciated!
Here is the run-down:
For Flash users, HTML page loads a variable-height AS3 Flash movie that will start at 556 pixels high, and after finishing its animation sequence, tween via Actionscript + JavaScript to 250 pixels high.
To kick off this movie sequence -- (below-left) -- I am attempting to set the initial height of the Flash movie via MooTools, so if users do not have Flash or Javascript enabled, they will see the shorter-height image area with alternative image content and HTML content revealed (below-right).
Element.setStyle sets the height just fine until swfObject runs, at which point the movie collapses since I am not specifying a height via CSS. If users do not have Flash, it defaults to the height of a static image.
So here is my question: Does anyone know how to dynamically pass a height variable to swfobject when it is set up to width/height # 100%? Am I killing myself for no reason trying to work with two page heights?
Image Sequence:
Left - Initial Flash movie with HTML navigation below
Right - Resized movie at the end of the sequence with HTML nav & content below, looks the same as no-Flash version (static image)
alt text http://client.deicreative.com/op/images/twopages.jpg
^^ should land here for users w/o Flash
<script type="text/javascript">
<!--
window.addEvent('domready', function() {
$('flashContent').setStyle('height', 556); // sets height for initial movie
$('homeContent').setStyle('display', 'none'); // hides homepage text + photos below
doSwfObject(); // attempting to start swfObject after setStyle is done
});
function resizePage(h) { // to be called from AS3
var tweenObj = new Fx.Tween('flashContent');
tweenObj.start('height', h);
}
function doSwfObject(){
var flashvars = {};
var params = { scale: "noScale" };
var attributes = { id: "flashContent", name: "flashContent" };
swfobject.embedSWF("swf/homeMovie.swf", "flashContent", "100%", "100%", "9.0.0", false, flashvars, params, attributes);
alert(document.getElementById('flashContent').style.height);
// alerts & shows correct height, but page collapses after hitting 'ok'
}
//-->
</script>
The simplest solution is to embed your SWF in a wrapper DIV. Set the SWF to 100% width/height of the wrapper DIV, then use JS to resize the wrapper DIV, not the <object> itself. Less buggy that way.
Since SWFObject 2 replaces the target DIV with the object, you'll need an additional div in your markup:
<div id="wrapper">
<div id="flashcontent"></div>
</div>
becomes
<div id="wrapper">
<object id="flashcontent" width="100%" height="100%" (etc.) ></object>
</div>
I think the act of posting something on here helps me think through the problem -- after doing so, the answer became more clear. So here is my solution for anyone who stumbles across this later.
To animate the Flash movie's height to its initial, taller state while preserving shorter height for non-Flash users (see images above), I use JavaScript the same way I would to tween the movie's height once sequence is complete. The result resembles a push-down ad on a newspaper website.
In AS3, after preloading is done, I tell Javascript to tween the height of the flash movie container (simplified, obviously -- there is no preloading code):
package {
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.external.ExternalInterface;
public class HomeMovie extends MovieClip {
private var stageHeight:uint;
public function HomeMovie(){
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
stageHeight = 556;
// Tell javascript the stage needs resizing.
if (ExternalInterface.available) {
ExternalInterface.call("resizePage", stageHeight);
}
}
}
}
In JavaScript (via MooTools):
<script type="text/javascript">
<!--
window.addEvent('domready', function() { // hide content on home-page below movie
$('homeContent').setStyle('display', 'none');
});
function resizePage(h) {
var tweenObj = new Fx.Tween('flashContent', {
property:'height',
duration:500,
transition:Fx.Transitions.Quad.easeOut
});
tweenObj.start(h);
}
//-->
</script>
I will probably take it one step further and check for Flash before hiding the home-page content, so that it will not occur if the user has Javascript but not Flash. Again, this is all for the sake of standards.
Have you tryed SWFForceSize? It's an SWFObject addon and it could help you. Even if you don't use it, you could take a look at the source code to see how they do things.
Btw you don't need SWF object when using Mootools as it has a call called Swiff that does everything SWFObject does and then some! :D

Categories

Resources