I’m having a strange situation here.. I have three links which are loading content with ajax. First time when one of these three links is pressed, the content is sliding down but I want that the next li to animate left/right depending on their position in main menu. Right now they are appended to the #content element.
What I want is to give the loaded content from the start a certain index.. as the index which appear in the main menu..
You can see an example at http://www.openminded.ro/
This is the script I’m using right now:
// JavaScript Document
$(document).ready(function(){
$("#main-menu a").click(function(e){
e.preventDefault();
var $a = $(this);
var $clicked = $a.attr('href').substr(1);
if($('#logo').hasClass('unmoved')) {
$('#logo').animate({marginTop:'30px'}, 500, function(){
$a.removeClass('unmoved').addClass('moved');
});
}
$("#main-menu .active").removeClass('active');
$a.addClass('active');
if($('#content ul li.' + $clicked).length == 0) {
$.ajax({
url: '/resources/ui' + $(this).attr('href') + '.php',
cache: false
}).done(function(html) {
if($('#content ul').html().trim().length == 0) {
$("#content ul").html(html).find('li').slideDown(500);
} else {
$("#content ul").css('width',($("#content ul").width() + 900) + 'px');
$('#content ul').append(html).find('li.' + $clicked);
$a.trigger('click');
}
});
} else {
$('#content ul').animate({left:-$('#content ul li.' + $clicked).index() * 900 + 'px'}, 500, 'easeInQuart');
}
});
});
Right now everything works ok if you press the links in order: About us / Portofolio / Contact but if you start with Portofolio link and then you press About us.. you’ll see that About us is after Portofolio but it must be before it.. I want to set it’s index from the start..
When I load it I want to set About us at index 0, Portofolio 1 and Contact 2 without being dependent if one of these three links has been pressed before
Is there a solution? or I have to do it in hard way?
The problem seems to be with this line:
It is blindly appending the next chunk of text to the end of whatever was there before, so if you click Contact first it will be to the left of About Us.
There are other similar problems that come up too, for example try to double click any one of the links, you will probably see the text loaded twice. (
if($('#content ul').html().trim().length == 0)is still true while the first click&ajax request is in progress, so the second click triggers an ajax request and now there is content twice.)Idea 1
One way you can get around all these problems is to forget about using ajax and just preload everything.
Idea 2
If you need to use ajax…
Since you know there are always 3 sections of text I suggest you pre-load all of the
<li>tags and then fill them in as each button is clicked. I’ve used the.data()method from jquery to link the button to the correct container.your index.php page can start off like: