user1836966
user1836966

Reputation:

My link doesnt work, when using ajax & jquery to open it

I have some div elements on my page. In the main div, content is loaded via AJAX using jQuery when links are clicked. This works perfectly when i click links that are not in the main div. But when I have a link in the main div that has been loaded via AJAX, they just don't work. I have no idea why. Here's an example:

I have a link. I gave it the class products so jQuery knows which content to load. So my link looks like this:

<a href="javascript:;" class="products">products</a> 

I've put href="javascript:;" because for me href="#" doesn't work and I need a href so some CSS will work.

What can be the problem?

Upvotes: 1

Views: 189

Answers (4)

user1836966
user1836966

Reputation:

the solution with .live worked for me.

here is the jquery code that i use now:

here is my code. sorry that i forgot to post it!

    <script>
$(document).ready(function() {
    $('.sofas').live('click',function() {
    $('#content-shown , #pics').animate({opacity:0},250,function() {

    $('.content-loading').fadeIn(250, function() {
    $('#navigation_all , #content-shown').css("height","6600px");
    $('#pics').load('content.html #sofas-bild').animate({opacity:1},250);
    $('#content-shown').load('content.html #sofas', function() {
    $('.content-loading').fadeOut(250, function() {

        $('#content-shown').animate({opacity:1},250);

    });
    });
    });
    });
            });
            });


</script>

before that, i got .click(function() { instead of .live....

Upvotes: 0

Michael Antonius
Michael Antonius

Reputation: 972

JQuery API official suggest to all users to use .live() for this case,

Which the syntax like this:

$('a.products').live('click',function() {
   // do what you want
});

Good luck

Upvotes: 0

Hiren Desai
Hiren Desai

Reputation: 1091

well, When you are putting href="#", the page is actually reloads with the url being upended with # sign. you need to put return false at the end of click event to stop reloading and all will work fine. else you can do that in href as well.
How, that you need to find out I guess it has to be like href="javascript:return false;"

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337580

Without seeing your actual code I'm guessing, but more often that not problems like this are caused because you are assigning the click handler on load, and not re-assigning them when the new div elements are appended to the page.

To get around this use a delegated event handler, like this:

$('#parentDiv').on('click', 'a', function() {
    // do your thing in here
});

Upvotes: 4

Related Questions