Text appears fast

Asked

Viewed 92 times

3

The page is running all right, but when I click on the menu it displays the text very fast and then deletes.

Could someone give me a light why the text disappears after the click?

window.addEventListener('DOMContentLoaded', (event) => {

  var formacao = document.getElementById("formacao");
  var experiencia = document.getElementById("experiencia");
  var habilidade = document.getElementById("habilidade");
  var objetivo = document.getElementById("objetivo");

  objetivo.addEventListener('click', (event) => {
    let objeto = document.getElementById("menu")
    objeto.innerHTML = ("<h2>Objetivo</h2><p>Conseguir um emprego de estagio ou júnior na área de programador front-end.</p>")
  });
  formacao.addEventListener('click', (event) => {
    let objeto = document.getElementById("menu")
    objeto.innerHTML = ("<h2>Formação</h2><p>Graduação em Analise em Desenvolvimento de Sistemas. Previsão de termino: 2020/2</p>")
  });
  experiencia.addEventListener('click', (event) => {
    let objeto = document.getElementById("menu")
    objeto.innerHTML = ("<h2>Experiencia</h2><p><strong>Vennar Burger Empresário (Mei)</strong></p><p>Administração de uma pequena de empresa de hamburguer com 3 funcionários</p>")
  });
  habilidade.addEventListener('click', (event) => {
    let objeto = document.getElementById("menu")
    objeto.innerHTML = ("<h2>Habilidade</h2><ul><li>JavaScript</li><li>Html5</li><li>CSS3</li><li>Node</li><li>Postregresql</li><li>Mysql</li></ul>")
  });

  console.log('DOM fully loaded and parsed');
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Romulo Lessa Developer</title>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="index.css">
</head>

<body onload="">
  <header>
    <nav>
      <!--Menu-->
      <ul>
        <li id="objetivo">
          <a href="">Objetivo</a>
        </li>
        <li id="formacao">
          <a href="">Formação</a>
        </li>
        <li>
          <a href="">Portifolio</a>
        </li>
        <li id="experiencia">
          <a href="">Experiencias</a>
        </li>
        <li id="habilidade">
          <a href="">Habilidades</a>
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section>
      <div id="menu"></div>

      <!--Conteudo Sobre min-->
    </section>
  </main>
  <footer>
    <!--Roda pe com contatos: github, linkedin, facebook, twitter, email-->
  </footer>
  <script defer src="script.js"></script>
</body>

</html>

2 answers

2


The problem is because by clicking on a list item, its anchor <a href=""> associated redirects the browser to a blank page(about:blank) right after the content of <div id="menu"> be loaded via Listener.

One way to solve it is in itself HTML causing the anchorage do not redirect the browser using the hashtag(#)

<a href="#">

Another way to solve is in javascript using the method Event.preventDefault() informing the browser that the event click no longer needs to be processed.

I gave a simplified in your example leaving only two cases one using <a href="#"> and another with preventDefault():

window.addEventListener('DOMContentLoaded', (event) => {

  let formacao = document.getElementById("formacao");
  let objetivo = document.getElementById("objetivo");

  let objeto = document.getElementById("menu")

  objetivo.addEventListener('click', (event) => {
    event.preventDefault(); // Aqui informa ao navegador que o evento não precisa mais ser processado.
    objeto.innerHTML = ("<h2>Objetivo</h2><p>Conseguir um emprego de estagio ou júnior na área de programador front-end.</p>")
  });

  formacao.addEventListener('click', (event) => {
    objeto.innerHTML = ("<h2>Formação</h2><p>Graduação em Analise em Desenvolvimento de Sistemas. Previsão de termino: 2020/2</p>")
  });


  console.log('DOM fully loaded and parsed');
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Romulo Lessa Developer</title>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="index.css">
</head>

<body onload="">
  <header>
    <nav>
      <!--Menu-->
      <ul>
        <li id="objetivo">
          <a href="">Objetivo</a>
        </li>
        <li id="formacao">
          <!-- O atributo href="#" previne que o link direcione a para about:blak-->
          <a href="#">Formação</a>
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section>
      <div id="menu"></div>

      <!--Conteudo Sobre min-->
    </section>
  </main>
  <footer>
    <!--Roda pé com contatos: github, linkedin, facebook, twitter, email-->
  </footer>
</body>

</html>

  • I’d like to know what it’s like to get a negative response?

-1

welcome to the stackoverflow!

The riddle that is passing unnoticed by your eyes is as follows:

window.addEventListener('DOMContentLoaded', (event) => {...

But why RXSD?

This command line adds a Listener, or rather, a listener to your page. It’s as if this piece of code is waiting for some function, in your case, the HTML to be fully executed Domcontentloaded, in order to be activated, which in your case would not be the interesting (since you want to treat only the home menu item click, right?). Faced with this, we face the following situations:

  1. Your code will pass through this Javascript code sempre that the page is rendered, I don’t know if you noticed, but when clicking on an item <a> no directing URL href="" from the menu, your page is running a Reload going through what I explained earlier.
  2. Note that the tag <a> needs a href(this attribute specifies the URL of the page to which the link will redirect, as you are using the empty attribute, the page is making a refresh and consequently falling in situation 1), however, there are some tricks that you can use as for example use the Wire # as a href parameter, thus you are telling the browser that your link will move the scroll from your page to the top, avoiding your Reload, gives a little peek that has a nice content.

You can use your code as follows:

  document.querySelector("body").addEventListener('click', function(e) {
  var anchor = e.target.closest('a');
  if(anchor !== null) {
    var formacao = document.getElementById("formacao");
	var experiencia = document.getElementById("experiencia");
	var habilidade = document.getElementById("habilidade");
	var objetivo = document.getElementById("objetivo");

	  objetivo.addEventListener('click', (event) => {
		let menu= document.getElementById("menu")
		menu.innerHTML = ("<h2>Objetivo</h2><p>Conseguir um emprego de estagio ou júnior na área de programador front-end.</p>")
	  });
	  formacao.addEventListener('click', (event) => {
		let menu= document.getElementById("menu")
		menu.innerHTML = ("<h2>Formação</h2><p>Graduação em Analise em Desenvolvimento de Sistemas. Previsão de termino: 2020/2</p>")
	  });
	  experiencia.addEventListener('click', (event) => {
		let menu= document.getElementById("menu")
		menu.innerHTML = ("<h2>Experiencia</h2><p><strong>Vennar Burger Empresário (Mei)</strong></p><p>Administração de uma pequena de empresa de hamburguer com 3 funcionários</p>")
	  });
	  habilidade.addEventListener('click', (event) => {
		let menu= document.getElementById("menu")
		menu.innerHTML = ("<h2>Habilidade</h2><ul><li>JavaScript</li><li>Html5</li><li>CSS3</li><li>Node</li><li>Postregresql</li><li>Mysql</li></ul>")
	  });

	  console.log('DOM fully loaded and parsed');
  }
}, false);
  <header>
    <nav>
      <!--Menu-->
      <ul>
        <li id="objetivo">
          <a href="#">Objetivo</a>
        </li>
        <li id="formacao">
          <a href="#">Formação</a>
        </li>
        <li>
          <a href="#">Portifolio</a>
        </li>
        <li id="experiencia">
          <a href="#">Experiencias</a>
        </li>
        <li id="habilidade">
          <a href="#">Habilidades</a>
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section>
      <div id="menu"></div>

      <!--Conteudo Sobre min-->
    </section>
  </main>
  <footer>
    <!--Roda pe com contatos: github, linkedin, facebook, twitter, email-->
  </footer>

Notice that right now, we’re not adding one Listener for whenever there is a page load/Reload, now we are waiting only click of one of the anchored items <a>.

document.querySelector("body").addEventListener('click', function(e) {...

Remember that the href’s are using the # only to avoid page reload.

And don’t forget to treat the item • Portifolio ein?!

  • That answer is wrong, DOMContentLoaded and triggered once when the initial HTML document was fully loaded and parsed, without waiting for style sheets, images and sub-frames to complete the upload. That is after the DOM tree is built and made available and has nothing to do with reloads. The installation of event observers within that event DOMContentLoaded aims to safeguard the installation of listeners of other scripts by making dynamic changes to the DOM during loading...

  • ... something else, the way it’s doing, every click is unnecessarily reinstalling all event observers. To check is simple on the first line of your callback to body put Alert("xxxxxxxx"); and any click of der on the links or anywhere on the page the alert will appear indicating that every click all the listeners are being re-registered.

  • Are you saying that Domcontentloaded is triggered only once, in the way that is implemented by Romulo? For this is very simple, just add a breakpoint in your Javascript, you will see that the code will fall there 1x, in the page load. 2x at the click of the item, 3x at the page Reload. You can understand what I mean by Reload?

  • But this is default behavior, an event call to a DOM payload. The only mistake he made was pointing the links to about:Lank to fix just do '<a href="#">' on all links

  • In your case every click all listeners are reinstalled , so much so that the line console.log('DOM fully loaded and parsed'); is persistently evoked at each click.

  • Guy the console is being called only on the clicks of menu items...

  • If this happens it is because all the code that accompanies this call is also being executed (resettlement of listeners).

  • You can demonstrate that statement " so much so that the console.log line('DOM Fully Loaded and Parsed'); is persistently evoked at each click. " visually?

  • You are already looped just create an https://imgur.com/a/sRgVMWLcounter

  • or else run your code in the sandbox and press for several times any of the items until the screen is covered by the phrase DOM fully loaded and parsed

  • There’s another mistake I realized now, the first time I click on any of the items the menu.innerHTML is not completed only is completed from the second click on.

Show 6 more comments

Browser other questions tagged

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