Search code examples
jquerymenuinternet-explorer-7toggleinternet-explorer-6

Show Hide a div on click issues


I have an image with a class of "actions_image" that when clicked shows a menu. This image with hidden menu appears several times on the same page. I'm having issues with the code below for 2 reasons:

1 - In the Javascript code, the first line is to ensure that if there's already a menu open, this will be closed before the new menu is shown. But when this line is added, then the second line with the toggle command no longer toggles. It only shows the div when you click, but won't hide it when you click again. All the rest of the actions work perfectly, as in the div hides when anything but the image that shows it is clicked

2 - IE 7 is throwing up an error for the 2nd line of javascript because of the use of :hover and won't show the menu at all (grrr...!)

Can anyone help?

Javascript code:

section_actions_menu: function(event){  
    $(".actions_image").next().hide();  
    $(".actions_image:hover").next().toggle();  
    $("body").click(function(e){  
        if(e.target.className !== "actions_image")  
        {  
            $(".actions_image").next().hide();  
        }     
    });                             

}

HTML Code:

<img src="/media/images/spacer.gif" width="31" height="18" alt="Section Actions Menu" title="Section Actions Menu" class="actions_image" onclick="section_actions_menu(event);"/>
<div class="toggle">
    <ul>
        <li><a title="Add">Add</a></li>
        <li><a title="Edit">Edit</a></li>
        <li><a title="Remove">Remove</a></li>
    </ul>
</div>

Any help would be much appreciated.


Solution

  • It turns out someone much cleverer than me also pointed out this method:

    section_actions_menu: function() {
    
        var action_menu = $(".actions_image");
        action_menu.live('click', function(e) {
            var other_action_menus = $(".actions_image").not($(this));
            other_action_menus.next().hide();
            $(this).next().toggle();
    
    });
    

    and together with this:

    $("body").click(function(e) { //hides menu when clicking outside the menu
        if(e.target.className !== "actions_image") {
        $(".actions_image").next().hide();
        }
    });
    

    ... it allows to show and hide the menu when you click on an element with class ".actions_image", hides the menu when you click outside ".actions_image" and hides other menus that might be showing when you click on another element with class ".actions_menu".