简体   繁体   中英

how to hide the element using jquery when clicked outside the element

Till now I can grab the src of the image and display it in a fixed division, kind of like a pop up. But I want to hide the div element when the mouse is clicked outside the div. Please guide me how to do it, and also please correct me if my code can be improved. Thanks!

js:

$(document).ready(function () {
    $(".pic").hide();
    $(".screen").click(function () {
        display($(this));
    });
});

function display($this) {
    var source = $("img", $this).attr("src");
    $(".pic img").attr("src",source);
    $(".pic img").css("width","450px");
    $(".pic").show();
}

html:

            <div id="album">
                <div class="pic">
                    <img src="" />
                </div>

                <div class="screen">
                    <h1 class="title">Photo 1</h1>
                    <img src="images/1 png.png" class="image" />
                    <p class="description">This is a description</p>
                </div>

                <div class="screen">
                    <h1 class="title">Photo 1</h1>
                    <img src="images/2 png.png" class="image" />
                    <p class="description">This is a description</p>
                </div>
                <span class="clear_left"></span>

            </div>

blur event of jquery can be used

$(".screen").bind('blur',function () {
    hide($(this));
});

function display($this) {
    $(".pic").hide();
}

Try like this

$(document).click(function () {
    if ($(this).class != "pic") {
        $(".pic").hide();
    }
});

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM