1

I'm not sure how to entitle my question correctly, but here is the problem:

I have a number of div elements on a page and trigger links pointing to each of those elements with anchor ids. Those elements will work as popups.

<a href="#pop1" class="trigger" id="t1">Show Popup #1</a>
<a href="#pop2" class="trigger" id="t2">Show Popup #2</a>
<a href="#pop3" class="trigger" id="t3">Show Popup #3</a>

<div id="pop1" class="popup">...content here...</div>
<div id="pop2" class="popup">...content here...</div>
<div id="pop3" class="popup">...content here...</div>

Now what is the effecient way to associate multiple links to divs for toggling them on link click? Coding them one by one is not a good option because there can be too many elemens on a page.

$("#t1").click(function(){
  $("#pop1").toggle();
});
artemean
  • 805
  • 1
  • 10
  • 24

2 Answers2

1

Since your triggers have a common class trigger, you can do:

$(".trigger").click(function(){
    $(this.href).toggle(); // href is "#pop1", "#pop2", etc.
    return false; // prevent default action of anchor tag click
});
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • `preventDefault()` should be used instead of `return false` - http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – Sonny Jan 22 '15 at 15:18
  • @techfoobar, this could be a good and easy solution, but it doesn't work... $(this.href) in your code returns empty array. – artemean Jan 22 '15 at 15:18
1

You can add data-attribute (for example, data-div-id) to your link tags that will contain associated div's id:

<a href="#pop1" class="trigger" id="t1" data-div-id="pop1">Show Popup #1</a>

And then you just trigger it like this:

$('a.trigger').click(function(){
    $('div#' + $(this).data('divId')).toggle();
}
Alex Todef
  • 370
  • 2
  • 7