I'm very new to JQuery, and I'm having some trouble understanding how to do this:
I have an image of class "imgexpander" with the src attribute set to "img1.png". When the image is clicked on, it should look to see whether a div with class "expand" is currently hidden or visible.
OR:
I'm not familiar with the available functions in JQuery yet. How could this be accomplished? Can you give me some sample code that I can work with?
Thanks in advance!
UPDATE: I forgot to add a detail: is it possible to somehow make the onclick of an image of class "imgexpander" only influence divs that are all included together in one big div? So, the hierarchy would be something like:
The desired result would be to have each "image with onclick" only influence "divs that need to be influenced" inside its respective "big div". Is this possible? I'm not sure the current answer would fit, but thanks!
How about:
$("img.imgexpander").click
(
function()
{
var expandableDIVs = $(this)
.parents("div.bigdiv:first")
.find("div.expand");
expandableDIVs.toggle();
this.src = expandableDIVs.is(":visible") ? "img2.png" : "img1.png";
}
);
This code sets up a click event handler for all IMG elements of class imgexpander. The handler toggles the visibility of all DIV elements of class expand. The src attribute of the image is updated by testing if any of the DIV elements matched by "div.expand" are visible.
Notice that I can assign the jQuery wrapped set of DIVs matching the "div.expand" selector to a JavaScript variable for later use.
The this keyword in the event handler refers to the current DOM element matched by the "img.imgexpander" selector. Remember, there can be several elements matched by this expression.
EDIT: The method of acquiring the div.expand elements has been updated to reflect the changes to the OP. Only DIV elements that are children of the parent bigdiv classed DIV will be toggled when an img is clicked.
Note that care has been taken to ignore the way that elements are marked up. It is important to us that the IMG element has a parent DIV somewhere in its parent chain of class bigdiv, but this element does not have to be an immediate parent. This is the reason for my use of the :first pseudo-selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With