Search code examples
arraysmethodsjbuttonactionlistener

Detect clicks on button array with a single method


Im working in a school project, a minesweeper. Will be 20x20, so it has 400 buttons. Its there a way to add an actionEvent/actionPerformed and implement a generalized method for the whole array? Or there is an easier way?


Solution

  • Maybe something like that (using jQuery for convenience but you can do it with Vanilla JS too):

    Your HTML:

    <div id="buttonsHolder">
        <button data-num=1>1</button>
        <button data-num=2>2</button>
        <button data-num=3>3</button>
        ...
        <button data-num=4>4</button>
    </div>
    

    Your JavaScript:

    $('#buttonsHolder').on('click', 'button', (function(evt){
        var buttonNum = $(this).attr('data-num');
        // Now, buttonNum variable holds the button number has clicked.
    });
    

    Of course instead of use data-num atribute you can use whatever data you need.