1

I have the following html, dynamically created.

<a class="open"></a>
<div class="dialog"></div>
<a class="open"></a>
<div class="dialog"></div>
<a class="open"></a>
<div class="dialog"></div>
<a class="open"></a>
<div class="dialog"></div>

Using the follwing jquery, I'm assigning ID's to each a aswell as each div

$('a.open').prop('id', function(i){
return '' + (i + 1);
});
$('div.dialog').prop('id', function(i){
return 'dialog' + (i + 1);
});

I'm then using the assigned ID's to trigger a jquery ui Dialog pop-up, however, I'm having to rewrite the function below for x number of times. Is there a way to create the below function so I do not have to rewrite it x number of times. (x being the max. number of times the the divs may appear on page).

$("#1").click(function(){
   $("#dialog1").dialog("open");
});

3 Answers 3

2

Sounds like an ideal use for data attributes. When you dynamically generate the <a> tags, assign them a data attribute like so:

<a class="open" data-openNumber="1"></a>

(You can also do this via jQuery, of course).

Then all you have to do is write a single click handler:

$('body').on( 'click', '.open', function(){
    var num = $(this).data('openNumber');
    $('#dialog'+num).dialog( 'open' );
});

Note that I don't attach the handler directly to elements with class open; if I did that, I would have to do it every time the elements were dynamically created. Instead, I attach the handler to the body, and filter it by class open; that way I don't have to keep re-declaring that click handler. If you have a more handy enclosing class, you can use that instead of body, but not knowing your page structure, I didn't know what that element would be, so I just used body.

I made a jsFiddle to demonstrate the concept. I hope it's helpful:

http://jsfiddle.net/Jammerwoch/Z9U67/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick responce, this has been bugging me all day, had to hardcode the solution, I'll give you the answer first thing in the morning when I try this out.
1

What about this?

HTML

<a class"open" data-id="1">open</a>
<div class="dialog" data-id="1"></div>

JS

$(document).on("click", ".open", function(e) {
    var id = $(this).data("id");
    $(".dialog[data-id="+ id +"]").dialog("open");
});

Comments

1

If you are only using the id attribute to listen for clicks later on. It makes more sense to create a single event listener for the group.

$("a.open").on("click", function(){
    $(this).find(".dialog").dialog("open")
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.