tareoflight
tareoflight

Reputation: 13

php Generated html Button to run javascript

What i would like to do is click the button and have it up date the background of another div. The buttons are generated with php from imgs in a file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <title></title>
    <style>
        button{width: 100%; }
    </style>
</head>
<body>
    <div id="Navi" style="width: 150px; height: 640px;background: green;">
        <?php
            foreach (glob("*.png") as $filename) {
                echo "<button id='$filename' onclick='change(event);'>".substr($filename, 0, -4)."</button></br>";
           }
        ?>
    </div>
    <div id="ImgBig" style="height: 640px; width: 640px;margin-left: 150px; margin-top: -640px; background: blue;"></div>
    <script>
        function change(event){
            $("#ImgBig").css("background-image", "url("+event.target.id+")"); 
        }
    </script>
</body>

Upvotes: 1

Views: 48

Answers (1)

Adib Aroui
Adib Aroui

Reputation: 5067

Please try to change event to this in your php target so that your javascript function is applied to the current item:

<?php
            foreach (glob("*.png") as $filename) {
                echo "<button id='$filename' onclick='change(this);'>".substr($filename, 0, -4)."</button></br>";
           }
        ?>

then in your javascript change function, just remove target:

function change(event){
            $("#ImgBig").css("background-image", "url("+event.id+")"); 
        }

Upvotes: 1

Related Questions