1

I have a number of image items with class 'more-info' that should respond to click event and load ajax content to a div, however this works find for the first time, but when I click in any other image for the second time, it triggers 2 clicks for third time it triggers 3 clicks and so on.

Here is the html:

<div id="test" style="display:none"></div>

<div class="image-item">
    <img class="more-info" src="/site/uploads/documents/_thumb01.jpg"  path="/site/auto/1" />
</div>
<div class="image-item">
    <img class="more-info" src="/site/uploads/documents/_thumb02.jpg" path="/site/auto/2" />
</div>
<div class="image-item">
    <img class="more-info" src="/site/uploads/documents/_thumb03.jpg" path="/site/auto/4" />
</div>

And ajax handdler:

  $(function () {  
    $('.more-info').click(function(event) { 
            event.preventDefault()

            url = $(this).attr('path');
                $('#test').load(url, function(){
                alert('loaded: '+ url)
            })
    })
});
2
  • put css code in your question Commented Aug 26, 2012 at 13:37
  • Check this for different solutions for your problem - stackoverflow.com/questions/2024389/… Commented Aug 26, 2012 at 13:39

1 Answer 1

1

I think you are loading an entire html page again including the javascript. So for each click you will have another event handler added.

So instead of loading the entire page you could only load a specific part of the page:

$('#test').load(url + ' #somediv', function(){

See jQuery's load example in the docs.

Or you should just make sure the result of the request only contains the part you need.

One last possible solution would be to .unbind() the event before loading the content:

$(function () {  
    $('.more-info').click(function(event) { 
        event.preventDefault();

        // for caching the element, because it will be referenced twice
        var $elem = $(this);

        url = $elem.attr('path');

        $elem.unbind('click');
        $('#test').load(url, function() {
            // used console.log which is cleaner imho
            console.log('loaded: '+ url);
        });
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. The problem was reloading the js file again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.