jQuery heigth() function problem

Hello guys,

please see http://codepen.io/Fajer39/pen/vOOpXq?editors=001 

$('#show').on('click', function(e) {
    e.preventDefault;
    showParagraphs();
   	
    var pHeight = $('.paragraphs').height();
    console.log(pHeight);
    $('lionContainer').height(pHeight);
    
  });

Open in new window


var pHeight = $('.paragraphs').height(); doesn't work as expected.

First paragraphs are hidden and showParagraphs(); make them visible but I guess I need some callback function to wait when showParagraphs(); is done but I'm not that skilled in jQuery yet so how would you do it?

The goal is to have a lionContainer's heigh based on paragraphs's height. When you see the codepen you'll get the idea
LVL 1
Fajer39Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David S.Commented:
You could simply use setTimeout() for this. Alternatively you could change your showParagraphs function to accept a callback function to pass on as the callback for slideDown: http://api.jquery.com/slideDown/

$('#show').on('click', function(e) {
	e.preventDefault;
	showParagraphs();

	setTimeout(function(){
		var pHeight = $('.paragraphs').height();
		console.log(pHeight);
		$('lionContainer').height(pHeight);
	},1000);
});

Open in new window

RobOwner (Aidellio)Commented:
Create your own callback for showParagraphs, I've used __cb:

function showParagraphs(__cb) {
  $('.lorem').hide();
  var numberShow = $('#numberShow').val();
  
  if(numberShow > 0 && numberShow <= $('.lorem').length) {
    for(i=0; i < numberShow; i++) {
      $('.lorem').eq(i).slideDown(1000);
      $('#numberShow').val("");
    }
    $('.info').fadeIn(1500, __cb);
  }
  else {
    alert('zadej prosím počet odstavců v rozmezí 1-4');
    $('#numberShow').val("");
    __cb();
  };
}

Open in new window


Then in your code:

  //zobrazi zvolený počet odstavců  
  $('#show').on('click', function(e) {
    e.preventDefault;
    showParagraphs(function() {
    var pHeight = $('.paragraphs').height();
    console.log(pHeight);
    $('lionContainer').height(pHeight);
      
    });
   	
    
  });

Open in new window


You'll see that the height output is not zero.
Fajer39Author Commented:
Thank You Rob and Kravimir, I used Rob's solution. Height output is correct now but only for first time run. When you type "4" in the input box and then click "zobrazit(which means 'show' in english)" it works but when you try again it doesn't.

I only made changes to click(); function because  I want lion to be hidden first.
$('#show').on('click', function(e) {
    e.preventDefault;
    showParagraphs(function() {
      var pHeight = $('.paragraphs').height() - 31;
    	console.log(pHeight);
    	$('.lion').height(pHeight);
      $('.lion').fadeIn(300);
    });
    
  });

Open in new window


The showParagraphs function is the same as you wrote - please see the codepen again.

Sorry for czech language there but my plan is to make enough pens to actually show employer and get a job/internship. Because of that I also have to understand all of it but problem is I don't really fully get what you did.

So I have following questions:

1.

how to assign lion image exact height without subtraction of margin and padding like this(with number) var pHeight = $('.paragraphs').height() - 31; ?

2.

The height(); works correctly only for the first run

3.

Can you please explain the process of __cb? I understand that it runs after the showParagraphs(); is complete but why you assign it to $('.info').fadeIn(1500, __cb); and else statement too? Why it have to run twice (if i get it right)?
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Fajer39Author Commented:
Ok Rob I understand now, thank You. But what about the #2 point, have you found a solution?
RobOwner (Aidellio)Commented:
Not sure what's going on for you but it works every time for me: http://jsbin.com/yoceji/1/edit?js,console,output
Fajer39Author Commented:
Well, I tested your bin in chrome & firefox win no extensions and I still got wrong values after second click on zobrazit(= show). Please see the image bellow.

problem.png
What could be wrong?
RobOwner (Aidellio)Commented:
Repeated clicks should do nothing so you can ignore that value.  However, I've modified the bin (http://jsbin.com/yoceji/2/edit?js,console,output) to pass a return value to the callback for you to test whether there was an error or not.

//volání funkcí po načtení DOM
$(function() {

  //zobrazi zvolený počet odstavců  
  $('#show').on('click', function(e) {
    e.preventDefault();
    showParagraphs(function(result) {
      if (!result.error) {
        var pHeight = $('.paragraphs').innerHeight() -31;
        console.log(pHeight);
        $('.lion').height(pHeight);
        $('.lion').fadeIn(300);
      }
    });

  });

  //skryje zvolený počet odstavců  
  $('#hide').on('click', function(e) {
    e.preventDefault();
    hideParagraphs();
  });

  //upraví zvoleny odstavec 
  $('#edit').on('click', function(e) {
    e.preventDefault();
    editParagraphs();
  });

  //skryje odstavec po kliku myší  
  $('.lorem').on('click', function() {
    $(this).slideUp(1000);
    clickHideInfo();
  });

});

//funkce pro zobrazení odstavců
function showParagraphs(__cb) {
  $('.lorem').hide();
  var numberShow = $('#numberShow').val();

  if(numberShow > 0 && numberShow <= $('.lorem').length) {
    for(i=0; i < numberShow; i++) {
      $('.lorem').eq(i).slideDown(1000);
    }
    $('#numberShow').val("");
    $('.info').fadeIn(1500, function() {__cb({error: false});});
  }
  else {
    alert('zadej prosím počet odstavců v rozmezí 1-4');
    $('#numberShow').val("");
    __cb({error: true});
  }
}

//funkce pro skrytí odstavců
function hideParagraphs() {
  var numberHide = $('#numberHide').val();
  var existingP = $('.lorem').length - $('.lorem:hidden').length;
  var currentP = $('.lorem:visible').length;

  if (numberHide <= existingP) {
    for(i=0; i < numberHide; i++) {
      $('.lorem:visible').eq(i).slideUp(1000);
      $('#numberHide').val("");
    }
    if (numberHide == currentP) {
      $('.info').fadeOut(1500);
    }
  }
  else {
    alert('můžete skrýt pouze ' + existingP + ' odstavec(ce)');
    $('#numberHide').val("");
  }   
}

//funkce pro editaci odstavců
function editParagraphs() {
  var numberEdit = $('#numberEdit').val() - 1;
  if (numberEdit >= 0 && numberEdit < $('.lorem:visible').length) {
    var editP = $('#editP').val();
    $('.lorem:visible').eq(numberEdit).slideUp(300, function() {
      $(this).slideDown(300).text(editP);
      $('#numberEdit').val('');
      $('#editP').val('');
    });
  }
  else {
    alert('nelze zvolit odstavec, který není zobrazen');
    $('#numberEdit').val('');
  }
}

function clickHideInfo() {
  if ($('.lorem:visible').length == 1) {
    $('.info').fadeOut(1500);
  }
}

Open in new window

Fajer39Author Commented:
Rob I think that you don't know what I am trying to achieve here. I know I don't have it in english so I try to explain it again.

1.

You add value between 1-4 in the first input and then you click zobrazit==show. After that number of paragraphs that you enter should appear and an image with height of the size of paragraphs.

2.

When you repeat the process (add 3[for 3 paragraphs] in the first input e.g.....)...but this time it doesn't work, paragraphs shows but the image doesn't and that's the reason why I ask a question here.
Before I asked here It worked with the image every time, but the height of image was wrong. That fixed your solution but now it only works for the "first input submit"

So please look into that.
RobOwner (Aidellio)Commented:
Sorry - I now understand what you mean.  I've updated it so that the .info is hidden each time before showing it

function showParagraphs(__cb) {
  $('.lorem').hide();
  $('.info').hide();
Fajer39Author Commented:
Oh yes, it works. Thank You very much Rob. So I understand that the function breaked because $('.info').fadeIn(1500, function() {__cb({error: false});}); could not fadeIn what was already showed. Am I right?

I appreciate your effort. It was silly misstake by me.

Last Q- when I try to test it in chrome dev tools(sources) and add some breakpoints, after the finish of the function it tells me warning for infinite loop at line 45-  for(i=0; i < numberShow; i++) . But i don't see why it should be infinite.
RobOwner (Aidellio)Commented:
That's exactly right.  The element had already completed the fade in.

As for the infinite loop, I'm pretty sure that's because .val() returns a string.  You're trying to compare an integer (i) with a string.  Depending on how the comparison is made you may find that i is always less than the numberShow.

Best thing to do is convert the result to an integer like this (and anywhere else you expect a number e.g. numberHide etc):

var numberShow = $('#numberShow').val() * 1;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fajer39Author Commented:
Ok, I see.

Thank You Rob.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.