• 0

[JS] Center a menu that is floated left.


Question

I found the following snippet of javascript (uses jQuery) that would allow me to centre a menu/nav that is set to float:left. It seems to work in IE and Opera OK. But in FF and Safari, it works sometimes and other times trips out (keep refreshing the page and it will eventually work/fail). In Chrome it doesn't work at all.

Here is the code:

$(function() {
	var menu_width = $('#nav').css('float', 'left').width();
	$('#nav').css({float : 'none', width : menu_width, margin : '0 auto'});
});

I don't know js so I can't figure out what the problem is. If anyone can help it would be much appreciated.

Here is the page running the code:

http://www.islandrobot.com/vanessa/

Cheers,

Jordan

15 answers to this question

Recommended Posts

  • 0

Sorry, yes I am trying to centre the entire navigation on that blue strip. Without the js it would be aligned to the left. With the js it should be centred.

P.s. I made an edit to my above post and then deleted it. If you saw the edit, just ignore it ;)

  • 0

That would be the easy way out, yes. But I would rather have it centre automatically since the client may add/remove/rename items from the menu at any time which would mean manually recalculating and changing the width. Since they don't know CSS I wouldn't expect them to have to do that.

  • 0

It wasn't the easy way out when I looked over your code but rather the logical solution to your problem based only on your initial post (which didn't say that the menu would actually be dynamic versus static.)

That being said the best bet is to replace float: left for display:inline. Then you can have all list items centered under the unordered list without needing any javascript.

  • 0

That being said the best bet is to replace float: left for display:inline. Then you can have all list items centered under the unordered list without needing any javascript.

I tried this method at first but encountered problems with the drop down menus. I couldn't get them to fall directly under their parent li. Instead, the drop-downs always appeared in the far left corner (beginning of the root ul) regardless of which li you were mousing over (if that makes any sense). I played around with it for a while but couldn't get it to behave the way I wanted.

I also tried using inline-blocks which worked nicely except in FF2 which doesn't support it. -moz-inline-box didn't help either because of the drop-down menus.

JS seems like my last and only resort to have a centred, horizontal menu of unknown width and with drop down menus.

  • 0

Hi sweetsam. That seems to have helped a little bit. It at least works in Chrome now sometimes where as it didn't work at all before. However, it is still failing on some page loads. If you keep refreshing the page in FF/Chrome/Safari (Opera and IE seem stable) it will eventually get screwed up. Is this a common problem with javascript? Could it be a jQuery issue?

  • 0

An update:

I've almost got it pegged now. Previously I did not have float:left; applied to #nav (which is the ul). I only had it applied to the li's. As I understood it, the .css('float', 'left') part of the script was trying to add the float to #nav for me??? Well I took that part out and just added float:left; to #nav in the css. This made #nav wrap snug around the li's and allowed for the correct width to be determined. Now everything seems stable in FF.

EDIT: FF is still giving the same problem as Chrome and Safari

Chrome and Safari still seem to be having slight problems getting it perfectly centred though. Sometimes its a bit more to the left and other times it's perfect.

I have also simplified the script down to this:

$(function() {
        var mleft = Math.round(($('#nav-wrap').width() - $('#nav').width()) * 0.5);
        $('#nav').css('margin-left', mleft);
});

  • 0

Ok I am pretty sure now that the problem is a simple matter of the calculations being made before the navigation part of the page has been drawn up (if that makes sense). I realize this as some testing showed that occasionally $('#nav-wrap').width() and $('#nav').width() were returning results like 1407 and 1367 respectively. This would also explain why the browsers with faster javascript engines are having the problem more frequently. How can I make sure that the calculations are only made AFTER the html/css has been drawn up by the browser?

Sorry for all these posts, as I said in the beginning I don't know much about js so figuring this out is a whole learning experience :/

EDIT: HOT DAMN.... I guess it was as simple as moving my stylesheet above the javascript. All good now :)

  • 0

To avoid this kind of problem though you should have done this :


$(document).ready(function() {
$(function() {
 var mleft = Math.round(($('#nav-wrap').width() - $('#nav').width()) * 0.5);
 $('#nav').css('margin-left', mleft);
});});

It ensures any jquery is applied after the dom has been fully parsed, most of the time the effect is instant.

  • 0

I was actually reading up on the .ready() function when I discovered that I could just move the css above the js.

To quote the .ready() page of the jQuery site that tipped me off:

When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

Is it still advisable that I also use the .ready any ways?

  • 0

Yes. But you were using it already. Following pieces of code are equivalent. The problem was being caused by the fact that the styles were being applied after the script swung in to action. Scripts should always be the last to run and more importantly should be included after the stylesheets. Sometimes you will see scripts attached to the end of the document for the same reason.


$(function(){

})

and

$(document).ready(function(){

})

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • >defenders of AI-generated artworks often claim that AI is just a tool It is not. It is the inhuman artist replacement. The human writing the prompt is the employer/manager requesting the work product of the artist -- a supervisory/descriptive job that doesn't carry with it any rights to the copyright of that work product at all. And since AI is not human itself, it can't gain copyright for anything it is asked to regurgitate or hallucinate, so it can't transfer that copyright to the employer/manager/human who asked for the output. This was all legally reaffirmed last year. So, no, while there are AI tools, AI slopware generation is NOT a "tool" in the legal definition of that word.
    • As long as i get to play GTA 6 before it ends 😂😂
    • Google is opening the world's first AI museum in Los Angeles by Ivan Jenic Image via: Google Ever since AI image generators went mainstream, the debate over whether AI-generated art is real art hasn't let up. Those who don’t consider AI to be art say that if a machine does the creating and anyone can prompt it, there’s no skill involved, and therefore no art is produced. The counter-argument is equally persistent, as defenders of AI-generated artworks often claim that AI is just a tool, and that every major technological breakthrough, like the camera or the computer, was met with the same skepticism before eventually being accepted as a legitimate creative medium. Google’s position in this debate is clear. Which is no surprise, as the company is investing billions in AI infrastructure. And now, in efforts to encourage people to use its AI even more, Google is opening Dataland on June 20, which it's calling the world's first AI arts museum. Located inside The Grand LA, a Frank Gehry-designed building in Los Angeles, the museum spans 25,000 square feet. The museum is built around a collaboration with media artist Refik Anadol, who has worked with Google since 2016. The inaugural exhibition is called Machine Dreams: Rainforest, and is powered by an AI model trained on “an extensive dataset of the natural world.” It generates 1.2 billion pixels of visuals in real time and reacts to visitors dynamically. The space also generates soundscapes, real-time emotion sensing, and algorithmically produced scents. Image via: Refik Anadol Studio / Google Google says that the museum is powered by its Gemini models, which run on Google Cloud. So, everything is generated inside one of Google’s AI data centers and is streamed to the museum. Alongside the museum opening, Google Arts & Culture is funding an AI Artist Residency, giving four artists $25,000 grants each, along with mentorship from Refik Anadol Studio and access to Google's machine learning tools. Their work will be shown at Dataland and on the Google Arts & Culture website later this year. Google’s AI museum will undoubtedly initiate a fired-up debate on social media, and we can’t wait to see the first reactions. Via: Smithsonian Magazine
    • Calling GTA 6 overhyped crap doesn’t make you edgy, it just makes you sound like someone who hasn’t enjoyed anything since the PS2 era.
    • I’m not arguing whether Rockstar likes money. Obviously, they do, they’re a business. I’m saying this isn’t new. They’ve always launched console first. This is just how Rockstar operates.
  • Recent Achievements

    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
    • One Month Later
      eurospharma62 earned a badge
      One Month Later
    • Week One Done
      With What earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      570
    2. 2
      +Edouard
      178
    3. 3
      PsYcHoKiLLa
      74
    4. 4
      Michael Scrip
      68
    5. 5
      neufuse
      64
  • Tell a friend

    Love Neowin? Tell a friend!