Search code examples
javascriptjqueryunobtrusive-javascript

How to pass arguments to function using unobtrusive JavaScript?


In traditional code I will pass arguments to link button like this:

<a href="javascript:call_hello(1, 2, 3)" role="button">Hello</a>

How can I do it in unobtrusive JavaScript style with JQuery or similar library.

<a href="#" class="hello" arg1="1" arg2="2" arg3="3" role="button">Hello</a>

Do not focus that code is longer since it is only example. I want attach Javascript code in such way.

$(".hello").on('click', call_hello2);

Can you suggest the best solution in your opinion for unobtrusive JavaScript style (attaching Javascript by matching elements not by html code).


Solution

  • You should use data-* prefixed custom attributes which can be stored and fetched using $.fn.data()

    Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

    Alternatively HTMLElement.dataset can also be used.

    The HTMLElement.dataset read-only property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

    $(function() {
      $('a').on('click', function(event) {
        event.preventDefault();
        var arg1 = $(this).data('arg1');
        
        alert(arg1)
        
        //Using native JS
        console.log(this.dataset.arg1)
      })
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" class="hello" data-arg1="1" data-arg2="2" data-arg3="3" role="button">Hello</a>