开发者

Jquery how to trigger function if clicked?

I am trying to create a simple error message that should disapear on page click.

Here is my Jsfiddle: http://jsfiddle.net/ZKgWR/1/

I want to hide the .super message when clicked on the page, when the message is visable.

Here is my jquery:

// show super on click
$('.error').click(function(e) {
    e.preventDefault();
    var position = $(this).position();
    $('.super').css({
        display: 'block',
        position: 'absolute',
        left: position.left + 50,
        top: position.top
    });
    var super = true
});


// If .error clicked then enable the function to remove the super message
if ($('.error').show()) {
    $(document).click(function() {
        $('.super').hide();
    });
}


// If .error clicked then enable the function to remove the super message
if ($('.error').show()) {
    $(document).click(function() {
        $('.super').hide();
    });
}

The problem is that this part of the code is not working:

if ($('.error').show()) {
    $(document).click(function() {
        $('.super').hide();
    });
}

Nothing appends when clicking on .error because of the function is also active when开发者_如何学JAVA the .super is invisable.


Why not add a class called active or visible?

$('.error').click(function (e) {
e.preventDefault();
var position = $(this).position();
$('.super')
   .show()
  .css({display: 'block', position: 'absolute', left: position.left + 50, top: position.top})
.addClass("active");
});

$(document).click(function() {
   if($('.super').hasClass("active"))
     $('.super').removeClass("active").hide();
});

Your error was in the if statement, an event must occur first before doing any checks...

EDIT:

Looking at your js fiddle I realised the mistake I made, it should be e.stopPropogation, here is a full working code:

$(document).click(function(e) {
    if($('.super').hasClass("active"))
        $('.super').hide();
});

$('.error').click(function(e) {
    e.stopPropagation();
    var position = $(this).position();
    $('.super').fadeIn(250).css({
        display: 'block',
        position: 'absolute',
        left: position.left + 50,
        top: position.top
    }).addClass("active");
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜