0

I am trying to use darkbox and have ran into an error I do not understand. I am displaying a random image when the page loads or refreshes. That part works okay, different images occur. However the error console on Safari reports "Can't find variable:$, and nothing happens when I click the image. The line in question is in the script near the end, $(document).ready(function()

This is my code. I am not very good at javascript so I am not surprised if the answer is obvious to others. Sorry about the badly formatted code.

<?php
  $imageList = array(); 
  foreach(glob('randomimages/*.*') as $file) {
    $imageList[] = $file;
  }
  $image = $imageList[array_rand($imageList)];      
?>

<img src="<?php echo $image?>" id="darkboximg" data-darkbox="randomimages/<?php echo $image?>">  
<div id="darkboximg" style="width:100%"></div>
  <script>
    $(document).ready(function(){
      $("#darkboximg").load("$image");
    });
  </script>
</div>
Amresh Venugopal
  • 8,159
  • 4
  • 33
  • 48
Colin
  • 11
  • 6

4 Answers4

0

$ is not a javascript variable. $ is an alias to Jquery. So add jquery before your script.

0

Make sure JQuery is added.

In $("#darkboximg").load("$image"); should be $("#darkboximg").load( <?php echo '"' . $image . '"' ?>);

Try the following:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
  <?php
    $imageList = array(); 
    foreach(glob('randomimages/*.*') as $file) {
        $imageList[] = $file;
    }
    $image = $imageList[array_rand($imageList)];  
  ?>
  <img src="<?php echo $image?>" id="darkboximg" data-darkbox="randomimages/<?php echo $image?>">

  <div id="darkboximg" style="width:100%"></div>
  <script>
    $(document).ready(function(){
      $("#darkboximg").load( <?php echo '"' . $image . '"' ?>);
    });
  </script>
</body>
</html>
uautkarsh
  • 452
  • 3
  • 9
0
 <?php

    $imageList = array(); 
    foreach(glob('randomimages/*.*') as $file) {
        $imageList[] = $file;
    }
    $image = $imageList[array_rand($imageList)]; 
    ?>
    <script>
    var image = <?php $imageList[array_rand($imageList)] ?>;        

</script>
<img src="<?php echo $image?>" id="darkboximg" data-darkbox="randomimages/<?php echo $image?>">

            <div id="darkboximg" style="width:100%"></div>


            <script>
                $(document).ready(function(){
                    $("#darkboximg").load(image);
                });
            </script>

            </div>`enter code here`
0

Thanks to those who offered answers. The problem was on the line

<img src="<?php echo $image?>" id="darkboximg" data-darkbox="randomimages/<?php echo $image?>">

Changed it to

<img src="<?php echo $image?>" id="darkboximg" data-darkbox="<?php echo $image?>">

and now it works.

Colin
  • 11
  • 6