message : "div is not defined"

Asked

Viewed 110 times

0

I have a function to hide a div and open the data with a href. It works in another form normally, but does not work in this form I need it to work, it returns me the following error:

message : "div is not defined"

Follows the function:

window.onload = function() {
  // Localiza o elemento
  var div = document.getElementById('minha_div');
  // Esconde a DIV
  div.style.display = 'none';
  // O link
  var clique = document.getElementById('clique');

  // Captura o evento de clique no link
  clique.onclick = function() {
    alert('clique');
    // Verifica se getComputedStyle é suportado
    if ('getComputedStyle' in window) {
      var display = window.getComputedStyle(div).display;
    } else {
      // Obtém a opção display para navegadores antigos
      var display = div.currentStyle.display;
    }

    // Verifica se display é none
    if (display == 'none') {
      // Muda para display block
      div.style.display = 'block';
    } else {
      // Muda para display none
      div.style.display = 'none';
    }

    // Retorna falso para não atualizar a página
    return false;
  }
}

html:

<span class="fundo_clique">
    <a href="#" id="clique">Para configurar as mensagens, clique aqui!</a>
</span>
<br />
<%-- MODAL FINANCEIRO LANÇAMENTO DE CONTAS --%>
<span id="minha_div" style="border: none" runat="server">*conteúdo*</span>

I believe that the problems are in the references, because in another form that does not need these references works, and in this I need these:

<link rel="stylesheet" href="css/mobile/pessoas_small_1366.css" />
<script type="text/javascript" src="javascript/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" />
<script src="javascript/pessoa.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" />

But every time I change, the same thing happens.

What can it be?

  • 1

    problem seems to be that you set the variable div in the page load when it is possible that there is no div yet. How to use global variables in this way is not recommended. Try moving getelement into the function or create a function that returns that div and use it

  • This function of yours is declared where? Your problem is probably that you are performing this function before the minha_div exist

  • @Jean I managed to solve this way, I changed and it worked, thank you.

4 answers

4

First problem (unrelated), has two jQuerys no need:

<script type="text/javascript" src="javascript/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Either use one or use another

Second, the error does not seem to be in the code described above, because even if the element does not exist on the page the error that occurred would be something like:

Cannot read Property 'style' of null

Already the mistake

is not defined

It occurs when there is no variable in the scope of a function, so you probably have some other variable div in another script, that is to say $.ready and window.onload has nothing to do with the solution, the problem IS THE SCOPE variable access.

  • I do not understand why from DOWNVOTE, I explained the difference between both error messages, it is obvious that the error has no way to be solved, because the problem is elsewhere, what I did was to answer within the possible, explain that it is the access SCOPE, i.e., the variable was created in one scope and the AP is trying to access in another.

  • sorry guy would vote , and I ended up giving donwvote, his response was very good, I just edit

  • @Marcelobatista can leave so, it can also be what Paulohdsouza said. I just wanted to know if I had confused something. Thanks anyway for the return ;)

  • No expensive mistake was mine, I read your reply adequeda by signal and I ended up erring, better as learning, pay attention to vote

  • 1

    Haha that hilarious, I was going to answer exactly the same thing in view of the scope of var not being part of the scope of click function, I was sure of that, but then I saw that the variable was accessed and I was very confused, in the end I wasn’t sure and I just commented on the question. But I didn’t imagine that another variable div could be accessed instead of desired. It’s like learning to when I doubt myself to make sure there’s no chance that something outside is getting in the way :P

1

Simple, you’re with the div RUNAT=SERVER , soon the ID will change why this div wheel server side, try to catch by the class

 <span class="minha_div" id="minha_div" style="border: none" runat="server">*conteúdo*</span>

And in your . js

$(document).ready(function(){
  var minhaDiv = $('.minha_div'); 
});
  • I think you killed the puzzle, but you don’t need to select a class, just change the selector to consider the suffix of the attribute, $("[id*='my_div']")

  • May also.

0

Since you are including Jquery try this:

$(document).ready(function(){
  var div = $('#minha_div');
  div.css( "display", "none" );
  resto do seu código....   
});

Remove your onload and try $(Document). ready

The difference is that the div will only be hidden when the DOM is all read. Then it is called this function by callback that hides its element. callback will prevent the function from running before html is all loaded in the browser since javascript is an asynchronous language.

What Are Asynchronous Flows?

Even if designed to have a single execution flow, some tasks of your Javascript program can be executed without interfering with the main code execution flow. These tasks are known as asynchronous flows. You can fire a series of these tasks without waiting for each one to complete to proceed. On current computers, which have more than one processing core, some tasks within the scope of your program can even be performed at the same time as your code.

0

If you use multiple libraries (jQuery, Bootstrap and other related libraries), it would make more sense for you to use jQuery itself to simply show and hide the div, drastically reducing the code, and not even needing to do compatibility check with if ('getComputedStyle' in window).

Moreover, with the code below suggested, no error will be returned in relation to the div (at least in the example given in the question), with functions and variables within $(window).on('load', function(){ will only be invoked after page loading.

See that with only 9 lines with jQuery, you can do the same thing you want to do with more than 20 lines javascript:

$(window).on('load', function(){
   var div = $('#minha_div'); // Localiza o elemento
   div.hide(); // Esconde a DIV
   $('#clique').click(function(e){ // Captura o evento de clique no link
      alert('clique');
      div.is(':visible') ? div.hide() : div.show(); // pega o estado da div e mostra/esconde
      e.preventDefault();
   });
});

Example:

$(window).on('load', function(){
   var div = $('#minha_div'); // Localiza o elemento
   div.hide(); // Esconde a DIV
   $('#clique').click(function(e){ // Captura o evento de clique no link
      alert('clique');
      div.is(':visible') ? div.hide() : div.show(); // pega o estado da div e mostra/esconde
      e.preventDefault();
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="fundo_clique">
   <a href="#" id="clique">Para configurar as mensagens, clique aqui!</a>
</span>
<br />
<span id="minha_div" style="border: none" runat="server">*conteúdo*</span>

Browser other questions tagged

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