Nikos
Nikos

Reputation: 13

preventDefault() doesn't work on image link

i am trying to create a lightbox for my website but i got a problem. Since i am not very fluent in jQuery i do a lot of mistakes. One of them is that i cant make preventDefault() work for both text and image links! Check the following code

HTML code:

Text link: <a class='ultbox_simg' href='images/1.jpg'>Image 1</a>
Image link: <a href='images/1.jpg'><img src="images/1t.jpg" /></a> 

jQuery script:

$(document).ready(function ($){

    $(".ultbox_simg").click(function (obj){
        obj.preventDefault();
        var img_link=$(this).attr("href");

    });
});

Upvotes: 1

Views: 2587

Answers (5)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

With $('.ultbox_simg') you select the elements that have the class ultbox_simg and bind the click handler to them.

But the image link does not have this class assigned..

so

<a class="ultbox_simg" href="images/1.jpg"><img src="images/1t.jpg" /></a> 

Upvotes: 0

Ibu
Ibu

Reputation: 43850

here is what you need to change:

Image link: <a href='images/1.jpg'><img src="images/1t.jpg" /></a> 

to:

Image link: <a href='images/1.jpg'  class='ultbox_simg'><img src="images/1t.jpg" /></a>

now it will work

Upvotes: 0

Finnnn
Finnnn

Reputation: 3580

You need to add the class .ultbox_simg to your image link.

<a class='ultbox_simg' href='images/1.jpg'><img src="images/1t.jpg" /></a> 

Upvotes: 0

Piotr M&#252;ller
Piotr M&#252;ller

Reputation: 5558

You should also prevent default action on:

<a href='images/1.jpg'>

So add class for it for example 'noClick' and add to script:

$(".noClick").click(function (obj){
        obj.preventDefault();
});

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

You could add the class also to the img link:

Text link: <a class='ultbox_simg' href='images/1.jpg'>Image 1</a>
Image link: <a class='ultbox_simg' href='images/1.jpg'><img src="images/1t.jpg" /></a> 

$(".ultbox_simg").click(function (obj){
    obj.preventDefault();
    var img_link=$(this).attr("href");

});

or (even better i think), you could traget links with that href:

$('a[href="images\\/1\\.jpg"]').click(function (obj){
    obj.preventDefault();
    var img_link=$(this).attr("href");

});

Upvotes: 3

Related Questions