oliver13
oliver13

Reputation: 1036

JQuery one click event for multiple element events

My question is related to this one: jQuery same click event for multiple elements

However, when I do:

$('.class1, .class2').click(function() {
   some_function();
});

I always use the same function with the same object. What if I wanted to consolidate the following two statements for instance:

$(".class1").click(function () {
  $(".classer1").slideToggle("slow");
});

$(".class2").click(function () {
  $(".classer2").slideToggle("slow");
});

They reference a different object for each - can I even consolidate this?

Thanks, Oliver

Upvotes: 3

Views: 13911

Answers (5)

Kevin B
Kevin B

Reputation: 95022

It might be better to select based on the elements location depending on your html. For example, if this were your html:

<dl class="class1 list">
    <dt>Foo</dt>
    <dd>Foobar</dd>
    <dt>Dog</dt>
    <dd>Pitbull</dd>
</dl>
<dl class="class2 list">
    <dt>Foo</dt>
    <dd>Foobar</dd>
    <dt>Dog</dt>
    <dd>Pitbull</dd>
</dl>

you could use:

$(".list dt").click(function(){
    $(this).next("dd").slideToggle();
});

to handle both lists with a single click event.

Upvotes: 1

acconrad
acconrad

Reputation: 3219

I think the best way to do this is to add a data attribute to the reference number you are using for each of the classes so if you have something like

<div class="class1" data-ref-id="1"></div>

and

<div class="class2" data-ref-id="2"></div>

You could find your referenced toggle class like so:

$('.class1, .class2').click(function (e) {
    $('.' + NAME_OF_REFERENCED_TOGGLE_CLASS + this.data.refId).slideToggle('slow');
})

Upvotes: 2

pdoherty926
pdoherty926

Reputation: 10349

<div class='common-class' data-id='1'></div>

$('.common-class').on('click', function() {
    if ($(this).data('id')) { 
        $(".classer" + $(this).data('id')).slideToggle("slow");
    }
});

Upvotes: 2

Ahmad Alfy
Ahmad Alfy

Reputation: 13371

You might want to take a look at add(). Use it to add selectors to the selection stack. Use it like this:

$('.class1').add('.class2').click(function (e) {
    // Do whatever you want
})

Upvotes: 2

j08691
j08691

Reputation: 207901

You could do this:

$(".class1, .class2").click(function () {
  $(".classer"+$(this).attr('class').substr(-1)).slideToggle("slow");
});

as long as the elements you're clicking on only have one class. This pulls the integer off the element being clicked on and appends it to .classer. So clicking on .class2 would trigger the toggle on .classer2.

Upvotes: 5

Related Questions