The images array

In JavaScript all images in a page are stored in the image array, that belongs to the document object.
Each image in a web page has assigned an index, starting from 0.
So, if you wanna access the first image object, you can use the following expression:

var img1 = document.images[0];
You can get the number of image objects with the length property.
The last image in page can be accessed with the following code.
var nr_imgs = document.images.length;
var last_img = document.images[nr_imgs -1];

Accessing images with JavaScript methods

A specific image in page can be accessed more clearly using the method getElementById() or querySelector().

• If the <img> tag has an ID, use the getElementById():
var img = document.getElementById('id_img');
- 'id_img' is the value of the 'id' attribute in <img>.

• If the <img> has a css class (added in the class attribute), you can use querySelector():
var img = document.querySelector('css_sel');
- 'css_sel' is a CSS selector that matches the image.

If the specified css selector matches multiple images, the querySelector() method returns the first image.


- Example, accesses an image with a specified 'class' from a Div. Then, the click on image it will display the 'src' value.
<h4>Example accessing image with querySelector</h4>
<p>Click on the image. It will show in #resp the address from 'src'.</p>
<div id='dv1'> Div<br>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Smile' class='cls_im'/>
</div>
<blockquote id='resp'>#resp</blockquote>

<script>
//gets the 1st image with class .cls_im from #dv1
var img = document.querySelector('#dv1 img.cls_im');

//detect the click on image
img.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = img.src;
});
</script>

Image Object

In JavaScript, every image in the HTML document represents an Image object.
Thr Image object has properties for working with images.
- For example, with the height property you can get or set the image height, and with the width property you can get or set the image width in page.

<h4>Example image sizes</h4>
<p>Each click on the 'Set size' button increases the image height and width by 50%.</p>
<img src='javascript/imgs/smile_gift.png' alt='Smile' height='115' width='130' id='img1'/><br>
<button id='btn1'>Set size</button>

<script>
var img = document.getElementById('img1');
document.getElementById('btn1').addEventListener('click', (ev)=>{
 //gets the image height and width
 let h = img.height;
 let w = img.width;

 //increases height and width by 50%
 img.height = h *1.5;
 img.width = w *1.5;
});
</script>

Properties of the Image Object

alt - returns or sets the value of the 'alt' attribute.
<h4>Example alt</h4>
<p>If you click on the image, it will display at #resp the value of the 'alt' attribute.</p>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Happy Smile' id='im1'/>
<blockquote id='resp'>#resp</blockquote>

<script>
var img = document.getElementById('im1');
img.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = ev.target.alt;
});
</script>
complete - returns True if the browser has finished loading the image, otherwise, False.
<h4>Example complete</h4>
<p>If you click the following button, it adds in page an IMG tag with style 'display:none;'. The image element will be made visible after the browser finishes loading it.</p>
<button id='btn1'>Add img</button>
<blockquote id='resp'>#resp</blockquote>

<script>
var img = document.getElementById('im1');
document.getElementById('btn1').addEventListener('click', (ev)=>{
 //adds image in #resp
 document.getElementById('resp').innerHTML ="<img src='javascript/imgs/smile_gift.png' alt='Smile' style='display:none;' id='im1'/>";

 //check the image load
 document.getElementById('im1').addEventListener('load', (ev)=>{
 //if it is completely loaded, makes it visible
 if(ev.target.complete) ev.target.style.display ='block';
 });
});
</script>
height - returns or sets the value of the 'height' attribute.
<h4>Example height</h4>
<p>If you click on the image, it will display at #resp the value of the 'height' attribute.</p>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Smile' id='im1'/>
<blockquote id='resp'>#resp</blockquote>

<script>
var img = document.getElementById('im1');
img.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = ev.target.height;
});
</script>
isMap - returns True if the image has the 'ismap' attribute, otherwise, False. - The 'ismap' can be added into an image added in an <a> element. When that image is clicked, it sends to server the click coords (to the address from 'href' of that <a> tag).
<a href='page.php'><img src='image.png' ismap/></a>
Sends to server the x/y coords of the click on 'image.png': page.php?x,y
naturalHeight - returns the original height of an image.
<h4>Example height / naturalHeight</h4>
<p>If you click on the image, it will display at #resp the value of the 'height' attribute, and the original height (naturalHeight).</p>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Smile' id='im1'/>
<blockquote id='resp'>#resp</blockquote>

<script>
var img = document.getElementById('im1');
img.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML ='height = '+ ev.target.height +'<br>naturalHeight = '+ ev.target.naturalHeight;
});
</script>
naturalWidth - returns the original width of an image.
<h4>Example width / naturalWidth</h4>
<p>If you click on the image, it will display at #resp the value of the 'width' attribute, and the original width (naturalWidth).</p>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Smile' id='im1'/>
<blockquote id='resp'>#resp</blockquote>

<script>
var img = document.getElementById('im1');
img.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML ='width = '+ ev.target.width +'<br>naturalWidth = '+ ev.target.naturalWidth;
});
</script>
src - returns or sets the value of the 'src' attribute.
<h4>Example src</h4>
<p>If you click on the image, it will display at #resp its name from 'src' address.</p>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Smile' id='im1'/>
<blockquote id='resp'>#resp</blockquote>

<script>
document.getElementById('im1').addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = ev.target.src.match(/[^\/]+$/i)[0];
});
</script>
useMap - returns or sets the value of the 'usemap' attribute of an image. - The usemap attribute sets an image with multiple clickable zones, where each area can open a different address.
See the tutorial from: coursesweb.net/html/image-map
width - returns or sets the value of the 'width' attribute.
<h4>Example width</h4>
<p>If you click on the image, it will display at #resp the value of the 'width' attribute.</p>
<img src='javascript/imgs/smile_gift.png' height='115' width='130' alt='Smile' id='im1'/>
<blockquote id='resp'>#resp</blockquote>

<script>
var img = document.getElementById('im1');
img.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = ev.target.width;
});
</script>

Accessing multiple images added into an HTML element

If you have multiple images into an HTML element, you can access them in JavaScript with one of these methods: getElementsByTagName('img') or querySelectorAll('css_sel') ('css_sel' is a CSS selector that matches the images).
These methods returns an array wih the selected elements, and can be parsed with the for() instruction.


- Example with getElementsByTagName('img'):
//gets all images from a html element with id 'dv1'
var imgs = document.getElementById('dv1').getElementsByTagName('img');

//traveres the images
for(var i=0; i<imgs.length; i++){
 //code to execute for each image
}

- Example with querySelectorAll():
//gets all images with class 'cls_im' from an element with id 'dv1'
var imgs = document.querySelectorAll('#dv1 img.cls_im');

//traveres the images
for(var i=0; i<imgs.length; i++){
 //code to execute for each image
}

Replacing an image with another

If you want to replace an image in page with one from another address, just modify the 'src' value with the new address.

var img = document.getElementById('id_img');
img.src ='addr/another_image.jpg';

- Here is an example. Each click on a buttom will replace an image with other images with address stored into an array.
<h4>Example replacing images</h4>
<p>Click on the following button to replace the image with another from an array with four 'src' addresses.</p>
<img src='javascript/imgs/sunshine.jpg' id='im1' height='235' width='340' alt='Image'/><br>
<button id='btn1'>Replace image</button>

<script>
//array with images
var imgs =['sunshine.jpg', 'spring_dream1.jpg', 'spring_dream2.jpg', 'waterfall.jpg'];
var icm =0; //idexul of the current image

var img = document.getElementById('im1');
document.getElementById('btn1').addEventListener('click', (ev)=>{
 icm++;
 if(icm >= imgs.length) icm =0; //reset to 0 if last img
 img.src ='javascript/imgs/'+ imgs[icm];
});
</script>

Preloading images

In the previous examplel, the browser must wait until the new image is loaded, and then can display it. In case of large images, the loading may take too long. This can be avoided by "preloading images", all images used on the page can be loaded in JavaScript when the page is opened, and will be displayed only when the display command is executed.
To preluad an image, use an instance of the Image object.
Syntax:

var obimg = new Image();
obimg.src ='adresa_img.jpg'; //preluads the image
- In the code above the image is preluaded and can be displayed directly from the 'obimg' object.

Here is an example. An image is changed with other images when the mouse cursor enters and leaves its area.
The images are preluaded with the Image object.
<h4>Example changing image when mouse enters and leaves its area</h4>
<p>Place the mouse over the following image, then move the mouse out of its area.</p>
<img src='javascript/imgs/spring_dream1.jpg' id='im1' height='235' width='340' alt='Image'/>

<script>
//object with images for enter and leave
var imgs ={enter:'spring_dream2.jpg', leave:'spring_dream3.jpg'};
var obimg ={}; //to store preluaded images


//preluads the images from imgs
function preloadImgs(imgs){
 //store each preluaded image in obimg
 for(var k in imgs){
 obimg[k] = new Image();
 obimg[k].src ='javascript/imgs/'+ imgs[k];
 }
}

//calls the function to preluad the images
preloadImgs(imgs);

//registers 'mouseenter' and 'mouseleave' events for img
var img = document.getElementById('im1');
img.addEventListener('mouseenter', (ev)=>{
 //adds the preluaded image from obimg
 img.src = obimg.enter.src;
});
img.addEventListener('mouseleave', (ev)=>{
 //adds the preluaded image from obimg
 img.src = obimg.leave.src;
});
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute indicates that an input field must be filled out before submitting?
required="required" autofocus="autofocus" placeholder="text"
<input type="text" name="name1" required="required" />
Which CSS method increases or decreases the size of the HTML element (including its content)?
translate() scale() skew()
#some_id:hover {
  transform: scale(2, 1.5);
  -ms-transform: scale(2, 1.5);    /* IE 9 */
  -moz-transform: scale(2, 1.5);   /* Firefox */
}
Click on the Date object method that returns the day of the month.
setDate() getMonth() getDate()
var rightnow = new Date();
var day = rightnow.getDate();
alert(day);
Which function is used to upload a file on server?
is_file() move_uploaded_file() fopen()
if(move_uploaded_file($_FILES["field_name"]["tmp_name"], "dir/file_name")) {
  echo "The file succesfully uploaded";
}
Image object

Last accessed pages

  1. JQZoom Image Magnifier (9940)
  2. SHA512 Encrypt hash in JavaScript (10932)
  3. Add Pause in JavaScript script (9962)
  4. Redirects (758)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (42971)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (417)
  2. Read Excel file data in PHP - PhpExcelReader (331)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (258)
  4. PHP getElementById and getElementsByTagName (210)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (199)