1

I want to call a function on button click event . The function is defined in another js file and I have enqueue that file in my function.php file. I can see that the file has been loaded from enqueue. But I got error

errorReferenceError: myFunction is not defined

when I click on that button. I want to display dropdown menu on that button click

<button onclick="jQuery(document).ready(function($) {myFunction();});" class="dropbtn"><i class="fa fa-bars fa-lg" aria-hidden="true"></i></button>

custom.js

(function( $ ) {

    function myFunction() {

        document.getElementById( 'myDropdown' ).classList.toggle( 'show' );

    }

    window.onclick = function( event ) { 

        if ( !event.target.matches( '.dropbtn' ) ) {

        var dropdowns = document.getElementsByClassName( 'dropdown-content' );
        var i;

            for ( i = 0; i < dropdowns.length; i++ ) {

                var openDropdown = dropdowns[i];

                if ( openDropdown.classList.contains( 'show' ) ) {

                    openDropdown.classList.remove( 'show' );

                } 

            } 

        }

    }

})( jQuery );
mattkrupnik
  • 517
  • 3
  • 16
  • Just write `myFunction` from outside to `$(function() {})`. and your anchor attribute should be `onclick=return myFunction();` – Vineet Jan 13 '17 at 12:21

3 Answers3

0

The issue is with the scope of the function, for more detailed explanation refer this link. To resolve it, try to call the function within the js file itself. For example:

$(document).ready(function(){
    function myFunction(){
    ...
    }

    $(".dropbtn").click(myFunction());
});
Manikiran
  • 2,618
  • 1
  • 23
  • 39
0

Should work

$(document).ready(function(){
    function myFunction(){
        alert ('Say something!');
    }

    $(".dropbtn").click(function(){
        myFunction();
    });
});
mattkrupnik
  • 517
  • 3
  • 16
0

I noticed that you do not need to use the ready function in the onclick attribute of the button, therefore this will suffice:

<button onclick="myFunction();" class="dropbtn">
  <i class="fa fa-bars fa-lg" aria-hidden="true"></i>
</button>

Instead of doing this however, you can remove that onclick attribute from the button (it is good practice to avoid inline scripts, for code maintainability and security reasons) and try the solution Manikiran suggested you, but with one small difference, you define myFunction but do not execute it in the custom.js:

jQuery(function(){
  function myFunction(){
    jQuery( '#myDropdown' ).toggle( 'show' ); //this is the jQuery way
  }

  // remaining code of your custom.js

  jQuery(".dropbtn").click(myFunction); // binds the click event to
                                        // all the buttons with the dropbtn class
});

I noticed you do not use the $ in some parts, you can replace them all with the jQuery keyword.

CPHPython
  • 12,379
  • 5
  • 59
  • 71