6

I'm totally new to JS. I'm trying to make me a bookmarklet that finds all images on a web page and adds a colorful border to them. Then, by clicking on an image I'd like to attach the image path. This is what I've got so far:

javascript:
for (var i= document.links.length; i-->0;) {
    if (document.links[i].getElementsByTagName('img').length!=0) {
        document.links[i].onclick= function() {
           window.open("http://www.example.com/whatever?imgsrc=" + this.src + "");
        };
    }
}

How can I add a border to the images?

Thanks, Bob

Michael
  • 327
  • 2
  • 6
  • 12
  • your English isn't bad. You've only made one big mistake (than instead of then). I've seen worse. By the way, all images of a website or a web page? Those are two different things. –  Mar 01 '11 at 23:18

2 Answers2

2

Try this code:

javascript:for(i=0;i<document.getElementsByTagName('img').length;i++){var imgTag=document.getElementsByTagName('img')[i];imgTag.style.border='2px solid #E8272C';imgTag.onclick=function(){return !window.open(this.src)};}void(0)

Friendly formatted view:

javascript:
for(i=0;i<document.getElementsByTagName('img').length;i++){
    var imgTag=document.getElementsByTagName('img')[i];
    imgTag.style.border='2px solid #E8272C';
    imgTag.onclick=function(){
        return !window.open(this.src);
    }
}void(0)
ahgood
  • 1,847
  • 20
  • 19
  • Thanks for your answer. There is just one thing I'ld like to know: Why does this code dosen't opening an external site? `imgTag.onclick=function(){return !window.open("http://www.myurl.com/#i/"+imgTag.src);}}void(0)` I tried to replace the part in your example. Thanks – Michael Mar 04 '11 at 16:54
  • Just tried on current page, it works fine for image source from external URL(the icon above your comment.) – ahgood Mar 05 '11 at 04:49
  • It's not opening the image I click on. I tried on several sites like http://ffffound.com. I just copy pasted your code. What do I wrong? – Michael Mar 07 '11 at 08:43
  • Thank you! So I tried to add a mouse over effect to it. Why is this not working? `imgTag.onMouseOver=function(){imgTag.style.border='20px solid #ff0000';}` That's the last mystery to solve. – Michael Mar 08 '11 at 21:45
0

There is no need to call getElementsByTagName

javascript:(function(){for(var i=0;i<document.images.length;i++){var image=document.images[i];image.style.border='medium solid blue';image.onclick=function(){location.href=this.src;return false;};}})()
Free Consulting
  • 4,300
  • 1
  • 29
  • 50