I have a map application that uses jQuery to show/hide some map controls upon clicking of a button. Now, all the controls are working fine except for one – the pan_zoom control. The html elements for the map controls are added dynamically together with some inline styling:
<div class="pan_zoom" style="display: block; top: 4px">pan zoom button</div>
The pan_zoom control is hidden upon loading of the map with:
$('.pan_zoom').hide();
Upon clicking of the button, a function containing the following line is called:
$('.pan_zoom').toggle();
This function hide the pan_zoom control on the first click. However, it did not show the control on the next click.
I tested the above again, without hiding the pan_zoom control upon initialization. This time, toggling has no effect on the element.
What could be the possible reasons that is preventing the toggle function from working properly?
Note that I did not set any CSS display property for this element and that I can solve this problem by replacing the toggle function with:
if($('.pan_zoom').css('display') == 'block')
{
$('.pan_zoom').hide();
}
else
{
$('.pan_zoom').show();
}
What I am more interested is to find out why toggle() is not working properly.
The click handler is:
$('button[name="expand_map"]').click(toggleMap);
function toggleMap() {
....
$('.pan_zoom, .and_other_controls').toggle();
}
This is a tricky one. I write it down here so that others who came across this will take a hard look at the computed element style. In my case, the computed height and width for the pan_zoom control element turns out to be 0 due to absolute positioning of divs within the control div. This in turn affects how jQuery
toggle()function treat the display of the element.I presume it considers elements with zero width and height to be equivalent to a hidden element and therefore does not hide it. One way to overcome this problem is to use
show()/hide()as described in the question. Another less obvious way, in order to usetoggle(), is to set a value for the width and height. With jQuery, this will be: