Chris Sobolewski
Chris Sobolewski

Reputation: 12955

Find if link targets image with javascript/jquery

I am trying to write a script that will find all <a> tags whose target is either a jpg, gif, or png and attach a function to them.

$('a')
    .filter(function(){
        return this.href.match(/*probably some regex here?*/)
    })
    .bind('mouseover', function(){
        alert('foo');
    })

This should work, but I don't know what the regex would look like. If there's a better way, please let me know that as well. Thanks!

Upvotes: 3

Views: 1866

Answers (2)

fozuse
fozuse

Reputation: 784

You may want to check filename with case insensitive regex. Because some files can be ".JPEG" instead of ".jpeg". So try this:

var file = "life/is/short.JPG"

if (/(jpg|jpeg|gif|png)$/i.test(file)) {
    alert("the file is an image");
}
else {
    alert("the file is not an image");
}

Upvotes: 1

Pastor Bones
Pastor Bones

Reputation: 7371

You almost had it!!!

$('a[href]').filter(function() {
  return /(jpg|gif|png)$/.test($(this).attr('href'))
}).bind('mouseover', function(){
  alert('foo');
})

Upvotes: 8

Related Questions