How to ensure that an element will have the DOM event?

1

Good afternoon,

Today I'm facing a rather strange bug in my application:

I have a field of type textarea where I type an email body and just under it a button that when clicked gets textarea content, opens a modal and inserts the same content inside the modal body .

The issue is that some users are reporting that the button opens the modal but does not insert the value of the textarea into it.

When analyzing this question I identified that it is not always that this occurs, when it gives problem, if you refresh the page the function tends to work.

When it gives an error, when I inspect the button click events, I realize that it has been replaced by a BootStrap JS function or simply no other function is replaced.

How can I make sure this does not happen?

  $('#btnPreviewEmail').click(function(){
  var assunto  = $('#txtAssuntoEmail').val();
  var texto    = CKEDITOR.instances['txtAreaCorpoDoEmail'].getData();
  var namepage = 'Campanha Marketing Lojas Uno';
  var landing  = buscaLandingPorNamePage(namepage);
  assunto = assunto.replace(/{{.FirstName}}/g, "Renoir dos Reis");
  assunto = assunto.replace(/{{.DataHoje}}/g, '31/10/2016');
  texto   = texto.replace(/{{.FirstName}}/g, "Renoir dos Reis");
  texto   = texto.replace(/{{.Tracker}}/g, "");
  texto   = texto.replace(/{{.URL}}/g, landing);
  texto   = texto.replace(/{{.DataHoje}}/g, '31/10/2016');
  $('#containerAssunto').html(assunto);
  $('#containerPreview').html(texto);
});

Button code that opens the modal:

<button type="button" class="btn btn-warning" id="btnPreviewEmail" data-toggle="modal" data-target="#modalPreview">Pre-visualizar</button>

Modal:

    
asked by anonymous 31.10.2016 / 19:56

1 answer

4

Have you tried using the click event this way?

$(document).on("click", "#btnPreviewEmail", function(){
    /*Seu Código*/
});

The code should be outside the PageLoad of the script.

Difference between .on("click") and .click() -

.on("click") :

  • It can work dynamically with elements that have been created from later on the page.
  • Is only loaded when the event is triggered.
  • It should be used in a parent element, which is in the page since PageLoad, to fetch from it the element that will be created dynamically (so $(document).on() and not $('#btnPreviewEmail').on()

.click()

  • Can not be fired if you have created an element later on your page.
  • Is loaded even if the element is not fired.

More details: Reference in English

I hope I have helped.

    
31.10.2016 / 20:27