views:

55

answers:

1

This is a newbie question: Can the following HTML/JavaScript code be further simplified by just keeping the DIV to be updated + the INPUT button?

<div id="main_section" name="main_section">
    <div id="update_div">Old stuff</div>
    <input type="button" value="Update" id="update_button"/>
</div>

<script type="text/javascript" src="/jquery.js"></script>

<script type='text/javascript'>
    $("#update_button").click(function() {
        $("#update_div").html("New stuff");
    })
</script>

Thank you.

A: 

You can even inline JavaScript code in your HTML but that is a horrible practice unless you know exactly what you're doing. Reads as:

<div id="update_div">Old stuff</div>
<input type="button" value="Update" onclick="$('#update_div').html('...')" />

If you want to encode the knowledge of what gets updated with that on click, then you can encode that knowledge in the HTML elements itself.

<div id='target'>Old</div>
<input type='button' value='Update' data-target='#target' date-value='New' />

In jQuery's onload, define this for all such buttons:

Since the data seems to be static here, a better global approach might be to define the data on the elements itself, and setup all handlers in one global sweep of the DOM.

$(function() {
    $(':button').click(function() {
        var dest = $(this).attr('data-target');
        var value = $(this).attr('data-value');
        $(dest).html(value);
    });
});

The above code still requires external JavaScript but only need it once for all such button and div elements on the page.

Anurag
In-line is a bad practice either way *if at all avoidable*, imho. I have yet to see a more maintainable project with inline script :)
Nick Craver
@Nick - My idea of inline scripts making the codebase more manageable is when the code is not written in HTML or JavaScript at all, but instead compiled down at multiple levels, dependencies calculated and resolved, and then the final output is just on* events merged with HTML. The hooman never writes that code :)
Anurag
@Anurag: I still think that's less manageable than `class="updater"` and `data-html="...."` with *one* set of script outside, it's easier to generate as well...and less payload to the client, I'm not aware of a downside actually :)
Nick Craver
@Nick Agreed. @Anurag, your suggestion of using obtrusive javascript under any circumstances is preventing me from giving this answer +1, since your other answer is pretty good. Although you have a typo where you called the attribute 'date-value'.
Jesse Dhillon