Detecting div height on resize - javascript

I am trying to detect the height of a div that I am loading content into. This div does not have a specified height, as I am loading pages into it and they themselves fill up the div in different amounts. I think the code I am using is not working.
The #content div is getting the correct height on document load, however I cannot get the height when the load event is clicked.
html:
<div id="select">
<div id="menu">
<ul>
<li><a class="load" href="javascript:void(0)" id="p1">P1</a></li>
<li><a class="load" href="javascript:void(0)" id="p2">P2</a></li>
</ul>
</div>
<div id="spacer"></div>
<div id="content"></div>
css:
#content {
left: 227px;
top: 20px;
width: 703px;
padding: 0 0 100px 0;
position: absolute;
}
#spacer {
border-right: 2px solid #000000;
left: 10px;
position: absolute;
top: 710px;
width: 215px;
}
my jquery:
$(document).ready(function() {
//Load Initial Content
$("#content").html('<ul><li>Loading Content...</li></ul>')
.load("/content/" + "projects.php", null, function() {
contentHeight = $("#content").height();
selectHeight = $("#select").height();
$("#content").height(contentHeight);
$("#select").height(selectHeight);
$("#spacer").height((contentHeight - selectHeight - 40) + "px")
.css({"top": selectHeight + 40 + "px" });
});
//Load content on click function
$(".load").click(function(){
loadName = $(this).attr("id");
$("#content").html('<ul><li>Loading Content...</li></ul>')
.load("/content/" + loadName + ".php", null, function(){
contentHeight = $("#content").height();
selectHeight = $("#select").height();
$("#spacer").height(0);
if(selectHeight > contentHeight) {
$("#spacer").css({"display": "none"});
}else{
$("#spacer").css({"top": selectHeight + 40 + "px", "display": "block" })
.height((contentHeight - selectHeight - 40) + "px");
return false;
}
});
});
});
I am getting this in firebug on load:
<div id="select" style="height: 689px;"/>
<div id="spacer" style="height: 5461px; top: 729px;"/>
<div id="content" style="height: 6190px;"/>
Now if I click on say P2, the div with content height stays the same, even though the actual content inside the div is only 625px tall; so it is not getting switched.

Unless JQuery is being super clever (and it is clever but I don't think its this clever) you aren't getting a resize event because firefox (and probably Safari) only support the resize event on the window object. IE does support the resize event on elements such as a DIV.
Hence you need a different approach:-
$(document).ready(function()
{
$("#content").html('<ul><li>Loading Content...</li></ul>')
.load("/content/" + "projects.php", null, function()
{
window.setTimeout(content_loaded, 0);
});
function content_loaded()
{
$("#content").css({"height": $("#content").height() + "px"});
}
$("#spacer").css({"height": $("#content").height() + "px"});
$(".load").click(function()
{
loadName = $(this).attr("id");
$("#content").html('<ul><li>Loading Content...</li></ul>')
.load("/content/" + loadName + ".php", null, function()
{
window.setTimeout(content_loaded, 0); });
});
$("#spacer").css({"height": $("#content").height + "px"});
});
});
Note I use the setTimeout method here because IE often lags when sorting out width and height parameters when content has changed. By using setTimeout it lets IE sort things out before the height and width properties are accessed. You could choose to remove it and pass content_loaded directly as the callback parameter to the load method.

//Get Content size after load
$("#content").bind("resize", function(){
$("#content").css({"height": $("#content").height()});
});
you're not adding the "px" to the end of the height value
//Get Content size after load
$("#content").bind("resize", function(){
$("#content").css({"height": $("#content").height() + "px"});
});
EDIT follows
got it working locally, you were missing parenthesis at the end of the height function in the click event:
$("#spacer").css({"height": $("#content").height() + "px"}); //added parenthesis enables the #spacer div to change height accordingly
hope this helps

I like to use offsetheight to detect height when one is not set.

Related

Increasing div's width doesn't work as expected

What I would like to achieve is when scrolling to the end of row(right arrow) then to have selection div stop on the last element. Before I was adding few dummy cells and it worked. But now I decided to just increase width of row div by some amount.
if(!rows[currentRowIndex].reachedEnd)
{
console.log("increasing ");
$("#row" + currentRowIndex).width("+=210");
rows[currentRowIndex].reachedEnd = true;
}
This doesn't work for some reason. I even tried to increase by some bigger number but it jumps to some unexpected location, which means I don't understand well what is going on with div after width is changed.
Working copy(resize window to show 2 cells in the client area) https://jsfiddle.net/souren/98rddfzp/3/
UPD1:
I even tried:
$("#row" + currentRowIndex).width($("#row" + currentRowIndex).width() + 210);
with same result.
jQuery's width takes the actual width as parameter and does not evaluate expressions. You have to do so yourself.
Here's an working example:
$(function () {
var $div = $('#myDiv')
$('#increase').on('click', function () {
$div.width($div.width() + 250)
})
})
#myDiv {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"></div>
<button id="increase">Increase</div>
Try to follow this example, this will solve your problem::
HTML
<div class="testDiv" style="background-color: grey; width: 100px;">Rana</div>
jQuery
<script type="text/javascript">
$(document).ready(function () {
$('button').on('click', function(){
$(".testDiv").width($(".testDiv").width() + 210);
});
});
</script>

onclick event not working with position:fixed

when i uses position:fixed the div's onclick event is not working. and this event is working with other values like static,relative etc.
My code is like below:
css:
#dialog_window_minimized_container {
position: fixed;
bottom: 0px;
left: 0px;
}
JavaScript:
<script>
var _init = $.ui.dialog.prototype._init;
$.ui.dialog.prototype._init = function() {
//Run the original initialization code
_init.apply(this, arguments);
//set some variables for use later
var dialog_element = this;
var dialog_id = this.uiDialogTitlebar.next().attr('id');
//append our minimize icon
this.uiDialogTitlebar.append('<a href="#" id="' + dialog_id +
'-minbutton" class="ui-dialog-titlebar-minimize ui-corner-all">'+
'<span class="ui-icon ui-icon-minusthick"></span></a>');
$('#dialog_window_minimized_container').append(
'<div class="dialog_window_minimized ui-widget ui-state-default ui-corner-all" id="' +
dialog_id + '_minimized">' + this.uiDialogTitlebar.find('.ui-dialog-title').text() +
'<span class="ui-icon ui-icon-newwin"></div>');
$('#' + dialog_id + '-minbutton').hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
}).click(function() {
dialog_element.close();
$('#' + dialog_id + '_minimized').show();
});
$('#' + dialog_id + '_minimized').click(function() {
$('#' + dialog_id + '_minimized').hide();
dialog_element.open();
});
};
</script>
jsp:
check if some other div or element is coming over it when you keep your element position as fixed, that's the first thing I would check for do a right click and inspect element on the position where you are clicking if you see some other element or div highlighted in the bar which shows up below then, some other div or element is covering your element.
Hope it helps
Try to give higher z-index value for the particular div and check . Might be other div covering over your position: fixed DIV
I had this problem. My element, which I added click and mouseover events, was not clickable. My element was inside a container div which was position: fixed and was positioned top: 400px;
<div class="container" style="position: fixed; top: 400px">
<div class="my-element">I have mouse events</div>
</div>
I found when I removed the top positioning my element's mouse events started working. For some reason the fixed positioning of the parent div was not "lining up" with the hit area of my element, if that makes sense. My solution was to take my element out of the fixed positioned container and to position it on it's own.
<div class="my-element" style="position: fixed; top: 400px">I have mouse events</div>
Hope this helps.

how to remove space at the bottom for dynamic contents?

I am designing a page where bottom part of a div should touch the end of the page that is no bottom margin or padding so I put height of the main div as
$(function() {
$('.divMain').css({'height': (($(window).height())) + 'px'});
$(window).resize(function() {
$('.divMain').css({'height': (($(window).height())) + 'px'});
});
});
My HTML is :
<div class="divMain">
<table id="eduGrid"></table>
</div>
where "eduGrid" is generated dynamically(Bootstrap).
Initially its work fine but I have some contents in that div that can be added at the user end(add new education etc) so that contents are moving outside the main div and its looking wired.
Check this for full screen result - http://fiddle.jshell.net/DRRsn/1/show/light/
Check this for fiddle code - http://jsfiddle.net/DRRsn/1/
CSS
html,body{width:100%;height:100%; overflow:hidden; margin:0;padding:0;}
div{background:blue;}
table{background:pink;height:100%;;width:50%}
HTML
<div class="divMain">
<table id="eduGrid"></table>
</div>
JS
$(function() {
$('.divMain').css({'height': (($(window).height())) + 'px'});
$(window).resize(function() {
$('.divMain').css({'height': (($(window).height())) + 'px'});
});
});
Hope this is what u were looking for.
Apologies if this isn't what you're looking for - I think it is? - but if you wish the 'divMain' to take 100% of the browser window's width & height, you can do this with CSS - simply by making it a position:absolute <div>
.divMain {
position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: auto;
}
So by default it will have 100% height, but if the <table> content is higher than the page, divMain will stretch out.
(Tested on Chrome)
Thanks guys but I have found a solution for this problem..I have changed my function body as :
$(function() {
$('.divMain').css({'min-height': (($(window).height()) - 70) + 'px'});
$(window).resize(function() {
$('.divMain').css({'min-height': (($(window).height()) - 70) + 'px'});
});
});
So now initially main div have minimum height as browser height and when content of main div got increased then height of main div will also increase.

Change margin-top position of an fixed positioned element after reaching the bottom of the page?

I need to change top-margin of an fixed div element from margin-top: 200px to margin top 0px after reaching the bottom of the page (or 200px from bottom) using vertical scrollbar.
And toggle return back if scrolling back to the top.
I guess some javascript/jQuery code code do that.
my html/layout code:
<div id="header" style="position: fixed; margin-top: 0px;">
Header content
</div>
<div id="main">
<div id="left" style="position: fixed; margin-top: 200px;">Google Ads here</div>
<div id="right">Content posts here</div>
</div>
<div id="footer">
Footer content
</div>
EDIT: Here are some images to make my question more clear.
normal state when you load the page:
problem when you scroll down, and the google ads column is in conflict with footer:
how it needs to be solved:
Derfder...
Voila, my proposed solution:
http://jsfiddle.net/YL7Jc/2/
The animation's a tad jerky, but I think it does what you want
(It's my take on an earlier s/o post:
Can I keep a DIV always on the screen, but not always in a fixed position? )
Let me know what you think!
Try below code which binds an event to window.scroll to check if the page hits the bottom (bottom in 200px) and moves the #left to top (margin-top: 0)..
DEMO: http://jsfiddle.net/6Q6XY/4/ ( added some demo code to see when it hits the bottom.)
$(function() {
var $left = $('#left');
$(window).bind('scroll', function() {
if (($(document).height()
- (window.pageYOffset + window.innerHeight)) < 200) {
$left.css('marginTop', 0);
} else {
$left.css('marginTop', 200);
}
});
});
Reference: https://stackoverflow.com/a/6148937/297641
You need to implement the window scroll function, this is a jquery implementation so please ensure you include the latest jquery libaries
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
//if it hits bottom
$('#left').css("margin-top", "0px");
}
else {
$('#left').css("margin-top", "200px");
}
});
HTML
<div id="main" style="width: 960px; margin: 0px auto;">
<div id="left" style="position: fixed; top: 200px; left: 0px; background: #000; width: 100%; color: #fff;">Google Ads here</div>
<div id="right"></div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var left = $('#left');
var leftTopPosition = $('#left').css('top');
leftTopPosition = parseInt(leftTopPosition.substring(0, leftTopPosition.length-2));
$(window).scroll(function(){
var pageOffsetY = window.pageYOffset;
if((documentHeight - pageOffsetY - windowHeight) <= 200 && leftTopPosition == 200) {
left.stop().animate({
'top': '0px'
});
leftTopPosition = 0;
}
else if((documentHeight - pageOffsetY - windowHeight) > 200 && leftTopPosition == 0) {
left.stop().animate({
'top': '200px'
});
leftTopPosition = 200;
}
});
});
</script>
Hi Firstly you should have been more clearer in the first place before marking people down, as everyone give similar answers then it shows the question was not clear.
See Js Fiddle for a potential fix, please tweak as you need it with the pixels etc
for this problem you should use z-index in css
Try somethins like this
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
document.getElementById(yourid).setAttribute("style","margin-top:0px");
}
Try this:
$(window).bind('scroll', function(){
if(($(window).height()-$(window).scrollTop())<200)
{
$('#left').css('margin-top',$(window).scrollTop());
}
else
{
$('#left').css('margin-top',200);
}
});

How to make Jquery UI Tabs scroll horizontally if there are too many tabs

Now the image above is an example of " too many tabs ", It appears as multiple line by default.
But I want to make it in a single line and horizontally scrollable, either adding two arrows before the beginning tab and after the last tab, or scroll automatically are OK.
I have a different approach to this issue, as I think a scroll for the tabs is counter-intuitive. I created a plugin to do a dropdown when the tabs break to a second line.
https://github.com/jasonday/plusTabs
I was recently looking for a solution to this but none of the other plugins / examples seemed to work with jQuery 1.9+, I also think that Jason's answer of creating a 'more' tab and displaying any extra tabs as a drop down provides the best UI experience, and so I expanded on his answer and created a jQuery plugin for 1.9+ that extends jQuery UI tabs, if the total width of all of the tabs exceeds the width of the tabs container then the additional tabs are grouped together in a dropdown.
You can see the JSFiddle Demo to see it in action. Try resizing your browser window to see it working.
Or you can view the full plugin code at JSFiddle.
Initialising 'Overflow Tabs' is as simple as this:
$("#tabs").tabs({
overflowTabs: true,
tabPadding: 23,
containerPadding: 40,
dropdownSize: 50
});
tabPadding is the number of pixels of padding around the text in a tab.
containerPadding is the padding of the container.
dropdownSize is the pixel size of the dropdown selector button
I have tested this on the latest versions of Chrome, Firefox, and IE. If you spot any issues or can improve this then feel free to fork it and go ahead.
Now also available on GitHub.
None of the plugins listed here quite worked for me (most are outdated and not compatible with jQuery 2.0+) but I eventually found this:
https://github.com/joshreed/jQuery-ScrollTabs
...worth adding to the list.
I've just made a very simple plugin for this. Basically you have to add one fixed length div and a moveable one to the tab navigator.
Plugin code:
(function ($) {
var settings = {
barheight: 38
}
$.fn.scrollabletab = function (options) {
var ops = $.extend(settings, options);
var ul = this.children('ul').first();
var ulHtmlOld = ul.html();
var tabBarWidth = $(this).width()-60;
ul.wrapInner('<div class="fixedContainer" style="height: ' + ops.barheight + 'px; width: ' + tabBarWidth + 'px; overflow: hidden; float: left;"><div class="moveableContainer" style="height: ' + ops.barheight + 'px; width: 5000px; position: relative; left: 0px;"></div></div>');
ul.append('<div style="width: 20px; float: left; height: ' + (ops.barheight - 2) + 'px; margin-left: 5px; margin-right: 0;"></div>');
var leftArrow = ul.children().last();
leftArrow.button({ icons: { secondary: "ui-icon ui-icon-carat-1-w" } });
leftArrow.children('.ui-icon-carat-1-w').first().css('left', '2px');
ul.append('<div style="width: 20px; float: left; height: ' + (ops.barheight - 2) + 'px; margin-left: 1px; margin-right: 0;"></div>');
var rightArrow = ul.children().last();
rightArrow.button({ icons: { secondary: "ui-icon ui-icon-carat-1-e" } });
rightArrow.children('.ui-icon-carat-1-e').first().css('left', '2px');
var moveable = ul.find('.moveableContainer').first();
leftArrow.click(function () {
var offset = tabBarWidth / 6;
var currentPosition = moveable.css('left').replace('px', '') / 1;
if (currentPosition + offset >= 0) {
moveable.stop().animate({ left: '0' }, 'slow');
}
else {
moveable.stop().animate({ left: currentPosition + offset + 'px' }, 'slow');
}
});
rightArrow.click(function () {
var offset = tabBarWidth / 6;
var currentPosition = moveable.css('left').replace('px', '') / 1;
var tabsRealWidth = 0;
ul.find('li').each(function (index, element) {
tabsRealWidth += $(element).width();
tabsRealWidth += ($(element).css('margin-right').replace('px', '') / 1);
});
tabsRealWidth *= -1;
if (currentPosition - tabBarWidth > tabsRealWidth) {
moveable.stop().animate({ left: currentPosition - offset + 'px' }, 'slow');
}
});
return this;
}; })(jQuery);
Check it out at http://jsfiddle.net/Bua2d/
Here is a plugin for that: http://jquery.aamirafridi.com/jst/
I've also created an jQuery plugin for it here, but my main focus was on creating such structure for mobile sites that have little space and could rely also on scrolling horizontally with touch as well as control arrows.
The solution looks like the following:
I'm using Bootstrap and to implement the plugin you basically need to include:
In you HTML the following structure so the arrows can work correctly (I'm using font-awesome for them)
<div id="js_image_selection" class="horizontal-scrollable-tabs">
<div class="scroller arrow-left"><i class="fa fa-arrow-left"></i></div>
<div class="scroller arrow-right"><i class="fa fa-arrow-right"></i></div>
<div class="horizontal-tabs">
<ul role="tablist" class="nav nav-tabs nav-tabs-horizontal">
<li role="presentation" class="active"><img src="external/images/t-shirt-white.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-orange.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-green.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-white.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-orange.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-green.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-white.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-orange.jpg"/></li>
<li role="presentation"><img src="external/images/t-shirt-green.jpg"/></li>
</ul>
</div>
</div>
And call in you Js:
$("#js_image_selection").horizontalTabs();
Hope it helps anyone in the future!
Cheers!
One plugin can be found here https://github.com/Casper1131/scroller
it can be used for any undordered list.
Re: André Lourenço - Great addon, just wanted to throw in a hack that needs refining that allows the scroller to resize on window resize (ie: rotate mobile device);
if(!$(".fixedContainer").length) {
ul.wrapInner('<div class="fixedContainer" style="height: ' + ops.barheight + 'px; width: ' + tabBarWidth + 'px; overflow: hidden; float: left;"><div class="moveableContainer" style="height: ' + ops.barheight + 'px; width: 5000px; position: relative; left: 0px;"></div></div>');
ul.append('<div class="leftBtn" style="width: 40px; float: left; height: ' + (ops.barheight - 2) + 'px; margin-left: 5px; margin-right: 0;"></div>');
var leftArrow = ul.children().last();
leftArrow.button({ icons: { secondary: "ui-icon ui-icon-carat-1-w" } });
leftArrow.children('.ui-icon-carat-1-w').first().css('text-align', 'center');
ul.append('<div class="rightBtn" style="width: 40px; float: left; height: ' + (ops.barheight - 2) + 'px; margin-left: 1px; margin-right: 0;"></div>');
var rightArrow = ul.children().last();
rightArrow.button({ icons: { secondary: "ui-icon ui-icon-carat-1-e" } });
rightArrow.children('.ui-icon-carat-1-e').first().css('text-align', 'center');
} else {
var leftArrow = $(".leftBtn");
var rightArrow = $(".rightBtn");
$(".fixedContainer").css("width", tabBarWidth);
}
Then I call it again on window resize ie:
$(window).resize(function(e){
$("#tabs").scrollabletab();
});
Not the most efficient way to do it, but it works for my testing purposes at the moment.
I created yet another plugin for this. This time using Chrome style tab-resizing behaviour.
Initialize with
$( ".tabpanel" ).tabs().tabs('overflowResize');
Demo
GitHub
There are multiple scenarios and cases to handle when showing tabs on single line.
Simple solution would be to add a div around the ui-tab-header <ul> and set the overflow as scroll. This method works out of box as the browser handles the scrolling through the tab headers. But the default scrollbar provided by browser will look odd. So you need a customize/stylish scrollbar addon. OR
To use an jQuery UI tabs extension like the below one:
Extended jQuery UI widget that offers scroll-able tab feature and does automatically handle responsive page size changes by showing navigation controls when required.
Features:
It is responsive or fluid layouts
Has support for touch swipe to scroll through tab headers in touch devices (* requires external dependency)
Fully customizable & css based styling
Supports removal of tabs using close button
No extra HTML structure changes required, it automatically enhances the markups on the fly.
https://davidsekar.github.io/jQuery-UI-ScrollTabs

Categories