skip to Main Content

I’ve been trying to implement a JS call from a seperate script and despite referencing m,ultiple demo I cannot get my example to work.

Can someone help me trouble shoot this simple example?

tescript.php says

<!DOCTYPE HTML>
<!-- Load checkout JS -->
<script type="text/javascript" src="tscript.js"></script>

<div class="col-md-3 col-sm-4 col-xs-12 imageUploadSide">
    <ul>
    <li> <button id="buyingPhoto" class="btn btn-buy">A New Buyit Button</button>   
   </li>
   </ul>
 </div>

Then the script file says

// checking script load & log
console.log("script file has been loaded")

$('#buyingPhoto').on('click', function() {
console.log("Can a button be depressed?")
});

I get a console log that the script has loaded (troubleshooting step 1) but the onclick itself doesn’t run

2

Answers


  1. You are missing to import jQuery library .$() is jQuery using. And be careful about order of libraries. And be sure also page is loaded. So you should use document.ready.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="tscript.js"></script>
    
    console.log("script file has been loaded")
    
    $( document ).ready(function() {
        $('#buyingPhoto').on('click', function() {
       			 console.log("Can a button be depressed?")
        });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="col-md-3 col-sm-4 col-xs-12 imageUploadSide">
        <ul>
        <li> <button id="buyingPhoto" class="btn btn-buy">A New Buyit Button</button>   
       </li>
       </ul>
     </div>

    without jquery

    document.getElementById("buyingPhoto").onclick = function() {
    console.log("Can a button be depressed?")
    
    };
    <div class="col-md-3 col-sm-4 col-xs-12 imageUploadSide">
        <ul>
        <li> <button id="buyingPhoto" class="btn btn-buy">A New Buyit Button</button>   
       </li>
       </ul>
     </div>

    or you can give click in html

    function test(){
    
    console.log("Can a button be depressed?")
    
    }
    <div class="col-md-3 col-sm-4 col-xs-12 imageUploadSide">
        <ul>
        <li> <button onclick="test()" id="buyingPhoto" class="btn btn-buy">A New Buyit Button</button>   
       </li>
       </ul>
     </div>
    Login or Signup to reply.
  2. Your whole code is correct. You have not included jquery library, just include the below CDN in your <head></head>section.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search