|
|
|||
Jquery load and superfish
I am a relative novice with Javascript and have spent quite some time trying to improve my website by combining a couple of tutorials from Javascript, the missing manual.
I have succesfully used superfish to generate dropdown menus from a UL. I have also managed to load the HTML for the UL from an external file using the jQuery load() function. The problem occurs when I try to combine the two functions. As soon as I use load() the menu headers are displayed but the superfish script fails to operate. I had been testing the page with Firefox 3.6.10. but when I tried IE 8.0 I was amazed to find that the code worked perfectly! I then tried Opera 10.62 and Safari 5.0.2 both reacted exactly the same as Firefox. Finally, Google Chrome, failed to load the UL. I thought the advantage of using jQuery was to overcome the cross browser inconsistencies. What am I doing wrong? I downloaded jQuery library v1.4.2. 2 Replies
You're encountering this problem because of the order in which the Javascript executes on the page. When you call the Superfish function, a bunch of code is attached to the navigation menu. When you use load() HTML is loaded from another web file. The superfish() function runs BEFORE the HTML code is loaded and added to the DOM. It's kind of like saying "navigation bar do this" and the browser says "what navigation bar, I don't have any navigation bar." Then the nav bar is loaded via AJAX, but by that time it's too late.
You should be able to get it to work by using a "callback" function with load(). For example, say you have an empty <ul> on the page and you're dynamically adding the list items using load(). If the <ul> has an id of nav, and your loading a file named nav_list.html you might have code like this $('#nav').load('nav_list.html', function() { $('#nav').superfish(); }); A callback function runs after some other function completes. So in this case AFTER the nav_list.html is downloaded and added to the DOM, the superfish() function runs. You can read more about load() at the jQuery documentation site: http://api.jquery.com/load/ Hope that helps. --dave mcfarland
Comment by
Graham Millman
: Oct 13 2010 08:13 AM
That's great. The callback function did the trick. You've no idea how much time I'd spent moving code around thinking it was to do with the order it loaded the DOM and ran the scripts.
I am very grateful for your advice. Thanks. One thing though, it now works in Firefox, Opera, Safari, IE but not Google Chrome. It's as if JS is disabled but I checked the settings and it's enabled. Any ideas? |
|||
|