Change alt image with javascript onclick

I have a thumbnail that, when clicked on, enlarges the image on the page. I have this piece of code working by simply modifying .src with onclick. Is there a way to change the alt and title attributes using onclick?

+6
javascript onclick
source share
3 answers

You can use setAttribute or set the property directly. In any case, setAttribute is the standard DOM way of doing this, though.

el.onclick = function() { var t = document.getElementById('blah'); // first way t.src = 'blah.jpg'; t.title = 'new title'; t.alt = 'foo'; // alternate way t.setAttribute('title', 'new title'); t.setAttribute('alt', 'new alt'); t.setAttribute('src', 'file.jpg'); } 
+7
source share

Similar.

 document.getElementById('main_image_id').title = 'new title' document.getElementById('main_image_id').alt = 'new alt' 
+4
source share
 img.onclick = function() { // old fashioned img.src = "sth.jpg"; img.alt = "something"; img.title = "some title"; // or the W3C way img.setAttribute("src", "sth.jpg"); img.setAttribute("alt", "something"); img.setAttribute("title", "some title"); }​; 

Note. No matter which one you use, if you are dealing with standard attributes.

+3
source share

All Articles