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:
length
property.A specific image in page can be accessed more clearly using the method getElementById()
or querySelector()
.
getElementById()
:
querySelector()
:
If the specified css selector matches multiple images, the querySelector()
method returns the first image.
<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>
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>
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.<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.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>
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.
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 }
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 }
If you want to replace an image in page with one from another address, just modify the 'src
' value with the new address.
<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>
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:
<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>
<input type="checkbox" name="a_name" value="value" checked="checked" />
#id { background:url("path_to_image.png"); background-size:contain; background-repeat:no-repeat; }
var rest8_7 = 8 % 7; alert(rest8_7);
$nr = ceil(3.5); echo $nr; // 4