Jake Champion Jake Champion - 5 years ago 103
Javascript Question

jQuery .hide() doesn't hide element

When finished parsing the json into the specified span tags I wanted to automatically hide the imperial tags currentimperial and forecastimperial but when I try to do this use



and view the result in chrome and look in the console I see that instead of

style="display: none; "

they actually have

style="display: inline; "

Here is my whole javascript and html on jsBin http://jsbin.com/efaguv/edit#javascript,html

Thanks for any help I recieve.

Answer Source

I think the problem is that you haven't allowed for the fact that your ajax call is asynchronous.

A much simplified example of what's happening:

1 jQuery(document).ready(function($) {
2   $('#warning').remove('#warning');   
3   $.ajax({
4        url: 'http://api.wunderground.com/api/APIKEYREMOVED/geolookup/conditions/forecast/q/51.773079,-1.591353.json',
5        dataType: "jsonp",
6        success: function(parsed_json) {
7           $('#currentimperial').fadeIn(1000).append(+temp_f+ '℉ ');
8        }
9    });
11   $('#celcius').hide();
12   $('#currentimperial').hide();
13   $('#forecastimperial').hide();
14 });
  • line 2 executes
  • line 3 executes to make the ajax request (response will be received at some point in the future)
  • lines 11-13 execute to hide the items
  • line 14: your document ready function completes
  • (eventually) ajax response is received and success handler is called so line 7 executes.

Because (in your full code) the ajax success callback makes the elements visible (using .fadeIn()) the end result is that they are visible.

Can you instead hide the elements within that ajax success callback?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download