Jump to content

Open Image In New Window


Welcome

Recommended Posts

Alright, guys. So I am trying to write a function that will open all my images in a new window when you click on them. Here is the code:

function imgWindow(x) {	// Use "this" as argument	var images = document.getElementsByTagName("img");	for (i = 0; i < images.length; i++) {		window.open(x.src);	}}document.getElementsByTagName("img").onClick = imgWindow(this);

I had this working before by manually adding onClick to all my image tags in HTML. Now I am trying to automate it. So is there a way to get images to open up in a new window automatically? Would it be better to just edit the properties of the image tags via innerHTML? As you can probably tell I just started writing JavaScript, sorry if I am missing something obvious.Any advice would be appreciated and it does not have to be in JavaScript. I just thought about having PHP go through content and when it finds an image to put anchors around it. I'm not sure if PHP can open new windows though (I'm looking into this). This problem has me stumped. =(Thanks in advance.tl;drHow do I tell JS to run code only after an image has been clicked, without having to add "onclick" to img tags.

Link to comment
Share on other sites

You can use addEventListner() to bind an event (using e.g. a loop and getElementsByTagName()).

Link to comment
Share on other sites

This line isn't going to work:

document.getElementsByTagName("img").onClick = imgWindow(this);

What you're doing there is assigning a single click event handler to a NodeList object. A NodeList doesn't have any instance on the page, you can't click on it. It's an abstract object with pointers to a series of nodes on the page.What you need to do is go through each element of the nodelist and add the event handler to it:

var img = document.getElementsByTagName("img");for (var i=0; i < img.length; i++) {  document.getElementsByTagName("img")[i].onclick = imgWindow;}

Your second mistake is this:document.getElementsByTagName("img").onClick = imgWindow(this);You're running the function right there and assigning the return value of the function to the event handler, which isn't going to work. Notice my previous example:document.getElementsByTagName("img").onclick = imgWindow;There are no parethesis ( ) on imgWindowThe next problem is this function:

function imgWindow(x) {	// Use "this" as argument	var images = document.getElementsByTagName("img");	for (i = 0; i < images.length; i++) {		window.open(x.src);	}}

When you run the function, all the windows will open all at once, that's what you're telling it to do.You should read this article: http://www.quirksmode.org/js/introevents.html

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...