Hello, I am really hoping someone can help me, I have zero JS experience and I am stuck. I have a messaging system, email type where they are listed, and I want to fade the div out when clicked, I won’t know the number of divs, obviously that wil depend on the users. I have code that will fade out one div “.messages-wrapper” when “.message-close” is clicked, but it only fades that div out and no others. I’m guessing what I need to to assign a unique id to the divs and fade them out depending on what div is clicked. I have no idea how to do that and am asking if someone can help me. Here is my js
$(document).ready(function(){
$( “.message-close” ).click(function() {
$( “.messages-wrapper” ).fadeOut( “slow”, function() {
});
});
});
and here is my html
button type=“submit” id=“message-close”
Any help is appreciated.
It’s hard to say anything without HTML. Much better if you can provide jsfiddle or codepen link.
1 Like
Can’t you use $(this) to access the clicked element?
So, for example
$(function() { // same as $(document).ready
$(".message-close").click(function() {
$(this).find(".messages-wrapper").fadeOut("slow"); // find child .messages-wrapper
// or
$(this).parent().find(".messages-wrapper").fadeOut("slow"); // find a .messages-wrapper in parent element
});
});
You can also use attributes.
<a class="message-close" data-message-id="1">Close</a>
<div class="messages-wrapper" data-message-id="1">...</div>
$(".message-close").click(function() {
var id = $(this).data("message-id");
$(".messages-wrapper[data-message-id='" + id + "']").fadeOut();
});
2 Likes
That worked, I used the id of the user that sent the message instead of “1” and it works fine. I appreciate the help big time. Much thanks.
1 Like