0

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');
winner
  • 1
  • 1
  • Probably because this outputs the script element to early, before the element you are trying to access via ID even exists. https://stackoverflow.com/questions/4498482/javascript-cant-find-element-by-id – CBroe Sep 06 '21 at 13:10
  • Have you tried `jQuery( document ).ready(function()` – Rüzgar Sep 06 '21 at 13:13

2 Answers2

0

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');
0

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);
Howard E
  • 5,454
  • 3
  • 15
  • 24