Question

I'm looking into Unobtrusive JavaScript, suggesting the JavaScript should be separated from HTML.

In my page, I use jQuery 1.9.1 with jQuery Migrate plugin 1.1.1 . I use <li> to simulate menu for my page. For each <li>, it is a menu item. Originally I assigned the JavaScript as follow:

    <ul>
        <li onclick="showQ('0001')">Q 1</li>
        <li onclick="showQ('0002')">Q 2</li>
        <li onclick="showQ('0003')">Q 3</li>
        <li onclick="showQ('0004')">Q 4</li>
    </ul>

1st Question: How to convert it with respective to Unobtrusive JavaScript ?

The JavaScript function is as follow:

function showQ(id) {
  $('#' + id).show();
}

2nd Question: ( it's probably a jQuery question ) How can the function reference the original <li>, e.g. to add a class via .addClass('some_css_class'); ?

Was it helpful?

Solution

change the id of each <li> to include the id that you want to pass into the showQ function. in the document ready handler assign a click hander to the <li> elements and call the showQ function from there, passing in the id extracted from the clicked <li>. in the click handler refer to the clicked <li> using $(this) in order to add a class to it

html

<ul>
    <li id="i0001">Q 1</li>
    <li id="i0002">Q 2</li>
    <li id="i0003">Q 3</li>
    <li id="i0004">Q 4</li>
</ul>

javascript

function showQ(id) {
  $('#' + id).show();
}

$(document).ready(function() {
    $("ul li").click(function() {
        var id = $(this).attr("id").substring(1);
        showQ(id);

        $(this).addClass("some_css_clas");
    });
});

example

OTHER TIPS

HTML:

<ul>
    <li>Q 1</li>
    <li>Q 2</li>
    <li>Q 3</li>
    <li>Q 4</li>
</ul>

JS snippet:

$(document).ready(function(){


$('ul li').click(function(){


$(this).addClass('some_css_class');

});

});

EDIT : In your function code:

function showQ(id) {
  $('#' + id).show();
}

which id do you want to show ? If the li with that id was not visible, how could you click on that ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top