Width of an element calculated with jQuery

2

I want the following. When I hover over li , the topoMenuBarra div is no longer display:none to be display:block , and the width of the div is equivalent to a that exists within li .

It is taking as width li . I've already reported $( ".topoMenu li a" ).hover(function() without a and it does not work.

$(document).ready(function(){

	$( ".topoMenu li a" ).hover(function() {
		var $this = $(this);
		var largura = $this.width();
		$( this ).find('.topoMenuBarra').css({
			'display':'block',
			'width': largura + 'px'
		});
	},
	function() {
		$( this ).find('.topoMenuBarra').css('display','none'); /*fazer barra desaparecer*/
	});

});
.topoMenu li {
    font: 300 20px/20px'Ubuntu', sans-serif;
    color: #fff;
    float: left;
}
.topoMenu li img {
    margin-right: 95px;
    margin-top: 44px
}
.topoMenu li a {
    margin-top: 62px;
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
}
.topoMenuBarra{
height: 2px;
background-color: #ced1d7;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><li><ahref="/empresas">empresa</a>
	<div class="topoMenuBarra"></div>
</li>
    
asked by anonymous 18.11.2014 / 20:11

1 answer

3

Your problem is to be using .find() looking for descendants of this . If you use .next() it will work because topoMenuBarra is not descended from the acora but rather sibling. (already .siblings() would also work).

jsFiddle: link

Use like this: $this.next('.topoMenuBarra').css({

Example with jQuery:

$(document).ready(function(){

	$( ".topoMenu li a" ).hover(function() {
		var $this = $(this);
		var largura = $this.width();
		$this.next('.topoMenuBarra').css({
			'display':'block',
			'width': largura + 'px'
		});
	},
	function() {
		$(this).next('.topoMenuBarra').css('display','none'); /*fazer barra desaparecer*/
	});

});
.topoMenu li {
    font: 300 20px/20px'Ubuntu', sans-serif;
    color: #fff;
    float: left;
}
.topoMenu li img {
    margin-right: 95px;
    margin-top: 44px
}
.topoMenu li a {
    margin-top: 62px;
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
}
.topoMenuBarra{
height: 2px;
background-color: #ced1d7;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><ulclass="topoMenu">
<li>
    <a href="/empresas">empresa</a>
	<div class="topoMenuBarra"></div>
</li>
</ul>

In fact this can only be done with CSS and you do not need the div below.

You only need: link

.topoMenu a:hover {
   border-bottom: 4px #bbbbbb solid;
}
    
18.11.2014 / 20:28