Get div height befor the div content is fully loaded - javascript

I've got a button, that when I click executes a js code. Like this.
jQuery( ".button" ).on('click', function(){
var page = jQuery(this).attr('data-href');//Get data-href with permalink.
jQuery('#ajax_div').load(page,
function(){
var newHeight = jQuery('#content_loaded').height()+200;
var el = jQuery('#div_containing_ajax_div_and_content_loaded');
el.css({'height': newHeight + 'px'});
});
});
The first time it loads the page works wrong, but after have the images, etc, in cache it works ok. How can I wait that the content is fully rendered to execute the height calc?
All of this without use delay functions and with out use a plugin. There is a function like $(windows).ready().
I'm using wordpress, and with jquery load() it gets the height before the image is fully render and the height is less than the real height of the content in the div.
Thanks.

You could check that all images added are loaded using following snippet:
jQuery(".button").on('click', function () {
var page = jQuery(this).attr('data-href'); //Get data-href with permalink.
jQuery('#ajax_div').load(page, function () {
var $self = $(this),
$contentImages = $(this).find('img');
$contentImages.one('load', function () {
$(this).addClass('loaded');
if ($self.find('img.loaded').length === $contentImages.length) {
var newHeight = jQuery('#content_loaded').height() + 200;
var el = jQuery('#div_containing_ajax_div_and_content_loaded');
el.css({
'height': newHeight + 'px'
});
}
}).each(function () {
if (this.complete) $(this).triggerHandler('load');
});
});
});

maybe I should say that you have 2 ways to do that .. one I'm not tested it and another I tested it
1st: untested way .promise().done();
jQuery('#ajax_div').load(page).promise().done(function(){
// var newHeight ......
});
2nd: tested way in .load callback function loop through images and check if loaded or not using Image.error(function() {});
$('img').each(function(){
var Image = $(this);
var GetSrc = $(this).attr('src');
Image.error(function() {
// newHeight ......
});
});
DEMO

Related

inconsistent css height for element using jquery

I have a relatively simple jquery function I am using to set the height of one div, based on the parent height.
(function() {
var $window = $(window);
function resize() {
if ($window.width() > 800) {
$(".event-list").each(function() {
var parentHeight = $(this).height();
$(this).children('.text').css("height",parentHeight);
$(this).children('.pattern').css("height",parentHeight);
});
} else {
$(".event-list").each(function() {
$(this).children('.text').css("height", 'auto');
$(this).children('.pattern').css("height", 'auto');
});
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
You can see it working here: http://theadventureschool.com/new-site/events/
On my local computer this works correctly every time, but when I pushed the site live, sometimes the height is the correct value, and sometimes it defaults to 22px.
Any help to resolve this would be greatly appreciated.
Thanks,
Jenny
You should wait for the image to finish loading. If I take the image out and resize the page I get the 22px height. Try adding in a listener on the image load and once the image is done loading then do the initial sizing.
(function() {
var $window = $(window);
$(".event-list img").load(function() {
resize();
});
function resize() {
if ($window.width() > 800) {
$(".event-list").each(function() {
var parentHeight = $(this).height();
$(this).children('.text').css("height",parentHeight);
$(this).children('.pattern').css("height",parentHeight);
});
} else {
$(".event-list").each(function() {
$(this).children('.text').css("height", 'auto');
$(this).children('.pattern').css("height", 'auto');
});
}
}
$window
.resize(resize)
.trigger('resize')
.load(resize);
})(jQuery);
$(document).ready() solve this?
JQuery documentation:
https://learn.jquery.com/using-jquery-core/document-ready/

jQuery css height not applying

For some reason the height is not being set in this piece of code
jQuery(document).ready(function() {
jQuery('#main-content').css({'height': ((jQuery(window).height()))+'px'})
jQuery('#nav-icons a').click(function(){
jQuery('#nav-icons a').removeClass("active-icon");
jQuery(this).addClass( "active-icon" );
var toLoad = jQuery(this).attr('href')+' #main-content';
var toLoadSlider = jQuery(this).attr('href')+' #homepage-slider';
jQuery('#main-content , #homepage-slider').fadeOut(1000, loadContent);
function loadContent() {
jQuery('#homepage-slider').empty().load(toLoadSlider)
jQuery('#main-content').empty().load(toLoad,'',showNewContent())
}
function showNewContent() {
jQuery('#main-content , #homepage-slider').css({'height': ((jQuery(window).height()))+'px'}).hide().fadeIn(2000).removeAttr('id class');
}
return false;
interestingly, the exact same line of code in the showNewContent() does set the height.
The only logical reason for this is that jQuery('#main-content') in your first line is not the actual jQuery object representation of the DOM element of your choice.
You will have to figure that out yourself as to why things turn out this way.
Assuming that you have
<div id="main-content">
... content
</div><!--main-content-->
This should do the trick :
var windowHeight = jQuery(window).height();
jQuery(document).ready(function ($) {
$('#main-content').css({
height: windowHeight
});
// other scripts
}); // ready
JSFIDDLE

jQuery: absolute pathname before hash

I'm currently experiencing some conflict between a hashchange function I have set up and jQuery mobile (used for sliding page transitions).
To demonstrate here's an isolated demo on my server: http://nealfletcher.co.uk/transition/
Click on transition click which slides the relevant page in, as it should and appends the url accordingly: /transition/news.
This is where the problem lies, click on news hash click and this will fire my hashchange function and load in the relevant div, BUT instead of the url being like so: /transition/news/#news-01 the url is being rendered like so /transition/#news-01 which causes problems when navigating to the url.
Is there anyway to force the /news/ to be added before the hash, so I get /transition/news/#news-01 instead of /transition/#news-01?
The relevant jQuery is below, is it at all possible to append /news/ before the hash?
Any suggestions would be greatly appreciated!
jQuery:
$(document).ready(function () {
$(window).hashchange(function () {
var hash = location.hash;
if (hash) {
var element = $('.click-block[data-hook="' + hash.substring(1) + '"]');
if (element) showDetail(element);
}
});
$(document).ready(function () {
$(document).hashchange();
var $container = $('#main-grid, #news-grid');
$(function () {
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.grid-block, .grid-break, .hidden',
animationEngine: 'best-available',
filter: '*:not(.hidden), .grid-block',
masonry: {
columnWidth: 8,
gutterWidth: 25
}
});
});
});
$(".click-block").click(function () {
document.location.hash = $(this).attr('data-hook');
});
});
function showDetail(element) {
var newHeight = $('#post-' + element.attr('data-hook')).height();
$('#post-' + element.attr('data-hook')).removeClass('hidden').addClass('grid-break').delay(300).fadeIn('slow');
newHeight = (Math.floor((newHeight + 10) / 230) + 1) * 230 - 10;
$('#post-' + element.attr('data-hook')).css('height', newHeight);
element.children('.up-arrow').fadeIn('slow');
setTimeout(function () {
$('html, body').animate({
scrollTop: $('#post-' + element.attr('data-hook')).offset().top - 90
}, "slow");
}, 1500);
$('#main-grid').isotope();
$('#news-grid').isotope();
}
Just add the section in your data-hook attribute. So for your news links they will be prefixed by news/ like so data-hook="news/news-01"
Now, I would reccomend you to consider using something like http://backbonejs.org/#Router for what you'r doing. Or atleast take a look at https://github.com/browserstate/history.js/

whats wrong with this code? im trying to change the height of each section to the height of window

whats wrong with this code? im trying to change the height of each section to the height of window.
function setsize()
{
var w=$(window).width();
var h=$(window).height();
var sections = new Array("home","about","skills");
for (var i=0;i<3;i++)
{
var element = document.getElementById(sections[i]);
$(element).height(h);
}
}
$(window).ready(function() {
setsize();
});
$(window).resize(function() {
setsize();
});
here is sample of the markup:
<section id="#home">
<h1>..................</h1>
</header>
Seems like a strange way to do that ?
$(window).on('resize load', function() {
$('#home, #about, #skills').height( $(this).height() );
});
You have to update the variables when the window changes size, i.e. inside the resize function
EDIT:
You'll also need a DOM ready handler, and window.onload isn't always triggered when doing it that way, so just do the same thing on DOM ready, like so :
$(function() {
$('#home, #about, #skills').height( $(window).height() );
$(window).on('resize', function() {
$('#home, #about, #skills').height( $(this).height() );
});
});
FIDDLE

click function does not work when changed to live or on

I have a function that uses ajax to load content throughout one of my sites.
This works all good but at some parts because new content is brought in that has more links I need to make the click function a live click function, but when I do the ajax stops working and it just changes the page as normal ( without ajax )
here is my code
function ajaxLoads(){
var $btn = $('a.ajax-btn');
var $container = $('#load');
var siteTitle = document.title;
//var $artistBG = $('#artist-viewport img');
$btn.click(function(e){
console.log();
e.preventDefault();
$btn.removeClass('selected');
//$artistBG.removeClass('top');
var sourceTarget = $(this).data('page'),
slideWidth = $container.width(),
$this = $(this),
$background = $this.data('background'),
pageUrl=$this.attr('href'),
pageTitle = $this.html();
//$changeTo = $("#artist-viewport img[data-background='"+ $background +"']");
$this.addClass('selected');
//$changeTo.addClass('top');
$container.animate({'right':-slideWidth}, 300, 'easeInExpo');
$container.load(pageUrl+" "+sourceTarget, function(){
subNav();
$("html, body").animate({ scrollTop: 0 }, 500, 'easeInExpo', function(){
$container.animate({'right':0}, 300, 'easeInExpo');
});
var pageContent = $(this).html();
window.history.pushState({"html":pageContent, "pageTitle": pageTitle},"", pageUrl);
//document.title=pageTitle+" :: "+siteTitle;
}); // end load function
}); // end click function
window.onpopstate = function(e){
if(e.state){
$container.css('opacity', 0).html(e.state.html).fadeTo('fast', 1);
document.title=e.state.pageTitle+" :: "+siteTitle;
}
};
}
I have tried changing the $btn.click(function(e) to $btn.live('click', function(e) and to $btn.on('click', function(e)
Add .on on document.
$(document).on('click','a.ajax-btn',function(){ });
try on
$('#load').on('click', '.ajax-btn', function(){
...
});
live is deprecated in jquery 1.8 and removed in 1.9.. so use on()
Give your button a css class and use this
$(document).on("click",".yourcssclass",function(e){});
This will work since by default, most events bubble up from the original event target to the document element.Though this degrades performance, a click event happens infrequently and you might use this as a fix to your problem.Then when you have time ,try to see why using delegates is not working by carefully looking on your page cycle.

Categories

Resources