Reputation: 1311
Currently I have a heading with a downwards pointing icon. If the header is clicked, I want the image to change to an upwards one.
I have tried using the "?" operator to query if it is, but I am not 100% sure how it works. I'm using this code at the moment.
// Toggle message_body
$(".message_head").click(function(){
var id = $(this).attr("id");
$(this).next(".message_body").slideToggle(500);
$(".icon[id=" + id + "]").attr("src", "../images/admin/Symbol_Down.png" ? : "../images/admin/Symbol_Up.png");
return false;
});
I know this code does not work. Could someone please show me how? Thanks!
Upvotes: 1
Views: 7871
Reputation: 99861
$(".message_head").click(function(){
this.next(".message_body").slideToggle(500);
this.attr("src", this.attr('src') == "../images/admin/Symbol_Down.png" ? "../images/admin/Symbol_Up.png" : "../images/admin/Symbol_Down.png");
return false;
});
More info on the ?: (ternary operator). This:
var A = B ? C : D;
Is the exact same as:
if (B) {
var A = C
} else {
var A = D;
}
Upvotes: -1
Reputation: 41401
This will do the trick. Note that you need to do the comparison within the terenary operator. If you just do "something" ? "blah" : "result
, it will always be true, because non-null values are always true.
var up = "../images/admin/Symbol_Up.png";
var down = "../images/admin/Symbol_Down.png";
$(".message_head").click(function(){
var icon = $(".icon[id=" + $(this).attr("id") + "]");
$(this).next(".message_body").slideToggle(500);
icon.attr("src", this.attr("src") == up ? down : up);
});
I just realized one fundamental issue with your HTML if your JavaScript css selector is accurate. You are asking for .icon[id=x] and using the ID attribute from the .message_head class to find the ID of the icon. For this to work, you would have to have the same ID for both, which is invalid HTML. What I imagine your HTML looks like is this:
<div class="message_head" id="1">
<img class="icon" src="up.jpg" id="1"/>
</div>
This is a nono. What you can do is this:
<div class="message_head" id="1">
<img class="icon" src="up.jpg" />
</div>
var up = "../images/admin/Symbol_Up.png";
var down = "../images/admin/Symbol_Down.png";
$(".message_head").click(function(){
var icon = $('.icon', this);
$(this).next(".message_body").slideToggle(500);
icon.attr("src", this.attr("src") == up ? down : up);
});
Upvotes: 3
Reputation: 21575
You're not using anything in the conditional.
$(".message_head").click(function(){
var id = $(this).attr("id");
var myBody = $(this).next(".message_body").slideToggle(500);
$(".icon[id=" + id + "]").attr("src", (myBody.css("display") == "none") ? "../images/admin/Symbol_Down.png" : "../images/admin/Symbol_Up.png");
return false;
});
Note that if this produces backwards behavior (i.e., up instead of down), you should change "none"
to "block"
.
Upvotes: 0