Skip to content
Advertisement

jQuery get width of ajax loaded elements

I am trying to add a css class to ajax loaded html element. My HTML look like as below:

<h4 class="overflow-text"><span>This is the response from the ajax call.</span></h4> 

This h4 is a fixed width element and span inside h4 may be overflowing. So I need to add a CSS class for h4 if span text is overflowing. Here I am trying this with getting width of these two element and comparing it as below.

var el = $('h4.overflow-text');
el.each(function() {
  var span = $(this).find('span')
  if (span.width() > $(this).width()) {
    $(this).addClass('text-marquee')
    console.log('overflow')
  } else {
    console.log('not overflow')
  }
})

This works for me, if html not load from ajax. But not working on ajax responce. So I tried it on ajax sussess as below. But it also doesn’t work for me.

success: function(res) {
  var $response = $("<div/>").html(res);
  var wp = $response.find('.overflow-text').width();
  var wc = $response.find('.overflow-text').children('span').width();


  console.log(wp,wc)

  $container.fadeOut( 50 , function() {
    jQuery(this).html( res);
  }).fadeIn( 1000 );
},

Doesn’t works mean, wp and wc always giving 0. Any help would be greatly appreciated.

Advertisement

Answer

Checking the width of the element after the content has been added to the DOM should work.

Edit: I saw that the DOM is not updated immediately however waiting for even a millisecond is enough and it gives the desired result.

    $.get("spantext", function(data, status){

          $('.container').fadeOut( 50 , function() {

            jQuery(this).html(data);

            $container = jQuery(this);
            setTimeout(function(){
                var wp = $container.find('.overflow-text').width();
                var wc = $container.find('.overflow-text').children('span').width();
                console.log(wp,wc)
            },1);

          }).fadeIn( 1000 );
    });
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement