Flot graph does not render when parent container is hidden - javascript

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.

Related

Javascript Scroll by one pixel on load of a div

I am using a mixture of jQueryTools overlay (lightbox type thing) and a scroll-bar called Perfect Scrollbar. The problem I have is that when the overlay is loaded the scroll-bar doesn't show until you scroll within that box. I need to be able to make it clearer so that everyone knows it is a scroll-able content box. One way this could be possible is to make the content box scroll up one pixel when the overlay is opened. I have found the following code
$(".scroll-content").load(function() {
window.scrollBy(0,-1);
}
which I have been told should work but no matter what I can't get it to scroll at all.. Is there something i'm doing wrong?
Since you have the scroll bar method bind to an element that is initially in a 'hide' status, in fact .BigSuperBlock .block_overlay is hidden by display:none; in Css, the plugin can not properly calculate the height of the overlay container.
So, when you call the function that show-up the 'overlay' container, you have to call the method on the scroll-content class:
$('.scroll-content').perfectScrollbar('update');
You can find the documentation of this in the author's page.
To make it works, you have to call the plugin 'update' method, again, in the jQueryTools modal function, as a callback.
$(".block_overlay").overlay({
onLoad: function(event) {
$('.scroll-content').perfectScrollbar('update');
// here you update the perfectScrollbar plugin
},
onClose: function(event) {
// other custom code
}
});
Try with this:
jQuery("container").animate({ scrollTop: 50 }, 800);
Give that you want to make clear that there is a scrollbar, you can have it on all the time if you change the perfect-scrollbar.css
.ps-container .ps-scrollbar-x-rail {
...
opacity: 0.6;
}
.ps-container .ps-scrollbar-y-rail {
...
opacity: 0.6;
}

How to get zoom working with turn.js

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.

Complete function before starting next (fadeIn/fadeOut)

UPDATED (see notes at bottom)
I have created an image map and when you hover over a specific section of this image map a description will appear in a designated area (the sidebar) of my website.
Each description is of varying length therefore I have not set any maximum height level for my sidebar area so that the display can grow vertically to accomodate each description.
The problem I am having is that when you rapidly hover over areas of the image map the display produces some weird results; showing blocks up content from another hot spot for a split second in full beneath the newly hovered over area and corresponding description (hope that makes sense)
Is there anyway to complete one function in full before displaying the next to avoid this nasty display/animation?
Here is my code:
$(document).ready(function() {
$("#a-hover").hide();
$("#a").hover(function() {
$("#a-hover").fadeIn();
}).mouseleave(function() {
$("#a-hover").fadeOut();
});
$("#b-hover").hide();
$("#b").hover(function() {
$("#b-hover").fadeIn();
}).mouseleave(function() {
$("#b-hover").fadeOut();
});
$("#c-hover").hide();
$("#c").hover(function() {
$("#c-hover").fadeIn();
}).mouseleave(function() {
$("#c-hover").fadeOut();
});
And my CSS;
#a-hover,#b-hover,#c-hover {
z-index: 2;
float: left;
position: relative;
}
#a-hover,#b-hover,#c-hover,{
position: relative;
top: 0px;
left: 0px;
z-index: 1;
width:326px;
min-height:603px;
background-color:#dedddd;
}
I have shortened my code for readability (I have 9 image map hot spots)
I am a novice when it comes to jQuery but I am making a committment to learn so please go easy as my code may not be up to scratch!
I have tried to solve this myself before posting here, but I am out of my depth and need some expert advice
I appreciate any responses.
Thank You,
Wp.
UPDTAE: I tried the majority of what was provided here as answers and whilst I believe these answers are on the right track I couldn't get the problem to stop however I did notice improvement in the animations overall.
I ended up using a combination .stop(true,true); and **resize font automatically.
**Ultimately not getting the desired result is due to my lack of polish with jQuery but being in a rush I managed to find another way to handle this issue (auto resizable font).****
Thanks to all who took the time out to answer and for those reading this for a similar solution at least know the .stop(true,true); properties did in fact work for me to solve one part of this problem.
Try adding .stop before each fadeIn and fadeOut. You should pass true, true to stop to complete the animating instantly rather than leave it half faded in:
$("#a").hover(function() {
$("#a-hover").stop(true, true).fadeIn();
}).mouseleave(function() {
$("#a-hover").stop(true, true).fadeOut();
});
You can also get rid of all of the repetition by binding on a class instead of id's:
$(".imageMapElement").hover(function() {
$("#" + $(this).attr("id") + "-hover").stop(true, true).fadeIn();
}).mouseleave(function() {
$("#" + $(this).attr("id") + "-hover").stop(true, true).fadeOut();
});
May be you can try Jquery Hover Intent plugin.
try stopping the other functions:
$("#a").hover(function() {
$("#b-hover").stop().hide();
$("#c-hover").stop().hide();
$("#a-hover").fadeIn();
}).mouseleave(function() {
$("#a-hover").fadeOut();
});
Try adding .stop() before each .fadeIn and .fadeOut -- that will cancel any previous animations and immediately begin your new one.
You also have a problem with using .hover() -- that actually encapsulates two actions, mouseover and mouseout. When you assign two functions to it, the first is mouseover and the second is mouseout, but when you assign only one function to it, that one function is used for both mouseover and mouseout. So, in effect, your code is causing the element to fadeIn and fadeOut on mouseout.
Incidentally, you can shorten your code a lot using standard jQuery techniques:
$("#a-hover,#b-hover,#c-hover").hide().hover(function() {
$(this).stop().fadeIn();
}, function() {
$(this).stop().fadeOut();
});
...or even better yet, assign a class to each of those three IDs and select it instead.
You have to chain all the jQuery function calls!

JQuery Progress Bar Inline Text

I am trying to use the basic progress bar however I am unable to figure out the css/command to actually put some text inside the bar. I am using this progress bar: http://docs.jquery.com/UI/Progressbar however I am open to other ones if they are just as simple to implement.
I want it to display in the left corner some static information and then a percentage of complete somewhere in the right section. All css I attempted to do just made the information display below or to the side of. As well I am unsure how to actually have this CSS change based on a JQuery method (new to JQuery).
below is my actual JQuery. Don't try to understand the url value just assume it returns 0-100.
<script type="text/javascript">
var url = "%%$protocol_url%%/bin/task_status?id=%%$tid%%&cmd=percent_done";
$(function() {
var progress = 0;
//alert("some value" + value, value);
$("#progressbar").progressbar({ progress: 0 });
setTimeout(updateProgress, 500);
});
function updateProgress() {
var progress;
$.get(url, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar")
.progressbar("option", "value", data);
setTimeout(updateProgress, 500);
} else {
$("#progressbar")
.progressbar("option", "value", 100);
}
});
}
Thanks
I'm not familiar with the plugin, but with CSS you can just position the div with lettering over the progress bar. I'm not sure if it would work with nested divs,since the inner div may get erased when the content for the progress bar is rendered.
You can play around with the top and left positions to position the text exactly where you want. In face you can dynamically change left, so that the text moves with the bar, though this may be a little trickier.
Z-index should not be a problem, but if you want to change the order of the divs, you might have to make sure that the text has a greater z-index than the bar.
The CSS:
#bardivs {
width:400px; /* or whatever the of the porgress bar is */
/*
The position of #bardivs must be something other than
static (the default) so that its children will be positioned
relative to it.
*/
position:relative;
}
#progresstext {
position:absolute;
top:0;
left:0;
}
The HTML:
<div id="bardivs">
<div id="progressbar"></div>
<div id="progresstext"></div>
</div>
The JS:
$("#progressbar").progressbar("option", "value", data);
$("#progresstext").html("<p>Hard code or string here<p>");
I've improved upon an already developed progressbar concept that is simply jquery and CSS based (but not using jquery-ui).
If you like you can look at the following link for having its details:
http://progressbar-simple.blogspot.com/
Hope that helps.

Find the "potential" width of a hidden element

I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.
Is the solution to show it, grab the width, then hide again? There must be a better way...
The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.
Otherwise, yes, show-measure-hide does work.
The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.
For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.
You can use the following function to get the outer width of an element that is inside a hidden container.
$.fn.getHiddenOffsetWidth = function () {
// save a reference to a cloned element that can be measured
var $hiddenElement = $(this).clone().appendTo('body');
// calculate the width of the clone
var width = $hiddenElement.outerWidth();
// remove the clone from the DOM
$hiddenElement.remove();
return width;
};
You can change .outerWidth() to .offsetWidth() for your situation.
The function first clones the element, copying it to a place where it will be visible. It then retrieves the offset width and finally removes the clone. The following snippet illustrates a situation where this function would be perfect:
<style>
.container-inner {
display: none;
}
.measure-me {
width: 120px;
}
</style>
<div class="container-outer">
<div class="container-inner">
<div class="measure-me"></div>
</div>
</div>
Please be aware that if there is CSS applied to the element that changes the width of the element that won't be applied if it's a direct descendant of body, then this method won't work. So something like this will mean that the function doesn't work:
.container-outer .measure-me {
width: 100px;
}
You'll either need to:
change the specificity of the CSS selector ie. .measure-me { width: 100px; }
change the appendTo() to add the clone to a place where your CSS will also be applied to the clone. Ensure that where ever you do put it, that the element will be visible: .appendTo('.container-outer')
Again, this function assumes that the element is only hidden because it's inside a hidden container. If the element itself is display:none, you can simply add some code to make the clone visible before you retrieve it's offset width. Something like this:
$.fn.getHiddenOffsetWidth = function () {
var hiddenElement $(this)
width = 0;
// make the element measurable
hiddenElement.show();
// calculate the width of the element
width = hiddenElement.outerWidth();
// hide the element again
hiddenElement.hide();
return width;
}
This would work in a situation like this:
<style>
.measure-me {
display: none;
width: 120px;
}
</style>
<div class="container">
<div class="measure-me"></div>
</div>
Two options:
position the element outside the viewport (ex: left:-10000px)
use visibility: hidden or opacity: 0 instead of hide().
Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...
Actual jQuery plugin!
Usage:
console.log('width without actual: ' + $('#hidden').width());
console.log('width with actual: ' + $('#hidden').actual('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<div style="width: 100px; display: none;">
<div id="hidden"></div>
</div>
If you know the element to be the full width of a parent element another approach is to create a recursive method:
es5:
var getWidth;
getWidth = function($el){
return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));
es6:
let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)
const width = getWidth(document.getElementById('the-element'))
What I did was ;
by the time hiding that element, stored its width in its dataset.
It only will work for you if you can hide programmatically.
ie.
When Hiding ;
var elem = $("selectorOfElement");
elem.dataset.orgWidth = elem.clientWidth;
Later when getting ;
var elem = $("selectorOfElement");
var originalWidthWas = elem.dataset.orgWidth;
thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.
Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.
var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
var width = parseInt($hiddenElement.outerWidth());
$hiddenElement.remove();
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value)
Grab the element:
let yourEle = document.getElementById('this-ele-id');
and use the function:
getComputedStyle(yourEle).width
This returns a string so you will have to remove the numbers from the string.
This works even when the element's display style is set to none.
Other articles to read about this includes here at zellwk.com

Categories

Resources