Clicking the link will also work

4

I always have this doubt, just look:

I have a menu, with ul and li:

<ul>
  <li><a href="/inicio">Inicio</a></li>
  <li><a href="/sobre">Sobre</a></li>
  <li><a href="/contato">Contato</a></li>
</ul>

How do I, when I place or click on li the a link to work? Because, for example, it only works if I click on a , but if I click outside, in this case, in li , it does not work, the a link does not activate.

    
asked by anonymous 14.07.2017 / 15:05

3 answers

1

If you set it in CSS

li a {
   display: block;
} 

The "A" tag is the same as the "LI" width, so everything is linked.

    
14.07.2017 / 20:48
3

Try something like:

$(document).on("click", "li", function() {
  window.location = $(this).find("a").attr("href");
});
ul {
  list-style: none;
}

li {
  width: 100px;
  background: gray;
  margin: 0 0 10px;
  cursor: pointer;
}

li:hover {
  background: yellow;
}

a {
  text-decoration: none;
  margin: 0 0 0 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><li><ahref="/inicio">Inicio</a></li>
  <li><a href="/sobre">Sobre</a></li>
  <li><a href="/contato">Contato</a></li>
</ul>
    
14.07.2017 / 15:09
1

I believe that using JavaScript (and mainly jQuery) to change the natural behavior of the li element is also not the best solution. This is a classic case of delegating a function to an element that is not the right one.

What is the impact of changing the default behavior of an HTML element?

If the event in question will redirect the user to another page, this event must be delegated to the a element and not to the li element. Implementing the second is to break the HTML semantics. Now, if the behavior of the a element is to be applied to the entire li element, the clearest solution is to have the a element occupy the entire li element.

li {
  position: relative;
}

li > a {
  position: absolute;
  width: 100%;
  height: 100%;
}

a:hover {
  background: green;
}
<ul>
  <li><a href="/inicio">Inicio</a></li>
  <li><a href="/sobre">Sobre</a></li>
  <li><a href="/contato">Contato</a></li>
</ul>

It does not hurt HTML semantics and does not use JavaScript.

    
17.07.2017 / 23:22