Reputation: 77
I have a basic list with titles. In a perfect world when a user clicks the title or a nested icon a descriptive paragraph displays and the icon changes. If the user goes title by title, opening and closing before moving on then there's no issue, but open and move to open the next and things get weird and bugg. The paragraph will toggle but the icon stays the same.
Perfect world scenario, title or img is clicked, the icon changes to the minus and the paragraph displays, the paragraph stays open and the next title is clicked, that paragraph and icon change and so on. Hashed and re-hashed this over and over and I'm at a loss.
$(".hold-text").click(function() {
if (!$("img").hasClass("foo")) {
$(this).find(".title").children("img").attr("src", "minus-icon.png").addClass("foo");
$(this).children("p").toggle();
} else {
$(this).find(".title").children("img").attr("src", "plus-icon.png").removeClass("foo");
$(this).children("p").toggle();
}
});
.hold-text>p {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="hold-text">
<h3 class="title">lorem blah<img class="img" src="plus-icon.png" /></h3>
<p>text</p>
</li>
<li class="hold-text">
<h3 class="title">lorem blah<img class="img" src="plus-icon.png" /></h3>
<p>text</p>
</li>
<li class="hold-text">
<h3 class="title">lorem blah<img class="img" src="plus-icon.png" /></h3>
<p>text</p>
</li>
</ul>
Upvotes: 0
Views: 29
Reputation: 24001
!$("img").hasClass
will check for any image with the class .. you can use !$(this).find("img").hasClass
and instead of use the if statement you can use .toggleClass()
.. see the next example$(".hold-text").click(function() {
var Getimage = $(this).find("img"); //Get the Image
Getimage.attr("src", Getimage.attr('src') == "minus-icon.png" ? "plus-icon.png" : "minus-icon.png").toggleClass("foo"); // toggle between image src and toggle the class
$(this).find("p").toggle(); // toggle p
console.log(Getimage.attr('src')); // Just to check the src is changed
});
.hold-text>p {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="hold-text">
<h3 class="title">lorem blah<img class="img" src="plus-icon.png" /></h3>
<p>text</p>
</li>
<li class="hold-text">
<h3 class="title">lorem blah<img class="img" src="plus-icon.png" /></h3>
<p>text</p>
</li>
<li class="hold-text">
<h3 class="title">lorem blah<img class="img" src="plus-icon.png" /></h3>
<p>text</p>
</li>
</ul>
Explantation:
Getimage.attr('src') == "minus-icon.png" ? "plus-icon.png" : "minus-icon.png"
this line means if the image src is "minus-icon.png"
change to "plus-icon.png"
else "minus-icon.png"
Upvotes: 1