Reputation: 9939
I have a number of list items that contain images within links. When one of these links is clicked, I want to get containing li
's rel attribute only, without following the click event though. Following the event through currently opens the link image up in a new page which I do not want.
I have tried return false;
within my function but this doesnt work (see below). I have also tried this on the actual link in the mark up but I would rather not do this as this isn't best practice.
$('a.main-img').click(function (){
var liRel = $(this).closest('li').attr('rel');
var relNumber = $('#banner-holder').find('img').attr('id', liRel);
rotatePics(relNumber);
return false;
});
Upvotes: 3
Views: 48323
Reputation: 6277
Note though that preventDefault
wont stop the event from bubbling up the DOM and being actioned by and event on one of the parents. The function event.StopPropagation
will do that. PreventDefault stops the default action of the link. Return false actually does both so using preventDefault won't be an exact functional replication of return false.
This SO question gives a comprehensive run through.
Probably won't make a difference in this case but when it does it has really confused me in the past
Upvotes: 7
Reputation: 10619
You should learn about event.preventDefault()
and event.stopPropagation()
event.preventDefault()
event.stopPropagation()
Upvotes: 2
Reputation: 100175
Try:
$('a.main-img').click(function (evt){ evt.preventDefault();
Upvotes: 0
Reputation: 666
http://api.jquery.com/event.preventDefault/
Read, here you have an example.
EDIT: Your corrected code will be like this:
$('a.main-img').click(function (event){
event.preventDefault();
var liRel = $(this).closest('li').attr('rel');
var relNumber = $('#banner-holder').find('img').attr('id', liRel);
rotatePics(relNumber);
});
Upvotes: 0