John Davidson

javascript - js to communicate with dom in wordpress

0 comments
Message:


I am trying to listen to a click event of a link using javascript inside a wordpress project. But I could notice, NodeList is getting empty. Seem to be it's having an issue when communicating with the DOM. My attempt is as below. I created a folder called theme and inside the index.php there, below lines were added.


<?php get_header(); ?>
<a href="#" class="btn btn-next width-50 ml-auto">Next1</a>
<a href="#" class="btn btn-next width-50 ml-auto">Next2</a>

Then inside the functions.php file imported the external scripting file as below.


<?php
function pet_data1(){
wp_enqueue_script('pet_adoption_style1',
get_stylesheet_directory_uri().'/script.js', array(), false, false);
}
add_action('wp_enqueue_scripts', 'pet_data1');
?>

Next the header.php file takes as below.


<!DOCTYPE html>
<html lang="en">
<head>
<?php wp_head();?>
</head>
</html>

Finally, script.js file which is not given the expected output is as in below.


const nextBtns = document.querySelectorAll(".btn-next");
console.log("nextBtns",nextBtns)

When I print the nodeList, length is zero. But there should be 2 nodes which contains the btn-next class. So I think there should be an issue with wordpress structure which I have followed. Since I am new to wordpress, I need your support to fix this out.



My Answer:
To listen to a click event of a link using JavaScript inside a WordPress project, you can follow these steps:

1. Create a JavaScript file in your theme folder. Let's name it `custom.js`.

2. Add the following code to your `custom.js` file:

javascript
document.addEventListener('DOMContentLoaded', function() {
var links = document.querySelectorAll('a');

links.forEach(function(link) {
link.addEventListener('click', function(event) {
event.preventDefault();
console.log('Link clicked!');
});
});
});


3. Enqueue the JavaScript file in your `functions.php` file by adding the following code:

php
function enqueue_custom_scripts() {
wp_enqueue_script('custom-script', get_template_directory_uri() . '/custom.js', array(), '1.0', true);
}

add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');


4. Save the changes and refresh your WordPress site. Now, when you click on any link on your site, you should see the message "Link clicked!" in the console.

By following these steps, you should be able to listen to click events of links using JavaScript in your WordPress project.

Rate this post

5 of 5 based on 5230 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us