While there is a lot of good resources on traversing the DOM with jQuery I am not having any luck on my example.
On my site www.smithgrey.co.uk I have a series of thumbnail galleries all which have a 'section title' div in front of them.
What I want to achieve is when you click on the 'section-title' div the first <a href>
link of the thumbnail to the right will clicked.
There are multiple instances of the class="section-title"
– Unfortunately I am not able to add any ID or Classes as this is generated dynamically and have been asked to keep it as is if possible.
The HTML looks like this:
<body>
<div id="content-grid">
<div class="section-title">
<span class="section-title-type">Title of the first thumbnail gallery</span>
</div>
<div class="index-article">
<a href="#" class="fancybox">
<img src="thumbnail-1">
</a>
</div>
<div class="section-title">
<span class="section-title-type">Title of the second thumbnail gallery</span>
</div>
<div class="index-article">
<a href="#" class="fancybox">
<img src="thumbnail-2">
</a>
</div>
<div class="index-article">
<a href="#" class="fancybox">
<img src="thumbnail-3">
</a>
</div>
<div class="index-article">
<a href="#" class="fancybox">
<img src="thumbnail-4">
</a>
</div>
</div>
</body>
And here is my jQuery so far but it does not yield the result I would imagine because it will click the link no matter if I click the first or second <div class="section-title">
.
$('div.section-title').click( function(){
$(this).parent().next($('div.index-article')).children('a.fancybox').click();
});
Solution:
With the help of the other commentors I managed to figure out how to make it work as I expected:
$(document).ready(function() {
$('div.section-title').click( function(){
$(this).next('.index-article').find('a.fancybox:first').click();
});
});
I will assume you have setup your jQuery correct with the appropriate ready event/etc. This is how I'd do it. Please note I've added a click event to the hyperlink to simulate the click in the jsfiddle example.
http://jsfiddle.net/lucuma/s9mds/