3

I need to programmatically trigger a click event that's being handled by jQuery. Here's the current code:

var $thumbs = $('#PhotoGalleryThumbs .tile');
var $zoom = $('#PhotoGallery #PhotoGalleryZoom img');
var $description = $('#PhotoGallery #PhotoGalleryDescription');

$thumbs.click(function(event) {
    event.preventDefault();
    var $thumb = $(this);
    $thumb.addClass('selected')
        .siblings().removeClass('selected');
    $zoom.attr('src', $thumb.children('a').attr('href'));
    $description.html($thumb.find('img').attr('alt'));
});

I am having a mental block working out how to create a function out of the event handling code and then arbitrarily calling it for an element in the $thumbs object.

2 Answers 2

5
$thumbs.click();

This would trigger the click event. Is this what you're looking for?

Sign up to request clarification or add additional context in comments.

5 Comments

Optionally, you could specifically target a given element, rather than the entire set of them. $('#yourTarget').click();
$thumbs is a collection of objects. I want to select a specific object and call the click() event on that.
as S Pangborn said, $('#yourSpecificElement').click()
I need it to be an indexed selection, like an array. Something like $thumbs[7].click(). I thought that .index() might do it, but that seems to do the reverse of what I need.
$($thumbs[7]).click() would do
2

Similar to the previous suggestion of

$($thumbs[7]).click();

you can use

$thumbs.eq(7).click();

For clarification, array indexing into a jQuery collection gives you the DOM Element at that position, whereas .eq(n) gives you a new jQuery object which references only the indexed element.

http://api.jquery.com/eq/

1 Comment

Thanks Geoff, I'll keep that one in my back pocket for sure!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.