April 11, 2012

Return false not working sometimes

Question by Vladimir

I have a page with photo gallery http://dev.dolina-imeniy.ru/fotogalereya/kp_usadba_tishnevo/
I use this to bind click event and return it false

$('a.link_photo').click(function(e) {
var new_img = $(this).attr('href');
var photo_title = $(this).attr('title');
var photo_info = $('.photo_info', this).html();
$('#photo_view img').attr({
    src : new_img
});
$('#photo_title').html(photo_title);
$('#photo_info').html(photo_info);
return false;
    });

But on some images it not work! Why it appears?

Try click on 10 image (ut-1-foto.jpg) in my example to see it.

Answer by c9220

The reason for this is that the function only binds to the elements that are already in existent when it is called. Every link created after the the document has loaded will not be bound to this function. To listen for the creation of these elements and to then bind the function to them, you could use the jQuery plugin liveQuery. I hope that helps.

Answer by Starx

For some reason you code is breaking, so it does not reach to return false.

You can use e.preventDefault(); to stop the default action

e.preventDefault();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!