How to use onload on DIV elements?

Asked

Viewed 651 times

1

I am set some similar functions for different pages on a website. So these functions are in the same file. When the JS file is loaded the functions $(function() { /*function1*/ }); and $(function() { /*function2*/ }); are executed. However, the elements which I pick up via jQuery (Ex.: $('.elem').val();) will not exist as they are on another page.

How do I execute a function only when a determining element is loaded?

  • could post the command calling these functions?

  • There are different ways depending on how elements are added. You can clarify how they "appear" on that page $('.elem')?

2 answers

1

depending on the operations you want to do with the (s) element(s), the ideal is to use $.each so that you can reference each of them with $(this) or with the variables of the parameters.

Ex:

$(".layout_cron").each(function(index, element) {
    if ($(this).data("elemento")) elemento = $(this).data("elemento"); else elemento = "#" + $(this).attr("id");
    cronometro_regressivo($(this).data("agora"), $(this).data("fim"), elemento);
});

HTML

<div id="header_banner_cron" class="layout_cron" data-agora="1407032260" data-fim="1407553140" style="position:absolute;left:197px;top:0px;"></div>

1

One way to know if an element exists with jQuery is to use the length property. $('.elem').length tells you how many elements there are on the page that match the selector .elem.

if( $('.elem').length > 0 ){
   //tem nós da classe elem no documento
}else{
   //nao tem
}
  • Gambiarra Lv. Asian, but it works! XD

  • 1

    Eh, it’s not even that common... it’s the most common way people use to test if an element exists using jquery.

  • Really? Damn it!!! I think it’s something a little common this my problem. I thought there was a more direct solution.

Browser other questions tagged

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