-1

I have JS code, that works as it supposed to. But insetad of calling "islandA.onclick" from the function, I need to call it from the outside - from HTML code. (there are more islands :)

    $(document).ready(function(){
        var islandA = document.getElementById("ostrovA");

        var websocket = new WebSocket("ws://localhost:8090/php-socket.php");
        
        islandA.onclick = function(event) {
                var messageJSON = {
                    team: '0001',
                    function: 'moveBoat'
                };
                websocket.send(JSON.stringify(messageJSON)); 
        }
        websocket.onmessage = function(event) {
            var Data = JSON.parse(event.data);
            moveBoat (); 
        };        

    });

The needed way of calling is <img src='img/island.png' id='isladnA' onclick='hereSouldBetheCalling()'>

Code used (and modified) from https://www.php.net/manual/en/function.socket-create.php Thank you so much :)

Láďa
  • 5
  • 4
  • 1
    _“there are more islands”_ - that does not mean that you have to revert back to old-school, _ugly_ ways of adding event handling using clunky HTML attributes. You are using jQuery already, so go read up on how its event handling using `.on()` works. – CBroe Feb 18 '21 at 14:57

1 Answers1

0

You can place this in your $(document).ready

var websocket = new WebSocket("ws://localhost:8090/php-socket.php");
 
 
$('#islandA').on('click', function(){

    var messageJSON = {
        team: '0001',
        function: 'moveBoat'
    };
    websocket.send(JSON.stringify(messageJSON)); 

});

This uses jquery's "on" method to handle a click event for that element. If you have multiple images you wish to click on, you can do it from a single definition by assigning a common class to all those images and using that to identify them.

<img src='img/island.png' class="myIsland" id='isladnA' onclick='hereSouldBetheCalling()'>

$('.myIsland').on('click', function(e){
    // $(e.target)
    //    or
    // $(this)
}

That will bind a click event to call the same function for all "myIsland" elements.

Phaelax z
  • 1,814
  • 1
  • 7
  • 19
  • Cool thank you very much :) It is almost perfect. The only I miss is to find out what "id" did trigger that action. The "this.id" is undefined when I use the class. – Láďa Feb 18 '21 at 18:24
  • I've updated the last code segment in my answer above to demonstrate how to get the element that triggered the event. I believe either solution should work. – Phaelax z Feb 18 '21 at 19:29