views:

275

answers:

3

I'm trying to create a standardized show/hide element system, like so:

<div class="opener popup_1">Click Me</div>
<div class="popup popup_1">I'm usually hidden</div>

Clicking on the div with the opener class should show() the div with the popup class. I don't know how many opener/popup combinations I'm going to have on any given page, I don't know where on any given page the opener and the popup are going to be displayed, and I don't know how many popups a given opener should call show() for. Both the opener and the popup have to be able to have more classes than just what's used by jQuery.

What I'd like to do is something like this:

$(".opener").click(function() {
  var openerTarget = $(this).attr("class").filter(function() {
    return this.class.match(/^popup_([a-zA-Z0-9-_\+]*) ?$/);
  });
  $(".popup." + openerTarget).show();

The idea is that when you click on an opener, it filters out "popup_whatever" from opener's classes and stores that as openerTarget. Then anything with class=popup and openerTarget will be shown.

+2  A: 
$('.opener').click(function() {
  var openerTarget = this.className.match(/\bpopup_\w+\b/);
  $('.popup.' + openerTarget).hide();
}​);​

http://jsbin.com/ezizu3/edit

Max Shawabkeh
+1. For better performance, use the id (rather than classname) of `popup` div as part of `opener`'s classname. `<div class="opener popup_1">` , `<div id="popup_1" class="popup">`
Chetan Sastry
Awesome, that did it.
motorfirebox
A: 

I tend to think this kind of thing works better using IDs:

<div id="popup1" class="opener">Click Me</div>
<div class="popup popup1">I'm usually hidden</div>

with CSS:

div.popup { display: none; }

and JS:

$("div.opener").click(function() {
  $("div." + this.id).toggle();
});
cletus
The issue with IDs is that they're supposed to be unique. That means that I can't, for instance, have multiple openers for a single popup.
motorfirebox
A: 

This seems like a good case to use the HTML5 custom data attributes.

HTML:

<div data-popup-trigger="popup1">Click me!</div>
<div class="popup1">Secret information no one will ever see! Muahaha!</div>

JS:

$('[data-popup-trigger]').click(function() {
  var popupClass = $(this).attr('data-popup-trigger');
  $('.' + popupClass).show();
});

I think this is cleaner because you don't have to parse the element's classes with reg ex. You can add any number of arbitrary other classes to the triggering element and it will still be plainly obvious which elements the trigger will cause to pop up.

Jimmy Cuadra