jqueryjquery-delegate

Using .delegate or .live with if statements (if empty do blah blah blah) on dynamic content


2 fold issue.

I need to hide an element(A) if another element(B) is empty and show A if B has elements within.

And I need to do this on elements loaded dynamically.

So I tried:

$(document).ready(function() {
  if ($('#mapDirections').html().trim()) {
    $('#mapReset').hide();
  }
  else
  {
    $('#mapReset').show();
  }
});

But that didn't work, and I didn't think it would - I've used delegate and live on click events, but not sure how to use them in conjunction with what I want to do.


Solution

  • Hopefully you have control of the JavaScript that is populating #mapDirections. you should implement the callback behavior then, immediately after the data arrives.

    If you don't have that control and the new data is stochastic then you'll need to determine a time interval to poll the node for new content.

    For instance, suppose onNewMapDirections() is called in response to some event in the DOM:

    function onNewMapDirections(newData) {
      $('#mapDirections').html(newData);
      //Add callback here
    }
    

    This could be done easily by binding and triggering custom event handlers on the document:

    //Called when new directions are ready to add to DOM
    function onNewMapDirections(newData) {
      $('#mapDirections').html(newData);
      $(document).trigger('checkMapDirections');
    }
    
    //Called in response to dispatched event
    function onMapDirectionsUpdated(evt) {
      if ($('#mapDirections').html().trim()) $('#mapReset').hide();
      else  $('#mapReset').show();
    }
    
    //Binds event
    $(document).ready(function() {
      $(document).bind('checkMapDirections', onMapDirectionsUpdated);
    });
    

    If you aren't able to embed the callback as soon as new map data calls in, you can still use the event logic and implement a timer that periodically calls

    $(document).trigger('checkMapDirections');