JGeer
JGeer

Reputation: 1852

Close div onclick <a> jquery

I use this code to display a div onclick:

;(function($) {
    $(function () {
        $('.m-help .m-text').hide();
        $('.m-help')
            .live('click', function () {
                $(this).find('.m-text').show();
            })
            .live('click', function () {
                $(this).find('.m-link-close-button').hide();
            });
    });
    $(document).bind('m-ajax-after', function (e, selectors) {
        $('.m-help .m-text').hide();
    });

})(jQuery);

And with this HTML:

<div class="m-help">
    <div class="m-text" style="width: 40px;">
        <?php echo $_helpHtml ?>
        <a href="#" class="m-link-close-button"><span>x</span></a>
    </div>
    <a href="#" onclick="return false;" class="details m-link"></a>
</div>

This does work onclick to display the div, but I want to use the X mark inside the div to close the div again. Closing the div does not work.

What am I doing wrong and how can I fix this problem?

Upvotes: 0

Views: 2691

Answers (4)

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

Use click event on a tag to close the div:

function($) {
    $(function () {
        $('.m-help .m-text').hide();
        $('.m-help')
            .live('click', function () {
                $(this).find('.m-text').show();
            });

            $(".m-link-close-button").live('click', function () {
               $(this).closest('.m-text').hide();
            });
    });
    $(document).bind('m-ajax-after', function (e, selectors) {
        $('.m-help .m-text').hide();
    });

})(jQuery);

Upvotes: 0

Tanya Sinha
Tanya Sinha

Reputation: 634

try this: HTML

<div class="m-help">
<div class="m-text" style="width: 40px;">
    <?php echo $_helpHtml ?>
    <a href="#" class="m-link-close-button"><span>x</span></a>
</div>
<a href="#" onclick="return false;" class="details m-link">Click</a>
</div>

JS:

$(".m-text").hide();
   $(".m-link").click(function () {
   $(".m-text").show();
});
   $(".m-link-close-button span").click(function () {
   $(".m-text").hide();
});

Working fiddle:http://jsfiddle.net/cncf5Lz9/

Upvotes: 0

Miguel
Miguel

Reputation: 20633

Event delegation

$('.m-help').on('click', function (event) {
    var close = $(event.target).closest('.m-link-close-button').length;
    $(this).find('.m-text')[close ? 'hide' : 'show']();
});

http://jsfiddle.net/moogs/9e47j19L/1/

Upvotes: 1

you can get the parent of your close button with parent() so you can do it this way :

(function($){
   $('.m-help .m-text').hide();
   $('.m-help').live('click', function(ev) {
       $(this).find('.m-text').show();
   });
   $(".m-link-close-button").live('click', function (ev) {
           $(this).parent().hide();
   });
})(jQuery)

Upvotes: 0

Related Questions