On Click Event fires only once

Hi Experts,

I have the following code, which works when the documents first loads
$(document).ready(function(){
    
    //Display App't Setter
    $('#aApptSetter').on('click', function(){
       //$('#divNextAppt').css('display', 'none'); 
       $('#divApptSetter').css('display', 'block');
    });
});

Open in new window


However, after I fire the below, the above no longer reacts?
function updateAppt(data){
    
    var gmail_id = data.event_id;
    var appt = data.date + ' at ' + data.time;
    
    var html = "";
    html += "<label>The next appointment for this client is <b>" + appt; 
    html += "</b> Click <a id=\"aApptSetter\">here</a> to change.</label>";
    
    $('#divNextAppt').html(html);
    $('#gmail_id').val(gmail_id);
    
    $('#slots').children().remove();
    $('#weeks').children().remove();
    
    $('#divApptSetter').css('display', 'none');
}

Open in new window


When the document loads, the  original HTML is
<div id="divNextAppt">
                
                                    <label>No upcoming appointments for this client.
                            Click <a id="aApptSetter">here</a> to set.</label>
                    
            </div>

Open in new window


Any help will be appreciated.
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Your Click event is bound to the #aApptSetter when the page first loads, but then you replace the conteint of divNextAppt with new HTML, so you also replace the aApptSetter with a new copy. This new copy doesn't have the event bound to it.

What you need to do is delegate the event binding to the parent DIV (the one that doesn't get replaced):

$('#divNextAppt').on('click', '#aApptSetter',  function() {
...

Open in new window

0
Leonidas DosasCommented:
Encapsulate the event click also into the function scope ie
$(document).ready(function(){
    
    //Display App't Setter
    $('#aApptSetter').on('click', function(){
       //$('#divNextAppt').css('display', 'none'); 
       $('#divApptSetter').css('display', 'block');
    });


function updateAppt(data){
    
    var gmail_id = data.event_id;
    var appt = data.date + ' at ' + data.time;
    
    var html = "";
    html += "<label>The next appointment for this client is <b>" + appt; 
    html += "</b> Click <a id=\"aApptSetter\">here</a> to change.</label>";
    
    $('#divNextAppt').html(html);
    $('#gmail_id').val(gmail_id);
    
    $('#slots').children().remove();
    $('#weeks').children().remove();
    
    $('#divApptSetter').css('display', 'none');
  
     $('#aApptSetter').on('click', function(){
       //$('#divNextAppt').css('display', 'none'); 
      $('#divApptSetter').css('display', 'block');
    });
}

});

Open in new window

0
APD TorontoSoftware DeveloperAuthor Commented:
I’m currently out of my office, but I believe that I tried, same issue.
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Chris StanyonWebDevCommented:
There's absolutely no need to repeat the event binding in the updateAppt() function. All that's needed is to delegate the event, as I've already shown.

You can see it working here -> https://jsfiddle.net/ChrisStanyon/6xzqyx3y/

If you say that doesn't work, then there's something else going on in your code that you're not showing us.
0
APD TorontoSoftware DeveloperAuthor Commented:
Chris, I heard about delegation before.  What is it?
0
Chris StanyonWebDevCommented:
In jQuery, you bind event handlers to elements, such as binding a Click event handler to a Button. Often, this will be Direct binding - you bind the Click event directly to a Button:

$('#someButton').on('click', function() { do something });

Doing this means that firstly, the element needs to already exist when you call that code, and secondly, if you delete that element, you delete the event handler along with it.

To avoid these issues, you can Delegate the event handler - effectively passing off the responsibility for the event to a different element that you know exists and won't be deleted:

$('#someOtherElement').on('click', '#someButton', function() { do something });

This stores the event binding on the #someOtherElement ready to fired by the #someButton element (if and when it exists). You can add and delete #someButton at any time without affecting the event because it's been delegated to #someOtherElement.

Now in your case, you currently use Direct binding to bind the click event to your #aApptSetter element. When you delete the element (by re-creating the HTML), you also delete the event with it, which is why it won't fire a second time.

By delegating the event to #divNextAppt, the event handler won't be deleted when you delete #aApptSetter and will continue to fire, no matter how many times you re-create the element.

:)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.