So I’ve got this code that has an image and when you click it a dropdown menu appears. Pretty simple. The code works fine but I’m trying to incorporate an image swap on click and I’m having difficulty. Here’s the HTML and the JS (there’s some CSS too, but I’ll leave that out):
HTML:
<div id="header">
<dl class="dropdown">
<dt><a href="#"><img src="images/cogwheel_btn.png"/></a></dt>
<dd>
<ul>
<li><a href="#">Favorites</a></li>
<li><a href="#">History</a></li>
</ul>
</dd>
</dl>
</div>
JS:
$(document).ready(function() {
$(".dropdown dt a").click(function() {
$(".dropdown dd ul").toggle();
});
$(".dropdown dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
$("#result").html("Selected value is: " + getSelectedValue("sample"));
});
function getSelectedValue(id) {
return $("#" + id).find("dt a span.value").html();
}
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
$(".dropdown dd ul").hide();
});
});
I’ve tried adding lines like (“dt”).empty(); and then (“dt”).html(“new_image”) but it causes the dropdown functionality to stop working. Anyone any ideas?
I think you’ll be wanting to update the src attribute of your image –
You can find the image in the dropdown like this:
Then update the src attribute
I suspect you’ll want this in the click function like so:
Note that if you want it to toggle on/off, you could check for the visibility of the
ulelement with the.is(':visible')check. Or better still, replace the image with a div, and use a background image changed withtoggleClass().