Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide parent div on click using jQuery

So I'm trying to write a super simple script that will allow a user to throw any link or button with the class .close inside of a div, and when that .close link is clicked, it automatically closes the parent container.

Here is what I'm currently trying to work with: JSFiddle

The code that I am currently trying to use is:

HTML

<div class="well notice bg-green">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <p>This is a notice that is green.</p>
</div>

CSS

.well {
    background: #f9f9f9;
    border-color: #f1f1f1;
    border-style: solid;
    border-width: 1px;
    padding: 15px 20px;
}
.notice {
    margin: 15px 0;
    padding: 0px 15px;
}
.well.bg-green {
    background: #dff0d8;
    border-color: #d6e9c6;
    color: #468847;
}
.close {
    color: #000;
    filter: alpha(opacity=20);
    float: right;
    font-size: 21px;
    font-weight: bold;
    line-height: 1;
    margin-top: 15px;
    opacity: .2;
    text-shadow: 0 1px 0 #fff;
}
.close:hover, .close:focus {
    color: #000;
    cursor: pointer;
    filter: alpha(opacity=50);
    opacity: .5;
    text-decoration: none;
}
button.close {
    background: transparent;
    border: 0;
    cursor: pointer;
    padding: 0;
    -webkit-appearance: none;
    -moz-appearance: none;
}

JavaScript (jQuery)

$('.close').live("click", function () {
    $(this).parents('div').fadeOut;
});

Let me know if my question doesn't make sense or if any more elaboration is needed. Thank you!

like image 288
Keenan Payne Avatar asked Feb 26 '14 20:02

Keenan Payne


4 Answers

Two problems:

  • live() doesn't exist in the version of jQuery in your fiddle (deprecated in 1.7, removed in 1.9)
  • fadeOut is a function (you were missing parens to execute it)

http://jsfiddle.net/KF7S6/

$('.close').on("click", function () {
    $(this).parents('div').fadeOut();
});

If you want it to work on dynamic elements, use this version:

$(document).on('click', '.close', function () {
    $(this).parents('div').fadeOut();
});
like image 59
Jason P Avatar answered Nov 04 '22 08:11

Jason P


http://jsfiddle.net/6Xyn4/4/

$('.close').click(function () {
    $(this).parent().fadeOut();
});

Recommended to use .click() now in place of deprecated .live()

like image 29
Christopher Marshall Avatar answered Nov 04 '22 09:11

Christopher Marshall


working demo http://jsfiddle.net/gL9rw/

Issue was .live which is deprecated now.

If you keen: What's wrong with the jQuery live method? :)

code

$('.close').on("click", function () {
    $(this).parents('div').fadeOut();
});
like image 3
Tats_innit Avatar answered Nov 04 '22 10:11

Tats_innit


Try this, it should be fadeOut() not fadeOut

$('.close').click(function () {
  $(this).parents('div').fadeOut();
});
like image 1
Krish R Avatar answered Nov 04 '22 10:11

Krish R