Execute method/function when loading page

Asked

Viewed 2,592 times

1

It’s not duplicate that: How to run a jquery script when loading a page


I have a function that lists a content in div:

function listar() {
    alert("listar"); // alert para saber se está sendo chamado
    arquivo = "lista.php";
    $.ajax({
        url:arquivo,
        success: function (textStatus) {      
            $('#iddiv1').html(textStatus);
        }
    }); 
}

I tried to load this function next to the page, but it doesn’t work:

$(document).ready(function(){
    listar();
});

Also, I would like, while running the method listar(), be hidden from div.

Example:

$('#iddiv1').hide();
$('#iddiv2').show();

I tried so, but unsuccessfully:

$('#iddiv1').load(function() {
    $('#iddiv1').hide();
    $('#iddiv2').show();
});
  • Pq does not create the function already inside the Document.ready?

  • @Leandrade Isn’t the example I tried? Or is it wrong?

  • 1

    Is loading jQuery before calling the $(document).ready(function(){? If not, you probably have an error on the console.

  • @sam to <script> of the function is in the <head> and the <script> jquery, at the end of the <body>... The order has to be reversed?

  • @sam is just... carrying!

  • 1

    You can leave in the order you want to change the $(document).ready(function(){ for document.addEventListener("DOMContentLoaded", function(){

Show 1 more comment

1 answer

2


It’s probably calling the event $(document).ready(function(){ before loading jQuery, and with that resulting in error, as the $(document).ready is a jQuery event.

In this case you have 2 alternatives:

Or call the $(document).ready(function(){ after the <script> which loads jQuery (after does not mean shortly after. After anywhere, as long as it’s after):

<script src="jquery.js"></script>
<script>
$(document).ready(function(){
    listar();
});
</script>

Or use the native Javascript event anywhere in the code, before or after you load jQuery:

<script>
document.addEventListener("DOMContentLoaded", function(){
   listar();
});
</script>

The method .load() is used to load HTML content to an element (a div, for example), not to detect page loading.

In this case you can execute the code after the return of Ajax, on success::

success: function (textStatus) {      
   $('#iddiv1').html(textStatus).hide();
   $('#iddiv2').show();
}
  • The sam, and the div’s Hide/show ?! I open another question?

  • Updated response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.