Search code examples
phphtmlwidth

related width of two elements


I want to relate the width of two elements, the first is a simple div, the second is a span.

<div id="wb_Name_To_Menu" style="position:absolute;left:768px;top:20px;width:171px;height:18px;z-index:4;">
<span id="sp_Name_To_Menu" style="color:#FF0000;font-family:Arial;font-size:16px;">Love Me!</span></div>    
<div id="Layer_to_mainu" style="visibility: hidden;position:absolute;text-align:left;left:772px;top:22px;width:132px;height:135px;z-index:132;" title="">
    <div id="wb_main_mainu" style="position:absolute;left:8px;top:9px;width:123px;height:28px;z-index:1128;padding:0;">
    <div id="main_mainu">
    <ul style="display:none;">
    <li><span></span><span id="id_full_name_from_main_menu">love&nbsp;Meeeeee</span>
    <ul>
    <li><span></span><span>Account&nbsp;Sitting</span></li>
    <li><span></span><span>Help</span></li>
    <li><span></span><span>Log&nbsp;Out</span></li>
    </ul>
    </li>
    </ul>
    </div> 

in JavaScript:

$(document).ready(function(){
  $("#wb_Name_To_Menu").hover(function(){ 
    $("#Layer_to_mainu").css("visibility","visible");  
    $("#Layer_to_mainu").css("width",$("#id_full_name_from_main_menu").width()+"px");
  });
});

$(document).ready(function(){
  $("#Layer_to_mainu").mouseleave(function(){
    $("#Layer_to_mainu").css("visibility","hidden");
  });
});

it doesn't work! and I know the cause: it is caused by $("#id_full_name_from_main_menu").width() which results in a null value!


Solution

  • $("#id_full_name_from_main_menu").width() returns 0 because its ancestor <ul> has display:none set. To read the width you might want to just remove that attribute, or you could temporarily change it in the js, depending on what you're trying to do

    $(document).ready(function(){
      $("#wb_Name_To_Menu").hover(function(){ 
      $("#Layer_to_mainu").css("visibility","visible"); 
      $("#main_mainu > ul").css("display","block");
      $("#Layer_to_mainu").css("width",$("#id_full_name_from_main_menu").width()+"px");
      $("#main_mainu > ul").css("display","none");
    });
    

    That won't display your text but it will update the width of #id_full_name_from_main_menu, you would need to remove the display:none to see your text appear.