Search code examples
javascriptjqueryjquery-selectorssiblingslightgallery

Pair element-trigger from a list of similar selectors using classes jquery


I have a html code similar to this:

<div class="col-md-7">   
  <div class="row launch">
       <img class="img-responsive" alt=""><br/>
  </div>
  <ul class="row gallery">
    <a href="" class="light-link col-xs-6 col-sm-4 col-md-3 ">
                        <img src=""/>
    </a>
  </ul>
 </div>
 <div class="col-md-7"> 
  <div class="row launch">
        <img class="img-responsive" alt=""><br/>
  </div>
  <ul class="row gallery">
    <a href="" class="light-link col-xs-6 col-sm-4 col-md-3 ">
            <img src=""/>
   </a>
  </ul>
</div>

What i am trying to do (with JQuery) is when the user is clicking on the first div "row launch" to do something with the link "light-link" inside next siblings ul "row gallery". I want the same thing with the second div "row launch", and the link inside the bellow sibling and so on...What i am dooing wrong? my code looks like this:

$('.launch').click(function(){
    $('.launch').next().children("a:first").trigger('click');
 });

But it does not work, it always attach the event to the first ul a "light-link" from the list, even when i click on the second div "row launch" from the list, or the third... Note: needed for a lightgallery example (multiple galleries using classes), i wanted to trigger a clic on a thumbnail, when the user clic on a default large image, and activate the related gallery.


Solution

  • You can use the siblings and children. note that to trigger a native click you should use the get and then use the click function to trigger it.

    $('.launch').click(function(){
        $(this).siblings('ul').children(".light-link").get(0).click();
     });
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="col-md-7">   
      <div class="row launch">
           <img class="img-responsive" alt="pic1"><br/>
      </div>
      <ul class="row gallery">
        <a href="" class="light-link col-xs-6 col-sm-4 col-md-3 ">
                            <img src="google.com" alt="pic link1"/>
        </a>
      </ul>
     </div>
     <div class="col-md-7"> 
      <div class="row launch">
            <img class="img-responsive" alt="pic2"><br/>
      </div>
      <ul class="row gallery">
        <a href="" class="light-link col-xs-6 col-sm-4 col-md-3 ">
                <img src="" alt="pic link2"/>
       </a>
      </ul>
    </div>