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

Stopping an Ajax Request in RichFaces

Having trouble canceling an Ajax Request in our RF-built application interface. The progress bar modal should have a cancel button to interrupt the current operation, such as cancelling filling controls from the database. How can this be achieved? I&apos ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

When the session times out, Ajax mistakenly displays the login page instead of an error message

I have a question that is somewhat similar to this one, but I will explain my understanding of the situation and the ideas I have come up with to fix it. Hopefully, someone can guide me in the right direction. The scenario: In my webapp, an authenticated ...

The method mongoose.connect() is not defined

Having a bit of trouble connecting to my MongoDB using Mongoose - keep getting this error. const { mongoose } = require('mongoose'); const db = 'dburl.com/db' mongoose.connect(db, { useNewUrlParser: true }) .then(() => console ...

How can I show a loading screen while making a synchronous AJAX call in Chrome?

Is there any method to show a loading screen in Chrome while using async:false in an AJAX call? The use of setTimeout poses several challenges when making multiple synchronous AJAX calls within the setTimeout function. Additionally, the loading indicator ...

Loss of styling is observed with jQuery's html() function

Here is the HTML code I am working with: <div class="myList"> <select> <option value="1">Item1</option> <option value="2">Item2</option> </select> </div> Everything looks great in terms of CS ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Refresh the content with an embedded iframe

I am attempting to update the body content by removing all existing content and inserting an iframe: function create_custom_iframe(target){ var iframe = document.createElement('iframe'); iframe.setAttribute('id', 'target_u ...

Calendar: Display upcoming dates within the next week starting from the current week

Hey there! I have a calendar that includes next and previous buttons. When the user clicks on the next button, the schedule for the upcoming week will be displayed. However, if the user clicks again, nothing happens. My goal is to only show dates for the n ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Unlocking the secrets of capturing key presses before submitting with jQuery

I'm seeking help with creating an app that scans a barcode and displays the data on screen. I prefer not to use textboxes in order to prevent data editing. Currently, I have set up the enter key to be automatically sent at the end of the barcode scan ...

The jQuery Mobile framework fails to initialize when loading data from an AJAX request in JSON format

I'm currently attempting to incorporate the jQuery Mobile 'styles' (specifically for buttons) into my project. Below is the HTML code snippet I am using (with Ajax): <!-- Using local jQuery + Mobile files --> <link rel="stylesheet ...

Steps to integrating an interface with several anonymous functions in typescript

I'm currently working on implementing the interface outlined below in typescript interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...m ...

Guide for setting up a React infinite scroll feature in a messaging app similar to Facebook Messenger

I have been exploring various questions regarding React infinite scroll, but I am looking to delve deeper in order to discover the most effective solution available for implementing such a component. Currently, I am working on a chat application and have ...

Extracting data from a JSON object using Angular

Recently, I've been delving into the world of AngularJS and encountered a hurdle with LocalStorage. After spending numerous hours trying to figure out how to save data locally, I believe I have finally got it working as intended. Now, my next challeng ...

Send form without reloading the page (partially updating the page)

Code snippet in index.php HTML head: <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> <script> // Ensurin ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...

How can real-time data be fetched or connected to Firebase v9 in the onSubmit function?

Please provide the code in firebase-v9 to fetch the onSubmit function from firestore: const onSubmit = (formData) => { console.log(formData) db.collection('emails').add({ to: formData.to, subject: formData.subject, message: formData.mess ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Tips for showcasing JSON data within an array of objects

I'm trying to work with a JSON file that has the following data: {"name": "Mohamed"} In my JavaScript file, I want to read the value from an array structured like this: [{value: "name"}] Any suggestions on how I can acc ...