0

I have code that does this:

$('.attachment-medium').each(function(){
$(this).click(function(){
    var gallWidth = $('.gallery').width();
    $('.gall-output').toggle().css('width', gallWidth);
    var url = $(this).attr('src').slice(0,-12) + '.jpg';
    $('.gall-output-img').html('<img class="img-responsive" src="' + url + ' "/>');
    var imgMeta = $(this).parent().next().html();
    $('#gall-output-meta').html(imgMeta);
});
});

This generates a modal overlay and displays an img withing a div with class .gall-output. I've created a small <p class="gall-close">close</p> to hide() the .gall-output but it doesn't seem to be working with this code:

$('.gall-close').click(function() {
    $('.gall-output').hide();
});

Is there a way of using this .gall-close to hide or toggle .gall-output?

Thanks for your help.

2
  • can you share the html sample Commented Oct 5, 2014 at 8:55
  • We will need to see your HTML. More than likely this is happening because JQuery cannot traverse to the .gall-output element based on your click. Commented Oct 5, 2014 at 9:07

1 Answer 1

1

In case the .gall-close is added later and not in the dom when the page is loaded, you can attach the click-event using event-delegation:

$(document).on("click", ".gall-close", function(){
    $('.gall-output').hide();
});

Instead of $(document) any static parent element can work as container element to delegate the event. In case this solves your issue, you can check https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.