Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out.

You can find the page I am referring to at:

The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script:

$("a.view-more").bind('click',function(event){
          event.preventDefault();
          if($('.post-holder').hasClass('ingredients')) { posttype = 'ingredient'; }
          if($('.post-holder').hasClass('recipe')) { posttype = 'recipe'; }
          if($('.post-holder').hasClass('cmed')) { posttype = 'cmed'; }
          filter = 'none';
          morePosts(posttype,filter);
      });
      

The functionality for allowing users to vote is handled by this code snippet:

$.post('http://taste.fourseasons.com/wp-admin/admin-ajax.php', data,
           function(response){
                   if(response!="-1") {
                           el.find('.vote-sm').removeClass('vote-sm').addClass('unvote-sm');
                           el.find('.vote-text').html("VOTED");
                           el.unbind("click");
                           if(response!="null") {
                                   el.find(".vote-count").html(response);
                           }
                           var cookie = getCookie("better_votes_"+postID);
                           if(!cookie) {
                                   var newcookie = postID;
                           } else {
                                   var newcookie = postID;
                           }
                           setCookie("better_votes_"+postID, newcookie, 365);
                   } else {
                   }
           });
           return false;
   });
    

However, when a user clicks "show more" and new elements are added to the DOM, the voting options do not work with these new elements. I assumed that combining them would solve the issue:

$("a.view-more").bind('click',function(event){
        event.preventDefault();
        if($('.post-holder').hasClass('ingredients')) { posttype = 'ingredient'; }
        if($('.post-holder').hasClass('recipe')) { posttype = 'recipe'; }
        if($('.post-holder').hasClass('cmed')) { posttype = 'cmed'; }
        filter = 'none';
        morePosts(posttype,filter);

        $(".vote").bind('click',function(event) {
               event.preventDefault();
               postID = $(this).attr('data-post');
               var el = $(this);
               //el.html('<span id="loader"></span>');
               var nonce = $("input#voting_nonce_"+postID).val();
               var data = {
                       action: 'add_votes_options',
                       nonce: nonce,
                       postid: postID,
                       ip: '66.252.149.82'                        
               };
               $.post('http://taste.fourseasons.com/wp-admin/admin-ajax.php', data,
               function(response){
                       if(response!="-1") {
                               el.find('.vote-sm').removeClass('vote-sm').addClass('unvote-sm');
                               el.find('.vote-text').html("VOTED");
                               el.unbind("click");
                               if(response!="null") {
                                       el.find(".vote-count").html(response);
                               }
                               var cookie = getCookie("better_votes_"+postID);
                               if(!cookie) {
                                       var newcookie = postID;
                               } else {
                                       var newcookie = postID;
                               }
                               setCookie("better_votes_"+postID, newcookie, 365);
                       } else {
                       }
               });
               return false;
       });
    });

Unfortunately, this approach does not seem to work and creates a situation where two votes are added instead of one every time a vote is cast.

I appreciate any assistance provided.

This code belongs to the wp-function page:

function add_votes_options() {
    $postid = $_POST['postid'];
    $ip = $_POST['ip'];

    if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce_'.$postid))
        return;

    $voter_ips = get_post_meta($postid, "voter_ips", true);
    if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
        echo "null";
        die(0);
    } else {
        $voter_ips[] = $ip;
        update_post_meta($postid, "voter_ips", $voter_ips);
    }   

    $current_votes = get_post_meta($postid, "votes", true);
    $new_votes = intval($current_votes) + 1;
    update_post_meta($postid, "votes", $new_votes);
    $return = $new_votes>1 ? $new_votes : $new_votes;
    echo $return;
    die(0);
}

Answer №1

Encountering a common issue with event binding is not uncommon.

$("a.view-more").bind('click',function(event){

The code you've written above attaches an event listener to the DOM elements present at that time. As a result, any new elements added to the DOM do not respond to the event because they lack the attached event listener.

To address this issue, we can utilize event delegation. This involves attaching the event to a parent element of the desired DOM elements. When the event propagates to the parent, we can determine which child triggered the event originally.

jQuery simplifies this process. While you can use the delegate() method, opting for the on() method is recommended as it handles all event operations in jQuery. Other methods like click(), mouseover(), and bind() are just aliases of on().

To delegate an event, you need to specify a selector for the parent where the event will be attached and a selector for the targeted elements. The code snippet will then appear as follows:

$("body").on('click', "a.view-more", function(event){

It's advisable to use something more specific than body in practice, but this serves as a simple example.

For further information, refer to: http://api.jquery.com/on/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic route fails to return value for ID search

Currently, I am testing by creating an array of users containing their respective IDs and names. There is also a button that triggers an onclick function to add the element's ID to the page's URL in order to establish a dynamic route. However, wh ...

The issue of 'MessageChannel not defined' arises specifically on web pages that have implemented reCaptcha v2

I am currently working on scraping some websites that have implemented reCAPTCHA, but I keep encountering an error when loading the page's source: (node:15536) UnhandledPromiseRejectionWarning: ReferenceError: MessageChannel is not defined. Despite a ...

What could be the reason for the malfunctioning of this JavaScript code?

Regarding the content found in this post: How to display a loading image while the actual image is downloading. I have implemented the following code snippet, however, I am facing an issue where the #loader_img element does not hide. Additionally, I would ...

Produces consistent results despite variations in tag names within the DOM

While iterating over each element (post) in an array, I have assigned each HTML tag name a value of post._id. In the DOM, the outputs have different values as expected. However, when I try to capture these values in the React Profile component, the console ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...

Having issues with uploading an image through a popup form in PHP

I am facing an issue with a popup form that I am submitting using AJAX and PHP. Although the form is successfully submitted, the script is not uploading or inserting the picture name into MySQL. Interestingly, when I use the same script without the popup ...

Generating a USA map with DataMaps in d3jsonData

I'm trying to create a basic US map using the DataMaps package and d3 library. Here's what I have attempted so far: <!DOCTYPE html> <html> <head> <title> TEST </title> <script src="https://d3js.org/d3.v5.js"> ...

Error message: The name of the variable is not defined - Attempting to transfer an array from a Ruby file to

We utilize a Mysql database and haml files for our project. Currently, we are facing an issue when dynamically generating a table with data from the mysql database. It triggers this error: NameError - undefined local variable or method `allsites' fo ...

Serializing intricate objects using JavaScript

I'm curious if there are any options outside of npm for serializing complex JavaScript objects into a string, including functions and regex. I've found a few libraries that can do this, but they all seem to depend on npm. Are there any good seri ...

React Tetris game always returns false in its function

Within my react project, I am working with a 2D array containing numbers. I have implemented a function called collisionCheck that iterates through the array to check for specific values. My goal is for this function to return true and exit when it encou ...

Error: The property 'scrollIntoView' cannot be read because it is null

class MessageApp extends Component { constructor(props) { super(props) this.state = { text: "", messages: [] } } componentDidMount() { const config = { apiKey: "<api-key>", authDomain: "<projec ...

Jasmine Timeout issue

Currently, I am in the process of writing a karma unit test script. Everything seems to be going smoothly, but unfortunately, I am encountering an error: Chrome 39.0.2171 (Windows 7) Unit: common.services.PartialUpdater Should be loaded with all dependenc ...

Detecting the preferential usage of -webkit-calc instead of calc through JavaScript feature detection

While it's commonly advised to use feature detection over browser detection in JavaScript, sometimes specific scenarios call for the latter. An example of this can be seen with jQuery 1.9's removal of $.browser. Despite the general recommendatio ...

How to directly stream a Google Cloud Storage file into an fs.Readstream without the need to save it

Is there a way for me to send a video file directly from Google Cloud Storage to an API that only accepts fs filestreams without having to download and save the file locally first? I'm currently using the code below to send video files, but it require ...

Vertically align the left div in the center, while maintaining the standard alignment of the right div

I have been experimenting with Bootstrap 4 and attempting to implement the Vertical alignment feature as outlined on the webpage: https://getbootstrap.com/docs/4.0/layout/grid/ Despite reviewing my code multiple times, I am unable to identify the mistake ...

Adjust the form action and text input name according to the selected radio input

Seeking assistance with the following code, can someone help? $(document).ready(function() { $('#searchform').submit(function() { var action = ''; if($('.action_url').val() == 'l_catalog') { ...

Displaying Array Information in JavaScript

After spending a significant amount of time searching online, I have not been able to find a working solution to achieve what I need. Essentially, I am making an AJAX request that executes a database query and then outputs the results using echo json_enco ...

Isolating JavaScript Ajax codes in a Laravel 8 js file results in functionality issues

Having recently delved into the world of Ajax, I've encountered some issues. Allow me to do my best in explaining the problem at hand. Currently, I'm engaged in a Laravel 8 project. In this project, users are given the choice to select an image, ...

Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt. Any bright ideas or sugges ...

Unable to integrate bower with gulp for automation

I am trying to get gulp to run the installation of all files listed in my bower.json. However, despite writing the code below, it is not working and I'm not seeing any errors. What could be causing this issue? var gulp = require("gulp"); var bower = ...