Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set onclick function to anchor element in laravel

I'm developing a laravel application, there I want to set a onclick function to Html anchor element. So I created it as following way.

In my blade view

<a class='compon' id="{{$value[1]}}" href="#" onclick="return myFunction();">
    <div class="mq-friends thumbnail">
       <div class="mq-friends-footer">
          <small>{{$value[0]}}</small>
       </div>
    </div>
</a>

my resources/assets/js/app.js

function myFunction() {
    console.log('whatever');
    return true;
}

This is not working, (I also carefully checked that app.js file has built into public/js/app.js using laravel-mix (npm run dev) and the function myFunction() is there.)

What I want to know is why it is not working? is there any problem with blade?

Note: This is clearly working when I insert this script into my same blade view without adding to js file:

<script type='text/javascript'>
     function myFunction()
     {
          console.log('whatever');
          return true;
     }
</script> 
like image 257
Vajira Prabuddhaka Avatar asked Dec 07 '25 08:12

Vajira Prabuddhaka


1 Answers

Im not 100% sure of it, but:

I think when you want to bind the anchor onclick event, you need to bind the function to the window object, like this in your app.js:

  window.myFunction = function(ev) {
     console.log(ev)
  });

In my case it solved.

Another way (seems to be the recommended one) is binding in an unobtrusive way.

Hope it helps o/

like image 65
Renato Gomes Avatar answered Dec 09 '25 21:12

Renato Gomes