0

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.

animuson
  • 53,861
  • 28
  • 137
  • 147
Jason
  • 7,612
  • 14
  • 77
  • 127
  • That won't work with dynamic HTML because the elements you're looking for don't exist for the selectors to find when you are applying this function. – Tetsujin no Oni Jan 24 '12 at 19:49
  • @TetsujinnoOni - ok, the element #mapDirections exists - but is empty. As elements are appended to it, I want other elements to show and if it's empty, I want to hide elements – Jason Jan 24 '12 at 19:52
  • 3
    Is your code responsible for adding to it? If so, why not add the appropriate code at that point? – Jeff B Jan 24 '12 at 19:54
  • per @JeffB, move your show/hide code to where you are appending error messages. Or wrap it in a function and call the function after you append to #mapDirections. – Brent Anderson Jan 24 '12 at 20:21

1 Answers1

0

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');
Ross Smith
  • 747
  • 4
  • 5