JavaScript Best Practices – Avoiding Inline JavaScript with Dynamic Content

javascript

I read here that you should avoid coding JavaScript inline (see item #1).

It sounds like a great idea; however, I'm not sure how to use js to select dynamic content without setting the id in the function call inline.

For example, I have a simple blog. The comments are hidden, but can be displayed by clicking an anchor (generated dynamically) that calls a JavaScript function to toggle the comments for that specific post:

$commentsButton = "<a name='comments" . $post->id . "' href='#comments" . $post->id . "'> comments (" . count($comments) . ")</a>";

toggleComments() function:

function toggleComments(id) {
    $('#' + id + ' .commentsContainer').toggle(500);
}

How do you keep from doing this kind of thing? Is it always appropriate to avoid inline JavaScript? Or is this a case where it's necessary?

Update:

I ended up using this:

$('.commentButton').each(function() {
    $(this).click(function() {
        $(this).parents('.post').find('.commentsContainer').toggle(500);
    });
});

with this:

$commentButton = "<a class='commentButton'> comments (" . count($comments) . ")</a>";

Best Answer

How do you keep from doing this kind of thing?

In browser based javascript, this is set to the DOM element that triggered the event in the event handler. You can take advantage of that to re-use a function for any DOM element.

function toggleComments() {
    $(this).find('.commentsContainer').toggle(500);
}

Then you don't have to emit the ID into the javascript.

Related Topic