0

I have added 2 buttons in my page and I have added the default button click code using javascript but it is not working.

This is my HTML code:

<button class="tablink" onclick="openPage('inside', this, '#0077c0')" id="defaultOpen">Inside</button>
<button class="tablink" style="left:40px;" onclick="openPage('outside', this, '#0077c0')" >Outside</button>

This is JS code added in functions.php:

function wp_head_custom_mm(){
?>

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

</script>
    <?php    
    }
add_action('wp_head', 'wp_head_custom_mm');

But it is not working, my default button is not clicked.

Error:

Uncaught TypeError: Cannot read property 'click' of null

I want to button with id defaultOpen should be clicked when the website opens.

Any help is much appreciated.

1 Answer 1

2

Anytime you want to use JavaScript in WordPress, you should enqueue it.

Save the JS as a file, ie clickbutton.js inside your theme folder:

document.getElementById("defaultOpen").click();

Then in functions.php, enqueue that file:

add_action('wp_enqueue_scripts', 'wpse_371294_enqueue_js');
function wpse_371294_enqueue_js() {
    wp_enqueue_script('click-button', get_template_directory_uri() . '/clickbutton.js', array(''), "1.0", true);
}

(If you only need the file to run on one page, enqueue it conditionally so it doesn't get loaded elsewhere.)

However, note that you haven't set any trigger for this to fire. For this type of JS to work, you will likely need to use a trigger such as

jQuery( document ).ready(function() {
    document.getElementById("defaultOpen").click();
});

so that the code runs when the page loads fully. If you go that route, you'll also need to make sure that you enqueue the script with jQuery as a dependency:

add_action('wp_enqueue_scripts', 'wpse_371294_enqueue_js');
function wpse_371294_enqueue_js() {
    wp_enqueue_script('click-button', get_template_directory_uri() . '/clickbutton.js', array('jquery'), "1.0", true);
}

And on a final note, it's likely you could achieve this same effect with CSS. Have whatever the button does load by default, use CSS to show it rather than hide it, and then if someone clicks to close use CSS to hide. It depends on exactly what you're doing, but there's often a way to avoid running JS for an initial page state.

1
  • Thank you for the answer. Now, it is working. I have added your code in my functions.php and it is working. Thank you. Jul 18, 2020 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.