jQuery, do not select 'Child' from the element

Asked

Viewed 127 times

3

I have this code that makes of a kind of fancybox, it works well but I wish that the click in the image did not make disappear the '#overlayFancy', it was good that only the click out of the image is to make with this disappear everything, although the image is inside the '#overlayFancy' which occupies 100%*100% of the window and the image is in the middle of the window, 500px*500px.

HTML:

<div class="wrapperExtraImg" style="background-image:url(<?php echo 'admin/' .$extraImg->extra_image_path; ?>)"></div>
<div id="overlayFancy"></div>

js: Zoom in

$(document).on('click', '.wrapperExtraImg' ,function(){
        var image = $(this).attr('id');
        $('#overlayFancy').stop().animate({
            "opacity":"1"
        }, 500);
        $( "#overlayFancy" ).append( "<img src="+image+">" );
});

js: Disappear, return to default page

$(document).on('click', '#overlayFancy' ,function(){
        $('#overlayFancy').stop().animate({
            "opacity":"0",
        }, 300);
        $('#overlayFancy').children('img').remove();
    });
  • Tried to put the image in a new Div inside the #overlayFancy. Type la in the append would be $( "#overlayFancy" ).append( "<div><img src="+image+"></div>" ); ?

  • Does the same, remains #overlayFancy’s Child

  • Can you explain in other words? for me it is still unclear

3 answers

1

instead of using.

$('#overlayFancy').children('img').remove();

use

$('#overlayFancy').html('');

or else

$('#overlayFancy').find('img').remove();
  • It does not work, what I want is that when clicking outside the image disappear everything, as I have in the last js posted, but if you click on the image nothing happens

1


The easiest way is to listen to the image click and prevent the spread, like this:

jquery:

$(document).on('click', '.wrapperExtraImg', function () {
    $("#overlayFancy").append("<img src=" + $(this).attr('id') + ">").stop().fadeIn(500);
});


$(document).on('click', '#overlayFancy img', function (event) {
    event.stopPropagation();
});

$(document).on('click', '#overlayFancy', function () {
    $('#overlayFancy').stop().fadeOut(300, function () {
        $(this).find('img').remove();
    });
});

See working on Jsfiddle

  • Very well thought out, thank you.

0

The problem is that Children() returns a list (which may be from 1) children, so possibly what you want is first() or something like, by your text, I don’t know if the functions of Hide() and show() are any better, than append() and remove()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.