skip to Main Content

i have set a simple JS, just an alert message on click of button with id "button". It is working fine when i insert the code inside Revolution Slider Custom CSS/JS field.

function hello(){
        alert("Hello! I am an alert box!!");
}
jQuery("#button").click(hello);

But not working on the function.php file of the child theme, why is that?

function button_fn() {
    ?>
        <script>
            function hello(){
                alert("Hello! I am an alert box!!");
            }
            jQuery("#button").click(hello);
        </script>
    <?php
}
add_action('wp_enqueue_scripts', 'button_fn');

2

Answers


  1. Try below code:

    function button_fn() {
        <script>
        function hello(){
            alert("Hello! I am an alert box!!");
        }
        jQuery(function() {
            jQuery(document).on('click', '#button', function(){ 
                hello();
            })
        })
        </script>
    }
    
    add_action('wp_enqueue_scripts', 'button_fn');
    
    Login or Signup to reply.
  2. The problem here is that you’re trying to enqueue the script without any dependencies, so it’s likely that jQuery hasn’t been enqueued yet. Instead of using wp_enquque_scripts try wp_footer with a priority higher than 20. 20 is where the enqueue scripts hook fires.

    function button_fn() {
        ?>
            <script>
                function hello(){
                    alert("Hello! I am an alert box!!");
                }
                jQuery("#button").on('click', function(){
                     hello()}
                );
            </script>
        <?php
    }
    add_action('wp_footer', 'button_fn', 30);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search