Skip to content
Advertisement

How to call the function from htmlcode

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 🙂

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement